Skip to content

Commit 65f8dc7

Browse files
committed
perf(conformations): avoid memory-universe copies in topology discovery
1 parent ad35001 commit 65f8dc7

2 files changed

Lines changed: 131 additions & 19 deletions

File tree

‎CodeEntropy/levels/dihedrals/topology.py‎

Lines changed: 110 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,31 @@ 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 when lightweight
105+
extraction is available; otherwise, the fallback fragment object
106+
returned by ``extract_fragment``.
107+
"""
108+
if hasattr(self._universe_operations, "extract_fragment_atomgroup"):
109+
return self._universe_operations.extract_fragment_atomgroup(
110+
data_container,
111+
int(molecule_id),
112+
)
113+
114+
return self._universe_operations.extract_fragment(data_container, molecule_id)
115+
93116
def _select_heavy_residue(self, mol: Any, res_id: int) -> Any:
94117
"""Select heavy atoms in a residue by residue index.
95118
@@ -100,13 +123,15 @@ def _select_heavy_residue(self, mol: Any, res_id: int) -> Any:
100123
Returns:
101124
AtomGroup containing heavy atoms in the residue selection.
102125
"""
103-
selection1 = mol.residues[res_id].atoms.indices[0]
104-
selection2 = mol.residues[res_id].atoms.indices[-1]
126+
residue_atoms = mol.residues[int(res_id)].atoms
127+
selection1 = residue_atoms.indices[0]
128+
selection2 = residue_atoms.indices[-1]
105129

106-
res_container = self._universe_operations.select_atoms(
107-
mol, f"index {selection1}:{selection2}"
130+
res_container = mol.select_atoms(
131+
f"index {selection1}:{selection2}",
132+
updating=False,
108133
)
109-
return self._universe_operations.select_atoms(res_container, "prop mass > 1.1")
134+
return res_container.select_atoms("prop mass > 1.1", updating=False)
110135

111136
def _get_dihedrals(self, data_container: Any, level: str) -> list[Any]:
112137
"""Return dihedral AtomGroups for a container at a given level.
@@ -121,26 +146,93 @@ def _get_dihedrals(self, data_container: Any, level: str) -> list[Any]:
121146
atom_groups: list[Any] = []
122147

123148
if level == "united_atom":
149+
selected_indices = {int(index) for index in data_container.indices}
150+
124151
for dihedral in data_container.dihedrals:
125-
atom_groups.append(dihedral.atoms)
152+
dihedral_atoms = dihedral.atoms
153+
dihedral_indices = {int(index) for index in dihedral_atoms.indices}
154+
155+
if len(dihedral_atoms) == 4 and dihedral_indices.issubset(
156+
selected_indices
157+
):
158+
atom_groups.append(dihedral_atoms)
126159

127160
if level == "residue":
128161
num_residues = len(data_container.residues)
129162
if num_residues >= 4:
130163
for residue in range(4, num_residues + 1):
131-
atom1 = data_container.select_atoms(
132-
f"resindex {residue - 4} and bonded resindex {residue - 3}"
164+
residue1 = data_container.residues[residue - 4]
165+
residue2 = data_container.residues[residue - 3]
166+
residue3 = data_container.residues[residue - 2]
167+
residue4 = data_container.residues[residue - 1]
168+
169+
atom1 = self._atoms_in_source_bonded_to_target(
170+
residue1,
171+
residue2,
133172
)
134-
atom2 = data_container.select_atoms(
135-
f"resindex {residue - 3} and bonded resindex {residue - 4}"
173+
atom2 = self._atoms_in_source_bonded_to_target(
174+
residue2,
175+
residue1,
136176
)
137-
atom3 = data_container.select_atoms(
138-
f"resindex {residue - 2} and bonded resindex {residue - 1}"
177+
atom3 = self._atoms_in_source_bonded_to_target(
178+
residue3,
179+
residue4,
139180
)
140-
atom4 = data_container.select_atoms(
141-
f"resindex {residue - 1} and bonded resindex {residue - 2}"
181+
atom4 = self._atoms_in_source_bonded_to_target(
182+
residue4,
183+
residue3,
142184
)
143-
atom_groups.append(atom1 + atom2 + atom3 + atom4)
185+
186+
dihedral_atoms = atom1 + atom2 + atom3 + atom4
187+
188+
if len(dihedral_atoms) == 4:
189+
atom_groups.append(dihedral_atoms)
190+
else:
191+
logger.debug(
192+
"Skipping residue-level dihedral for local residues "
193+
"%s-%s-%s-%s because it produced %d atoms.",
194+
residue - 4,
195+
residue - 3,
196+
residue - 2,
197+
residue - 1,
198+
len(dihedral_atoms),
199+
)
144200

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

‎CodeEntropy/trajectory/mda.py‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ class UniverseOperations:
2525
This helper provides methods to:
2626
- Build reduced universes by selecting subsets of frames or atoms.
2727
- Extract a single fragment (molecule) into a standalone universe.
28-
- Merge coordinates from one trajectory with forces from another trajectory.
28+
- Merge coordinates from one trajectory with forces sourced from another
29+
trajectory.
2930
"""
3031

3132
def __init__(self) -> None:
@@ -186,6 +187,25 @@ def extract_fragment(
186187
selection_string = f"index {frag.indices[0]}:{frag.indices[-1]}"
187188
return self.select_atoms(universe, selection_string)
188189

190+
def extract_fragment_atomgroup(self, universe: mda.Universe, molecule_id: int):
191+
"""Return a molecule fragment as an AtomGroup.
192+
193+
This helper mirrors the atom-index range used by ``extract_fragment`` but
194+
avoids building a standalone in-memory universe. It is intended for
195+
topology discovery paths where only the static atom selection is needed
196+
and trajectory coordinates do not need to be copied.
197+
198+
Args:
199+
universe: Source MDAnalysis universe.
200+
molecule_id: Fragment index in ``universe.atoms.fragments``.
201+
202+
Returns:
203+
MDAnalysis AtomGroup containing the atoms in the selected fragment.
204+
"""
205+
frag = universe.atoms.fragments[int(molecule_id)]
206+
selection_string = f"index {frag.indices[0]}:{frag.indices[-1]}"
207+
return universe.select_atoms(selection_string, updating=False)
208+
189209
def convert_lammps(
190210
self,
191211
tprfile: str,

0 commit comments

Comments
 (0)