Skip to content

Commit e075ae1

Browse files
authored
Merge pull request #371 from CCPBioSim/365-add-dask-execution-for-conformationdag
Avoid memory-universe copies during conformational topology discovery
2 parents 5e61a05 + 763079c commit e075ae1

12 files changed

Lines changed: 1775 additions & 123 deletions

File tree

‎CodeEntropy/levels/axes.py‎

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,161 @@ def get_UA_axes(self, data_container, index: int):
216216

217217
return trans_axes, rot_axes, center, moment_of_inertia
218218

219+
def get_UA_axes_from_topology(
220+
self,
221+
*,
222+
u,
223+
residue_atoms,
224+
topology,
225+
box: np.ndarray | None,
226+
):
227+
"""Compute UA axes using cached static topology.
228+
229+
This is the cached-index equivalent of ``get_UA_axes``. It preserves the
230+
frame-dependent numerical calculations, but avoids repeated MDAnalysis
231+
selection strings for heavy atoms, bonded atoms, and UA masses.
232+
233+
Args:
234+
u: Current-frame universe.
235+
residue_atoms: AtomGroup for the parent residue in the current frame.
236+
topology: Cached ``UAAxesTopology`` for this UA bead.
237+
box: Current periodic box lengths. If omitted, ``u.dimensions`` is used.
238+
239+
Returns:
240+
Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
241+
- trans_axes: Translational axes, shape ``(3, 3)``.
242+
- rot_axes: Rotational axes, shape ``(3, 3)``.
243+
- center: Rotation centre, shape ``(3,)``.
244+
- moment_of_inertia: Principal moments, shape ``(3,)``.
245+
246+
Raises:
247+
ValueError: If cached bonded-axis construction fails.
248+
"""
249+
dimensions = (
250+
np.asarray(box, dtype=float)
251+
if box is not None
252+
else np.asarray(u.dimensions[:3], dtype=float)
253+
)
254+
255+
heavy_atoms = u.atoms[topology.residue_heavy_indices]
256+
heavy_atom = u.atoms[int(topology.heavy_atom_index)]
257+
258+
if len(heavy_atoms) > 1:
259+
center = residue_atoms.center_of_mass(unwrap=True)
260+
moment_of_inertia_tensor = self.get_moment_of_inertia_tensor(
261+
center_of_mass=center,
262+
positions=heavy_atoms.positions,
263+
masses=topology.residue_ua_masses,
264+
dimensions=dimensions,
265+
)
266+
trans_axes, _moment_of_inertia = self.get_custom_principal_axes(
267+
moment_of_inertia_tensor
268+
)
269+
else:
270+
make_whole(residue_atoms)
271+
trans_axes = residue_atoms.principal_axes()
272+
273+
center = heavy_atom.position
274+
rot_axes, moment_of_inertia = self.get_bonded_axes_from_topology(
275+
u=u,
276+
heavy_atom=heavy_atom,
277+
topology=topology,
278+
dimensions=dimensions,
279+
)
280+
if rot_axes is None or moment_of_inertia is None:
281+
raise ValueError("Unable to compute bonded axes for cached UA bead.")
282+
283+
logger.debug("Translational Axes: %s", trans_axes)
284+
logger.debug("Rotational Axes: %s", rot_axes)
285+
logger.debug("Center: %s", center)
286+
logger.debug("Moment of Inertia: %s", moment_of_inertia)
287+
288+
return trans_axes, rot_axes, center, moment_of_inertia
289+
290+
def get_bonded_axes_from_topology(
291+
self,
292+
*,
293+
u,
294+
heavy_atom,
295+
topology,
296+
dimensions: np.ndarray,
297+
):
298+
"""Compute UA bonded axes using cached bonded atom indices.
299+
300+
This mirrors ``get_bonded_axes`` but receives precomputed bonded atom
301+
memberships from ``UAAxesTopology`` instead of rediscovering them with
302+
MDAnalysis selection strings inside the frame loop.
303+
304+
Args:
305+
u: Current-frame universe.
306+
heavy_atom: Current-frame heavy atom for the UA bead.
307+
topology: Cached ``UAAxesTopology`` for the UA bead.
308+
dimensions: Simulation box lengths, shape ``(3,)``.
309+
310+
Returns:
311+
Tuple[np.ndarray | None, np.ndarray | None]:
312+
- custom_axes: Custom rotation axes, shape ``(3, 3)``, or ``None``.
313+
- custom_moment_of_inertia: Principal moments, shape ``(3,)``, or
314+
``None``.
315+
"""
316+
if not heavy_atom.mass > 1.1:
317+
return None, None
318+
319+
custom_moment_of_inertia = None
320+
custom_axes = None
321+
322+
heavy_bonded = u.atoms[topology.bonded_heavy_indices]
323+
light_bonded = u.atoms[topology.bonded_light_indices]
324+
ua = u.atoms[topology.ua_atom_indices]
325+
ua_all = u.atoms[topology.ua_all_atom_indices]
326+
327+
if len(heavy_bonded) == 0:
328+
custom_axes, custom_moment_of_inertia = self.get_vanilla_axes(ua_all)
329+
330+
if len(heavy_bonded) == 1 and len(light_bonded) == 0:
331+
custom_axes = self.get_custom_axes(
332+
a=heavy_atom.position,
333+
b_list=[heavy_bonded[0].position],
334+
c=np.zeros(3),
335+
dimensions=dimensions,
336+
)
337+
338+
if len(heavy_bonded) == 1 and len(light_bonded) >= 1:
339+
custom_axes = self.get_custom_axes(
340+
a=heavy_atom.position,
341+
b_list=[heavy_bonded[0].position],
342+
c=light_bonded[0].position,
343+
dimensions=dimensions,
344+
)
345+
346+
if len(heavy_bonded) >= 2:
347+
custom_axes = self.get_custom_axes(
348+
a=heavy_atom.position,
349+
b_list=heavy_bonded.positions,
350+
c=heavy_bonded[1].position,
351+
dimensions=dimensions,
352+
)
353+
354+
if custom_axes is None:
355+
return None, None
356+
357+
if custom_moment_of_inertia is None:
358+
custom_moment_of_inertia = self.get_custom_moment_of_inertia(
359+
UA=ua,
360+
custom_rotation_axes=custom_axes,
361+
center_of_mass=heavy_atom.position,
362+
dimensions=dimensions,
363+
)
364+
365+
custom_axes = self.get_flipped_axes(
366+
ua,
367+
custom_axes,
368+
heavy_atom.position,
369+
dimensions,
370+
)
371+
372+
return custom_axes, custom_moment_of_inertia
373+
219374
def get_bonded_axes(self, system, atom, dimensions: np.ndarray):
220375
r"""Compute UA rotational axes from bonded topology around a heavy atom.
221376

‎CodeEntropy/levels/dihedrals/topology.py‎

Lines changed: 105 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,7 @@ def _discover_group_dihedral_topology(
5959
topologies: list[MoleculeDihedralTopology] = []
6060

6161
for molecule_order, molecule_id in enumerate(molecules):
62-
mol = self._universe_operations.extract_fragment(
63-
data_container, molecule_id
64-
)
62+
mol = self._extract_topology_fragment(data_container, molecule_id)
6563
num_residues = len(mol.residues)
6664
ua_dihedrals_by_residue: dict[int, list[Any]] = {}
6765
residue_dihedrals: list[Any] = []
@@ -90,6 +88,26 @@ def _discover_group_dihedral_topology(
9088

9189
return topologies
9290

91+
def _extract_topology_fragment(self, data_container: Any, molecule_id: Any) -> Any:
92+
"""Return a molecule fragment for topology discovery.
93+
94+
This uses the lightweight AtomGroup extraction helper when available so
95+
static conformational topology discovery does not create a standalone
96+
in-memory universe or copy trajectory frames. The fallback preserves
97+
compatibility with older ``UniverseOperations`` implementations.
98+
99+
Args:
100+
data_container: Source MDAnalysis universe or universe-like container.
101+
molecule_id: Fragment index identifying the molecule to extract.
102+
103+
Returns:
104+
MDAnalysis AtomGroup for the selected molecule
105+
"""
106+
return self._universe_operations.extract_fragment_atomgroup(
107+
data_container,
108+
int(molecule_id),
109+
)
110+
93111
def _select_heavy_residue(self, mol: Any, res_id: int) -> Any:
94112
"""Select heavy atoms in a residue by residue index.
95113
@@ -100,13 +118,15 @@ def _select_heavy_residue(self, mol: Any, res_id: int) -> Any:
100118
Returns:
101119
AtomGroup containing heavy atoms in the residue selection.
102120
"""
103-
selection1 = mol.residues[res_id].atoms.indices[0]
104-
selection2 = mol.residues[res_id].atoms.indices[-1]
121+
residue_atoms = mol.residues[int(res_id)].atoms
122+
selection1 = residue_atoms.indices[0]
123+
selection2 = residue_atoms.indices[-1]
105124

106-
res_container = self._universe_operations.select_atoms(
107-
mol, f"index {selection1}:{selection2}"
125+
res_container = mol.select_atoms(
126+
f"index {selection1}:{selection2}",
127+
updating=False,
108128
)
109-
return self._universe_operations.select_atoms(res_container, "prop mass > 1.1")
129+
return res_container.select_atoms("prop mass > 1.1", updating=False)
110130

111131
def _get_dihedrals(self, data_container: Any, level: str) -> list[Any]:
112132
"""Return dihedral AtomGroups for a container at a given level.
@@ -121,26 +141,93 @@ def _get_dihedrals(self, data_container: Any, level: str) -> list[Any]:
121141
atom_groups: list[Any] = []
122142

