Skip to content

class_grid_factory.py

Contains class with strategies to fill a grid with different properties.

GridFactory

Give parameters and in function of them, create a grid.

Attributes

self.__yaml : ParseYaml
The parsed ".yml" file.

self.__script_arg : ArgumentParser
Script arguments.

self.__system : md.Universe
The parsed molecule by MDAnalysis.

self.__grid_arg : dict
A dictionary containing argument to generate a Grid object.

self.__resolution_is_none : bool
True if one resolution (x, y or z) is None. Else, False.

Source code in src/smiffer/grid/class_grid_factory.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
class GridFactory:
    """Give parameters and in function of them, create a grid.

    Attributes
    ----------
    self.__yaml : `ParseYaml`
        The parsed ".yml" file.

    self.__script_arg : `ArgumentParser`
        Script arguments.

    self.__system : `md.Universe`
        The parsed molecule by MDAnalysis.

    self.__grid_arg : `dict`
        A dictionary containing argument to generate a `Grid` object.

    self.__resolution_is_none : `bool`
        `True` if one resolution (x, y or z) is `None`. Else, `False`.
    """

    def __init__(self, yaml, argument):
        """Generates a grid object in function of given arguments and
        parameters.

        Parameters
        ----------
        yaml : `ParseYaml`
            The parsed yaml file with parameters.

        argument : `ArgumentParser`
            The parsed arguments.

        Raises
        ------
        ValueError
            Thrown when the parameters "box_area_mode" is wrong or when there
            is no atoms that are selected.
        """
        self.__yaml = yaml
        self.__script_arg = argument

        # Defining the system.
        warnings.filterwarnings("ignore", module="MDAnalysis.*")
        self.__system: md.Universe = md.Universe(self.__script_arg.input)
        self.__grid_arg: dict = {}

        self.__resolution_is_none: bool = (
            self.__yaml["box_resolution_x"]
            and self.__yaml["box_resolution_y"]
            and self.__yaml["box_resolution_z"]
        ) is None

        # Using computation method linked to "whole" mode.
        if self.__yaml["box_area_mode"] == "whole":
            self.__whole()
        # Using computation method linked to "pocket_sphere" mode.
        elif self.__yaml["box_area_mode"] == "pocket_sphere":
            self.__pocket_sphere()
        # Throw an error when the "pocket_sphere" has a value different from the
        # expected ones. These are included in ["whole", "pocket_sphere"].
        else:
            raise ValueError(
                '[Err##] The "box_area_mode" in yaml file is '
                'wrong and should be included in "["whole", '
                '"pocket_sphere"]". Actual value is '
                f"{self.__yaml['box_area_mode']}"
            )

        # Check the number of atoms in the made selection.
        nb_atom: int = len(self.__grid_arg["molecule"])

        if nb_atom < 1:
            raise ValueError(
                "[Err##] Applying the given parameters, no atoms "
                "in the PDB were selected. Please check the "
                "parameters or the input files."
            )

        # Print the number of selected atoms in verbose mode.
        if self.__script_arg.verbose:
            print(f"> There are {nb_atom} atoms that are selected.")

        hydrogen_atoms: md.AtomGroup = self.__system.select_atoms(
            f"{self.__yaml['other_macromolecule']} and name H*"
        )

        self.__grid_arg["use_structure_hydrogens"] = len(hydrogen_atoms) > 0

        if self.__grid_arg["use_structure_hydrogens"]:
            # Temporary universe that excludes any unwanted atoms
            # (like ions with undefined vdw radii)…
            universe: md.Universe = md.Merge(
                self.__grid_arg["molecule"], hydrogen_atoms
            )

            if hasattr(universe._topology, "bonds"):
                universe._topology.bonds.types = list(
                    universe._topology.bonds.types
                )

            # …so that there are no problems with the bond guessing
            universe.guess_TopologyAttrs(to_guess=["bonds"])
            self.__grid_arg["molecule_with_h"] = universe.atoms

    def __whole(self):
        """Set a grid for the "whole" mode.

        Parameters
        ----------
        resolution : `np.ndarray`
            The chosen grid resolution.
        """
        pos: np.ndarray = self.__system.coord.positions

        # Min and max coordinates.
        coord: list = [
            np.min(pos, axis=0) - self.__yaml["box_extra_size"],
            np.max(pos, axis=0) + self.__yaml["box_extra_size"],
        ]

        molecule: str = self.__yaml["other_macromolecule"]

        resolution, delta = self.__resolution_delta(
            box_size=coord[1] - coord[0]
        )

        # Setting the grid parameters.
        self.__grid_arg: dict = {
            "delta": delta,
            "resolution": resolution,
            "coord": coord,
            "molecule": self.__system.select_atoms(
                f"{molecule} and not (name H*)"
            ),
            "molecule_broad": self.__system.select_atoms(
                f"{molecule} and not (name H*)"
            ),
            "use_structure_hydrogens": False,
            "molecule_with_h": None,
        }

    def __pocket_sphere(self):
        """Set a grid for the "pocket_sphere" mode.

        Parameters
        ----------
        resolution : `np.ndarray`
            The chosen grid resolution.
        """
        cog: np.ndarray = np.array(
            [
                self.__yaml["box_center_x"],
                self.__yaml["box_center_y"],
                self.__yaml["box_center_z"],
            ]
        )

        radius: float = self.__yaml["box_radius"]

        # Make a general selection with the last parameter to change.
        # This while go from f"{x} {{}}" to "0 {}" for instance.
        select: str = (
            f"{self.__yaml['other_macromolecule']} and not (name H*) and point "
            f"{cog[0]} {cog[1]} {cog[2]} {{}}"
        )

        coord: list = [cog - radius, cog + radius]

        resolution, delta = self.__resolution_delta(
            box_size=coord[1] - coord[0]
        )

        # Setting the grid parameters.
        self.__grid_arg: dict = {
            "delta": delta,
            "resolution": resolution,
            # Min and max coordinates.
            "coord": coord,
            # Modify the last parameter to be the radius.
            "molecule": self.__system.select_atoms(select.format(radius)),
            # Modify the last parameter to be the radius + the trimming atom
            # minimum distance.
            "molecule_broad": self.__system.select_atoms(
                select.format(
                    radius + self.__yaml["trimming_distance_atom_minimum"]
                )
            ),
            "use_structure_hydrogens": False,
            "molecule_with_h": None,
        }

    def __resolution_delta(self, box_size: float) -> tuple:
        """Compute the resolution and delta from the box size.

        Parameters
        ----------
        box_size : `float`
            The size of the box.

        Returns
        -------
        `tuple`
            The resolution and delta, both as `np.ndarray`.
        """
        if self.__resolution_is_none:
            delta: np.ndarray = np.array(
                [
                    self.__yaml["box_delta_x"],
                    self.__yaml["box_delta_y"],
                    self.__yaml["box_delta_z"],
                ]
            )

            resolution: np.ndarray = np.rint(box_size / delta).astype(int)
        else:
            resolution: np.ndarray = np.array(
                [
                    self.__yaml["box_resolution_x"],
                    self.__yaml["box_resolution_y"],
                    self.__yaml["box_resolution_z"],
                ]
            )

            delta: np.ndarray = box_size / resolution

        return resolution, delta

    def create_grid(self) -> Grid:
        """To obtain the grid once the factory has computed its parameters.

        Returns
        -------
        `Grid`
            The setted grid.
        """
        return Grid(
            yaml=self.__yaml, argument=self.__script_arg, **self.__grid_arg
        )

