Define a grid to display properties to export in .ndx files.
Attributes
self.yaml : object
The parsed ".yml" file.
self.__argument : object
Script arguments.
self.resolution : np.ndarray
The resolution of the grid.
self.delta : np.ndarray
The grid deltas.
self.coord : list
Minimum and maximum coordinates of the grid.
self.molecule : md.AtomGroup
The parsed molecule by MDAnalysis.
self.molecule_broad : md.AtomGroup
The parsed molecule by MDAnalysis [[ plus ]], in the case of being in
pocket_sphere mode and doing the occupancy trimming, a little offset,
for better visualization rendering.
self.use_structure_hydrogens : bool
True if the grid should use the structure hydrogens, else False.
Relevant for HBDonors.
self.molecule_with_h : md.AtomGroup | None
The parsed molecule by MDAnalysis with hydrogens, if the grid should
use the structure hydrogens. If not, None.
self.mask : np.ndarray
The boolean mask to trim the grid.
self.__property : list
A list containing properties methods to compute.
self.__trimming : list
A list containing trimming methods to apply on the grid.
self.trimming_coord : np.ndarray
Coordinates using the molecule as a reference. So, each coordinates in
the grid corresponds to the true one in the molecule system.
Source code in src/smiffer/grid/class_grid.py
19
20
21
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335 | class Grid:
"""Define a grid to display properties to export in `.ndx` files.
Attributes
----------
self.yaml : `object`
The parsed ".yml" file.
self.__argument : `object`
Script arguments.
self.resolution : `np.ndarray`
The resolution of the grid.
self.delta : `np.ndarray`
The grid deltas.
self.coord : `list`
Minimum and maximum coordinates of the grid.
self.molecule : `md.AtomGroup`
The parsed molecule by MDAnalysis.
self.molecule_broad : `md.AtomGroup`
The parsed molecule by MDAnalysis [[ plus ]], in the case of being in
`pocket_sphere` mode and doing the occupancy trimming, a little offset,
for better visualization rendering.
self.use_structure_hydrogens : `bool`
`True` if the grid should use the structure hydrogens, else `False`.
Relevant for HBDonors.
self.molecule_with_h : `md.AtomGroup | None`
The parsed molecule by MDAnalysis with hydrogens, if the grid should
use the structure hydrogens. If not, `None`.
self.mask : `np.ndarray`
The boolean mask to trim the grid.
self.__property : `list`
A list containing properties methods to compute.
self.__trimming : `list`
A list containing trimming methods to apply on the grid.
self.trimming_coord : `np.ndarray`
Coordinates using the molecule as a reference. So, each coordinates in
the grid corresponds to the true one in the molecule system.
"""
# pylint: disable=too-many-arguments, too-many-instance-attributes
# Special class that needs a lot of data to be set up. Using a dataclass
# would be unnecessary, as far as it would just simply take more memory
# for nothing.
__KEY: list = ["property", "trimming"]
def __init__(
self,
yaml,
argument,
resolution: np.ndarray,
delta: np.ndarray,
coord: list,
molecule: md.AtomGroup,
molecule_broad: md.AtomGroup,
use_structure_hydrogens: bool,
molecule_with_h: md.AtomGroup | None,
):
"""Initialize a grid object.
Parameters
----------
yaml : `ParseYaml`
The parsed ".yml" file.
argument : `ArgumentParser`
The parsed given arguments.
"""
self.yaml = yaml
self.__argument = argument
self.resolution: np.ndarray = resolution
self.delta: np.ndarray = delta
self.coord: list = coord
self.molecule: md.Universe = molecule
self.molecule_broad: md.Universe = molecule_broad
self.use_structure_hydrogens: bool = use_structure_hydrogens
self.molecule_with_h: md.Universe | None = molecule_with_h
self.mask: np.ndarray = np.zeros(self.resolution, dtype=bool)
self.__property: list = []
self.__trimming: list = []
self.trimming_coord: np.ndarray = (
self.coord[0] + np.indices(self.resolution).T * self.delta
)
# pylint: enable=too-many-arguments
def __getitem__(self, key: str) -> list:
"""Return a item linked to this object.
Parameters
----------
key : `str`
A key between "property" or "trimming".
Returns
-------
`list`
The list linked to the asked key.
Raises
------
KeyError
When the key is not "property" or "trimming", throw an error.
"""
if key == "property":
return self.__property
if key == "trimming":
return self.__trimming
raise KeyError(
f'[Err##] Key "{key}" does not exist. Only choices '
f'are "{self.__KEY}".'
)
def __setitem__(self, key: str, strategy: object):
"""Define an value linked to a specific key.
Parameters
----------
key : `str`
The key to set.
strategy : `object`
The properties or trimming strategies to set.
Raises
------
TypeError
You should only do:
```py
>>> object["key"] += [strategy]
```
with this object, and not:
```py
>>> object["key"] = [strategy]
```
KeyError
When the key is not "property" or "trimming", throw an error.
"""
if strategy not in [self.__property, self.__trimming]:
raise TypeError(
'[Err##] You cannot add a strategy using "=", '
'but only with "+=".'
)
if key == "property":
self.__property: list = strategy
elif key == "trimming":
self.__trimming: list = strategy
else:
raise KeyError(
f'[Err##] Key "{key}" does not exist. Only'
f'choices are "{self.__KEY}".'
)
def launch_trimming(self):
"""Launch the trimming strategies."""
if self.__trimming == []:
if self.__argument.verbose:
print("> No trimming method given.")
return None
for trimming in tqdm(self.__trimming, desc=" TRIMMING THE GRID"):
trimming.trim_box(grid_object=self)
# Delete a trimming strategy after being used.
del trimming
# Delete this, because it is now useless.
del self.__trimming
return None
def compute_property(self, date: str):
"""Launch the properties strategies and write the OpenDX files.
Parameters
----------
atom_constant : `AtomConstant`
An object containing constant linked to atoms.
date : `str`
The launching time.
Raises
------
ValueError
No properties strategies were defined, throw an error.
"""
if self.__property == []:
raise ValueError(
"[Err##] You must specify at least one property strategy."
)
# ======
# Header
# ======
# Adding grid data.
resolution: str = (
f"{self.resolution[0]} {self.resolution[1]} "
f"{self.resolution[2]}"
)
format: str = self.yaml["other_volume_format"]
# The header.
header: str = (
"# OpenDX density file written by write_dx()\n"
f"object 1 class gridpositions counts {resolution}\n"
f"origin {self.coord[0][0]:6f} {self.coord[0][1]:6f} "
f"{self.coord[0][2]:6f}\n"
f"delta {self.delta[0]:5f} 0 0\n"
f"delta 0 {self.delta[1]:5f} 0\n"
f"delta 0 0 {self.delta[2]:5f}\n"
f"object 2 class gridconnections counts {resolution}\n"
'object 3 class array type "float" rank 0 items '
f"{np.prod(self.resolution)} data follows"
)
# ======
# Footer
# ======
footer: str = (
"{}\n"
'attribute "dep" string "positions"\n'
'object "density" class field\n'
'component "positions" value 1\n'
'component "connections" value 2\n'
'component "data" value 3'
)
for property_i in tqdm(self.__property, desc="COMPUTING PROPERTIES"):
if self.__argument.verbose:
print(property_i)
# Create the grid.
grid: np.ndarray = np.zeros(self.resolution, dtype=np.half)
# Compute properties inside the grid.
property_i.populate_grid(grid=grid, grid_object=self)
# Trim the grid.
grid[self.mask] = 0
path: str = (
f"{self.__argument.output}/{date}_" f"{property_i.name()}.{format}"
)
# ============
# File writing
# ============
if self.yaml["other_volume_format"] == "dx":
self.save_dx(path=path, grid=grid, header=header, footer=footer)
elif self.yaml["other_volume_format"] == "mrc":
self.save_mrc(path=path, grid=grid)
def save_dx(self, grid: np.ndarray, path: str, header: str, footer: str):
grid_size: int = np.prod(grid.shape)
n_row: int = grid_size // 3
# pylint: disable=unbalanced-tuple-unpacking
# It is balanced, pylint, you know…
format_grid, extra_line = np.split(grid.flatten(), [3 * n_row])
# pylint: enable=unbalanced-tuple-unpacking
format_grid: np.ndarray = format_grid.reshape(n_row, 3)
extra_line: np.ndarray = extra_line.reshape(1, extra_line.shape[0])
# Converting the extra line into a string.
extra_line = " ".join(np.round(extra_line[0], 3).astype(str))
# ============
# File writing
# ============
with open(path, "wb") as file:
np.savetxt(
fname=file,
X=format_grid,
fmt="%.3f",
delimiter=" ",
header=header,
footer=footer.format(extra_line),
comments="",
)
def save_mrc(self, grid: np.ndarray, path: str):
data = grid.T
with mrc.mrcfile.new(path) as mrc_file:
mrc_file.set_data(data.astype(np.float32)) # mrc is very picky with the allowed data types
mrc_file.voxel_size = self.delta.tolist()
mrc_file.header["origin"]['x'] = self.coord[0][0]
mrc_file.header["origin"]['y'] = self.coord[0][1]
mrc_file.header["origin"]['z'] = self.coord[0][2]
mrc_file.update_header_from_data()
mrc_file.update_header_stats()
|
__getitem__(key)
Return a item linked to this object.
Parameters
key : str
A key between "property" or "trimming".
Returns
list
The list linked to the asked key.
Raises
KeyError
When the key is not "property" or "trimming", throw an error.
Source code in src/smiffer/grid/class_grid.py
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 | def __getitem__(self, key: str) -> list:
"""Return a item linked to this object.
Parameters
----------
key : `str`
A key between "property" or "trimming".
Returns
-------
`list`
The list linked to the asked key.
Raises
------
KeyError
When the key is not "property" or "trimming", throw an error.
"""
if key == "property":
return self.__property
if key == "trimming":
return self.__trimming
raise KeyError(
f'[Err##] Key "{key}" does not exist. Only choices '
f'are "{self.__KEY}".'
)
|
__init__(yaml, argument, resolution, delta, coord, molecule, molecule_broad, use_structure_hydrogens, molecule_with_h)
Initialize a grid object.
Parameters
yaml : ParseYaml
The parsed ".yml" file.
ArgumentParser
The parsed given arguments.
Source code in src/smiffer/grid/class_grid.py
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 | def __init__(
self,
yaml,
argument,
resolution: np.ndarray,
delta: np.ndarray,
coord: list,
molecule: md.AtomGroup,
molecule_broad: md.AtomGroup,
use_structure_hydrogens: bool,
molecule_with_h: md.AtomGroup | None,
):
"""Initialize a grid object.
Parameters
----------
yaml : `ParseYaml`
The parsed ".yml" file.
argument : `ArgumentParser`
The parsed given arguments.
"""
self.yaml = yaml
self.__argument = argument
self.resolution: np.ndarray = resolution
self.delta: np.ndarray = delta
self.coord: list = coord
self.molecule: md.Universe = molecule
self.molecule_broad: md.Universe = molecule_broad
self.use_structure_hydrogens: bool = use_structure_hydrogens
self.molecule_with_h: md.Universe | None = molecule_with_h
self.mask: np.ndarray = np.zeros(self.resolution, dtype=bool)
self.__property: list = []
self.__trimming: list = []
self.trimming_coord: np.ndarray = (
self.coord[0] + np.indices(self.resolution).T * self.delta
)
|
__setitem__(key, strategy)
Define an value linked to a specific key.
Parameters
key : str
The key to set.
object
The properties or trimming strategies to set.
Raises
TypeError
You should only do:
>>> object["key"] += [strategy]
with this object, and not:
>>> object["key"] = [strategy]
KeyError
When the key is not "property" or "trimming", throw an error.
Source code in src/smiffer/grid/class_grid.py
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 | def __setitem__(self, key: str, strategy: object):
"""Define an value linked to a specific key.
Parameters
----------
key : `str`
The key to set.
strategy : `object`
The properties or trimming strategies to set.
Raises
------
TypeError
You should only do:
```py
>>> object["key"] += [strategy]
```
with this object, and not:
```py
>>> object["key"] = [strategy]
```
KeyError
When the key is not "property" or "trimming", throw an error.
"""
if strategy not in [self.__property, self.__trimming]:
raise TypeError(
'[Err##] You cannot add a strategy using "=", '
'but only with "+=".'
)
if key == "property":
self.__property: list = strategy
elif key == "trimming":
self.__trimming: list = strategy
else:
raise KeyError(
f'[Err##] Key "{key}" does not exist. Only'
f'choices are "{self.__KEY}".'
)
|
compute_property(date)
Launch the properties strategies and write the OpenDX files.
Parameters
atom_constant : AtomConstant
An object containing constant linked to atoms.
str
The launching time.
Raises
ValueError
No properties strategies were defined, throw an error.
Source code in src/smiffer/grid/class_grid.py
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294 | def compute_property(self, date: str):
"""Launch the properties strategies and write the OpenDX files.
Parameters
----------
atom_constant : `AtomConstant`
An object containing constant linked to atoms.
date : `str`
The launching time.
Raises
------
ValueError
No properties strategies were defined, throw an error.
"""
if self.__property == []:
raise ValueError(
"[Err##] You must specify at least one property strategy."
)
# ======
# Header
# ======
# Adding grid data.
resolution: str = (
f"{self.resolution[0]} {self.resolution[1]} "
f"{self.resolution[2]}"
)
format: str = self.yaml["other_volume_format"]
# The header.
header: str = (
"# OpenDX density file written by write_dx()\n"
f"object 1 class gridpositions counts {resolution}\n"
f"origin {self.coord[0][0]:6f} {self.coord[0][1]:6f} "
f"{self.coord[0][2]:6f}\n"
f"delta {self.delta[0]:5f} 0 0\n"
f"delta 0 {self.delta[1]:5f} 0\n"
f"delta 0 0 {self.delta[2]:5f}\n"
f"object 2 class gridconnections counts {resolution}\n"
'object 3 class array type "float" rank 0 items '
f"{np.prod(self.resolution)} data follows"
)
# ======
# Footer
# ======
footer: str = (
"{}\n"
'attribute "dep" string "positions"\n'
'object "density" class field\n'
'component "positions" value 1\n'
'component "connections" value 2\n'
'component "data" value 3'
)
for property_i in tqdm(self.__property, desc="COMPUTING PROPERTIES"):
if self.__argument.verbose:
print(property_i)
# Create the grid.
grid: np.ndarray = np.zeros(self.resolution, dtype=np.half)
# Compute properties inside the grid.
property_i.populate_grid(grid=grid, grid_object=self)
# Trim the grid.
grid[self.mask] = 0
path: str = (
f"{self.__argument.output}/{date}_" f"{property_i.name()}.{format}"
)
# ============
# File writing
# ============
if self.yaml["other_volume_format"] == "dx":
self.save_dx(path=path, grid=grid, header=header, footer=footer)
elif self.yaml["other_volume_format"] == "mrc":
self.save_mrc(path=path, grid=grid)
|
launch_trimming()
Launch the trimming strategies.
Source code in src/smiffer/grid/class_grid.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208 | def launch_trimming(self):
"""Launch the trimming strategies."""
if self.__trimming == []:
if self.__argument.verbose:
print("> No trimming method given.")
return None
for trimming in tqdm(self.__trimming, desc=" TRIMMING THE GRID"):
trimming.trim_box(grid_object=self)
# Delete a trimming strategy after being used.
del trimming
# Delete this, because it is now useless.
del self.__trimming
return None
|