123143
if level == "united_atom":
144+
selected_indices = {int(index) for index in data_container.indices}
145+
124146
for dihedral in data_container.dihedrals:
125-
atom_groups.append(dihedral.atoms)
147+
dihedral_atoms = dihedral.atoms
148+
dihedral_indices = {int(index) for index in dihedral_atoms.indices}
149+
150+
if len(dihedral_atoms) == 4 and dihedral_indices.issubset(
151+
selected_indices
152+
):
153+
atom_groups.append(dihedral_atoms)
126154

127155
if level == "residue":
128156
num_residues = len(data_container.residues)
129157
if num_residues >= 4:
130158
for residue in range(4, num_residues + 1):
131-
atom1 = data_container.select_atoms(
132-
f"resindex {residue - 4} and bonded resindex {residue - 3}"
159+
residue1 = data_container.residues[residue - 4]
160+
residue2 = data_container.residues[residue - 3]
161+
residue3 = data_container.residues[residue - 2]
162+
residue4 = data_container.residues[residue - 1]
163+
164+
atom1 = self._atoms_in_source_bonded_to_target(
165+
residue1,
166+
residue2,
133167
)
134-
atom2 = data_container.select_atoms(
135-
f"resindex {residue - 3} and bonded resindex {residue - 4}"
168+
atom2 = self._atoms_in_source_bonded_to_target(
169+
residue2,
170+
residue1,
136171
)
137-
atom3 = data_container.select_atoms(
138-
f"resindex {residue - 2} and bonded resindex {residue - 1}"
172+
atom3 = self._atoms_in_source_bonded_to_target(
173+
residue3,
174+
residue4,
139175
)
140-
atom4 = data_container.select_atoms(
141-
f"resindex {residue - 1} and bonded resindex {residue - 2}"
176+
atom4 = self._atoms_in_source_bonded_to_target(
177+
residue4,
178+
residue3,
142179
)
143-
atom_groups.append(atom1 + atom2 + atom3 + atom4)
180+
181+
dihedral_atoms = atom1 + atom2 + atom3 + atom4
182+
183+
if len(dihedral_atoms) == 4:
184+
atom_groups.append(dihedral_atoms)
185+
else:
186+
logger.debug(
187+
"Skipping residue-level dihedral for local residues "
188+
"%s-%s-%s-%s because it produced %d atoms.",
189+
residue - 4,
190+
residue - 3,
191+
residue - 2,
192+
residue - 1,
193+
len(dihedral_atoms),
194+
)
144195

145196
logger.debug("Level: %s, Dihedrals: %s", level, atom_groups)
146197
return atom_groups
198+
199+
@staticmethod
200+
def _atoms_in_source_bonded_to_target(
201+
source_residue: Any,
202+
target_residue: Any,
203+
) -> Any:
204+
"""Return source-residue atoms bonded to atoms in a target residue.
205+
206+
This helper is used when constructing residue-level dihedral definitions
207+
from lightweight molecule AtomGroups. It selects atoms from the source
208+
residue that are bonded to any atom in the target residue without using
209+
global ``resindex`` selection strings.
210+
211+
Args:
212+
source_residue: Residue whose atoms should be tested for bonds.
213+
target_residue: Adjacent residue providing the target bonded atoms.
214+
215+
Returns:
216+
MDAnalysis AtomGroup containing atoms from ``source_residue`` that are
217+
bonded to at least one atom in ``target_residue``. If no matching
218+
atoms are found, an empty AtomGroup is returned.
219+
"""
220+
source_atoms = source_residue.atoms
221+
target_indices = {int(index) for index in target_residue.atoms.indices}
222+
selected_indices: list[int] = []
223+
224+
for atom in source_atoms:
225+
bonded_atoms = getattr(atom, "bonded_atoms", None)
226+
if bonded_atoms is None:
227+
continue
228+
229+
bonded_indices = {int(index) for index in bonded_atoms.indices}
230+
if bonded_indices.intersection(target_indices):
231+
selected_indices.append(int(atom.index))
232+
233+
return source_atoms.universe.atoms[selected_indices]

‎CodeEntropy/levels/level_dag.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from CodeEntropy.levels.frame_dag import FrameGraph
2020
from CodeEntropy.levels.neighbors import Neighbors
2121
from CodeEntropy.levels.nodes.accumulators import InitCovarianceAccumulatorsNode
22+
from CodeEntropy.levels.nodes.axes_topology import BuildAxesTopologyNode
2223
from CodeEntropy.levels.nodes.beads import BuildBeadsNode
2324
from CodeEntropy.levels.nodes.detect_levels import DetectLevelsNode
2425
from CodeEntropy.levels.nodes.detect_molecules import DetectMoleculesNode
@@ -49,6 +50,11 @@ def build(self) -> LevelDAG:
4950
self._add_static("detect_molecules", DetectMoleculesNode())
5051
self._add_static("detect_levels", DetectLevelsNode(), deps=["detect_molecules"])
5152
self._add_static("build_beads", BuildBeadsNode(), deps=["detect_levels"])
53+
self._add_static(
54+
"build_axes_topology",
55+
BuildAxesTopologyNode(),
56+
deps=["build_beads"],
57+
)
5258
self._add_static(
5359
"init_covariance_accumulators",
5460
InitCovarianceAccumulatorsNode(),

0 commit comments

Comments
 (0)