__init__(yaml, argument)

Generates a grid object in function of given arguments and
parameters.

Parameters

yaml : ParseYaml
The parsed yaml file with parameters.

ArgumentParser

The parsed arguments.

Raises

ValueError
Thrown when the parameters "box_area_mode" is wrong or when there
is no atoms that are selected.

Source code in src/smiffer/grid/class_grid_factory.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def __init__(self, yaml, argument):
    """Generates a grid object in function of given arguments and
    parameters.

    Parameters
    ----------
    yaml : `ParseYaml`
        The parsed yaml file with parameters.

    argument : `ArgumentParser`
        The parsed arguments.

    Raises
    ------
    ValueError
        Thrown when the parameters "box_area_mode" is wrong or when there
        is no atoms that are selected.
    """
    self.__yaml = yaml
    self.__script_arg = argument

    # Defining the system.
    warnings.filterwarnings("ignore", module="MDAnalysis.*")
    self.__system: md.Universe = md.Universe(self.__script_arg.input)
    self.__grid_arg: dict = {}

    self.__resolution_is_none: bool = (
        self.__yaml["box_resolution_x"]
        and self.__yaml["box_resolution_y"]
        and self.__yaml["box_resolution_z"]
    ) is None

    # Using computation method linked to "whole" mode.
    if self.__yaml["box_area_mode"] == "whole":
        self.__whole()
    # Using computation method linked to "pocket_sphere" mode.
    elif self.__yaml["box_area_mode"] == "pocket_sphere":
        self.__pocket_sphere()
    # Throw an error when the "pocket_sphere" has a value different from the
    # expected ones. These are included in ["whole", "pocket_sphere"].
    else:
        raise ValueError(
            '[Err##] The "box_area_mode" in yaml file is '
            'wrong and should be included in "["whole", '
            '"pocket_sphere"]". Actual value is '
            f"{self.__yaml['box_area_mode']}"
        )

    # Check the number of atoms in the made selection.
    nb_atom: int = len(self.__grid_arg["molecule"])

    if nb_atom < 1:
        raise ValueError(
            "[Err##] Applying the given parameters, no atoms "
            "in the PDB were selected. Please check the "
            "parameters or the input files."
        )

    # Print the number of selected atoms in verbose mode.
    if self.__script_arg.verbose:
        print(f"> There are {nb_atom} atoms that are selected.")

    hydrogen_atoms: md.AtomGroup = self.__system.select_atoms(
        f"{self.__yaml['other_macromolecule']} and name H*"
    )

    self.__grid_arg["use_structure_hydrogens"] = len(hydrogen_atoms) > 0

    if self.__grid_arg["use_structure_hydrogens"]:
        # Temporary universe that excludes any unwanted atoms
        # (like ions with undefined vdw radii)…
        universe: md.Universe = md.Merge(
            self.__grid_arg["molecule"], hydrogen_atoms
        )

        if hasattr(universe._topology, "bonds"):
            universe._topology.bonds.types = list(
                universe._topology.bonds.types
            )

        # …so that there are no problems with the bond guessing
        universe.guess_TopologyAttrs(to_guess=["bonds"])
        self.__grid_arg["molecule_with_h"] = universe.atoms

__pocket_sphere()

Set a grid for the "pocket_sphere" mode.

Parameters

resolution : np.ndarray
The chosen grid resolution.

Source code in src/smiffer/grid/class_grid_factory.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def __pocket_sphere(self):
    """Set a grid for the "pocket_sphere" mode.

    Parameters
    ----------
    resolution : `np.ndarray`
        The chosen grid resolution.
    """
    cog: np.ndarray = np.array(
        [
            self.__yaml["box_center_x"],
            self.__yaml["box_center_y"],
            self.__yaml["box_center_z"],
        ]
    )

    radius: float = self.__yaml["box_radius"]

    # Make a general selection with the last parameter to change.
    # This while go from f"{x} {{}}" to "0 {}" for instance.
    select: str = (
        f"{self.__yaml['other_macromolecule']} and not (name H*) and point "
        f"{cog[0]} {cog[1]} {cog[2]} {{}}"
    )

    coord: list = [cog - radius, cog + radius]

    resolution, delta = self.__resolution_delta(
        box_size=coord[1] - coord[0]
    )

    # Setting the grid parameters.
    self.__grid_arg: dict = {
        "delta": delta,
        "resolution": resolution,
        # Min and max coordinates.
        "coord": coord,
        # Modify the last parameter to be the radius.
        "molecule": self.__system.select_atoms(select.format(radius)),
        # Modify the last parameter to be the radius + the trimming atom
        # minimum distance.
        "molecule_broad": self.__system.select_atoms(
            select.format(
                radius + self.__yaml["trimming_distance_atom_minimum"]
            )
        ),
        "use_structure_hydrogens": False,
        "molecule_with_h": None,
    }

__resolution_delta(box_size)

Compute the resolution and delta from the box size.

Parameters

box_size : float
The size of the box.

Returns

tuple
The resolution and delta, both as np.ndarray.

Source code in src/smiffer/grid/class_grid_factory.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def __resolution_delta(self, box_size: float) -> tuple:
    """Compute the resolution and delta from the box size.

    Parameters
    ----------
    box_size : `float`
        The size of the box.

    Returns
    -------
    `tuple`
        The resolution and delta, both as `np.ndarray`.
    """
    if self.__resolution_is_none:
        delta: np.ndarray = np.array(
            [
                self.__yaml["box_delta_x"],
                self.__yaml["box_delta_y"],
                self.__yaml["box_delta_z"],
            ]
        )

        resolution: np.ndarray = np.rint(box_size / delta).astype(int)
    else:
        resolution: np.ndarray = np.array(
            [
                self.__yaml["box_resolution_x"],
                self.__yaml["box_resolution_y"],
                self.__yaml["box_resolution_z"],
            ]
        )

        delta: np.ndarray = box_size / resolution

    return resolution, delta

__whole()

Set a grid for the "whole" mode.

Parameters

resolution : np.ndarray
The chosen grid resolution.

Source code in src/smiffer/grid/class_grid_factory.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def __whole(self):
    """Set a grid for the "whole" mode.

    Parameters
    ----------
    resolution : `np.ndarray`
        The chosen grid resolution.
    """
    pos: np.ndarray = self.__system.coord.positions

    # Min and max coordinates.
    coord: list = [
        np.min(pos, axis=0) - self.__yaml["box_extra_size"],
        np.max(pos, axis=0) + self.__yaml["box_extra_size"],
    ]

    molecule: str = self.__yaml["other_macromolecule"]

    resolution, delta = self.__resolution_delta(
        box_size=coord[1] - coord[0]
    )

    # Setting the grid parameters.
    self.__grid_arg: dict = {
        "delta": delta,
        "resolution": resolution,
        "coord": coord,
        "molecule": self.__system.select_atoms(
            f"{molecule} and not (name H*)"
        ),
        "molecule_broad": self.__system.select_atoms(
            f"{molecule} and not (name H*)"
        ),
        "use_structure_hydrogens": False,
        "molecule_with_h": None,
    }

create_grid()

To obtain the grid once the factory has computed its parameters.

Returns

Grid
The setted grid.

Source code in src/smiffer/grid/class_grid_factory.py
250
251
252
253
254
255
256
257
258
259
260
def create_grid(self) -> Grid:
    """To obtain the grid once the factory has computed its parameters.

    Returns
    -------
    `Grid`
        The setted grid.
    """
    return Grid(
        yaml=self.__yaml, argument=self.__script_arg, **self.__grid_arg
    )