diff --git a/CodeEntropy/config/argparse.py b/CodeEntropy/config/argparse.py index 781cdb98..03647a18 100644 --- a/CodeEntropy/config/argparse.py +++ b/CodeEntropy/config/argparse.py @@ -170,6 +170,12 @@ class ArgSpec: help="Type of neighbour search to use. Default is RAD; grid search is also " "available.", ), + "conf_type": ArgSpec( + type=str, + default="ua_backbone", + help="Dihedral definition to use for conformational entropy." + "Default is ua_backbone.", + ), "parallel_frames": ArgSpec( type=bool, default=False, diff --git a/CodeEntropy/levels/dihedrals/conformational_state_builder.py b/CodeEntropy/levels/dihedrals/conformational_state_builder.py index 7c9c03f2..c96b7f2c 100644 --- a/CodeEntropy/levels/dihedrals/conformational_state_builder.py +++ b/CodeEntropy/levels/dihedrals/conformational_state_builder.py @@ -43,6 +43,7 @@ def build_conformational_states( levels: dict[Any, list[str]], groups: dict[int, list[Any]], bin_width: float, + conf_type: str, frame_selection: FrameSelection, progress: _RichProgressSink | None = None, chunk_size: int | None = None, @@ -78,6 +79,7 @@ def build_conformational_states( levels=levels, groups=groups, bin_width=bin_width, + conf_type=conf_type, frame_selection=frame_selection, chunk_size=chunk_size, progress=progress, @@ -89,6 +91,7 @@ def _build_conformational_states_serial_chunked( levels: dict[Any, list[str]], groups: dict[int, list[Any]], bin_width: float, + conf_type: str, frame_selection: FrameSelection, chunk_size: int, progress: _RichProgressSink | None = None, @@ -156,6 +159,7 @@ def _build_conformational_states_serial_chunked( group_id=group_id, molecules=molecules, level_list=level_list, + conf_type=conf_type, ) tasks = self._build_conformation_chunk_tasks( topologies=topologies, @@ -188,6 +192,7 @@ def _build_conformational_states_serial_chunked( level_list=level_list, peaks_ua=peak_data.peaks_ua, peaks_res=peak_data.peaks_res, + conf_type=conf_type, ) for observable in observables ] diff --git a/CodeEntropy/levels/dihedrals/dihedral_finder.py b/CodeEntropy/levels/dihedrals/dihedral_finder.py new file mode 100644 index 00000000..32aaf7fb --- /dev/null +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -0,0 +1,318 @@ +"""Dihedral state assignment for conformational entropy. + +This module converts selected-frame dihedral angle time series into discrete +conformational state labels. The resulting state labels are used downstream to +compute configurational entropy. + +Frame-index contract: + - ``FrameSelection.analysis_indices`` are used for MDAnalysis trajectory access + in the active analysis universe. + - ``Dihedral(...).run(start, stop, step)`` uses frame bounds in the active + analysis-universe index space. + - ``dihedral_results.results.angles`` is always indexed locally from zero. + Never use an absolute/source frame index directly into that result array. +""" + +from __future__ import annotations + +import logging +from typing import Any + +from CodeEntropy.levels.axes import AxesCalculator + +logger = logging.getLogger(__name__) + +UAKey = tuple[int, int] + + +class DihedralDefinitions: + """Build conformational state labels from dihedral angles.""" + + def __init__(self) -> None: + """Initializes the analysis helper.""" + self._axes = AxesCalculator() + + def method_res_bonds(self, data_container: Any, level: str) -> list[Any]: + """Return dihedral AtomGroups for a container at a given level. + Using bonds between residues (1, 2) and (3,4) to identify 4 points + to cast as a dihedral group at the residue level. + + Args: + data_container: MDAnalysis container. + level: Either ``"united_atom"`` or ``"residue"``. + + Returns: + List of AtomGroups, each representing a dihedral definition. + """ + atom_groups: list[Any] = [] + + if level == "united_atom": + selected_indices = {int(index) for index in data_container.indices} + + for dihedral in data_container.dihedrals: + dihedral_atoms = dihedral.atoms + dihedral_indices = {int(index) for index in dihedral_atoms.indices} + + if len(dihedral_atoms) == 4 and dihedral_indices.issubset( + selected_indices + ): + atom_groups.append(dihedral_atoms) + + if level == "residue": + num_residues = len(data_container.residues) + if num_residues >= 4: + for residue in range(4, num_residues + 1): + residue1 = data_container.residues[residue - 4] + residue2 = data_container.residues[residue - 3] + residue3 = data_container.residues[residue - 2] + residue4 = data_container.residues[residue - 1] + + atom1 = self._atoms_in_source_bonded_to_target( + residue1, + residue2, + ) + atom2 = self._atoms_in_source_bonded_to_target( + residue2, + residue1, + ) + atom3 = self._atoms_in_source_bonded_to_target( + residue3, + residue4, + ) + atom4 = self._atoms_in_source_bonded_to_target( + residue4, + residue3, + ) + + dihedral_atoms = atom1 + atom2 + atom3 + atom4 + + if len(dihedral_atoms) == 4: + atom_groups.append(dihedral_atoms) + else: + logger.debug( + "Skipping residue-level dihedral for local residues " + "%s-%s-%s-%s because it produced %d atoms.", + residue - 4, + residue - 3, + residue - 2, + residue - 1, + len(dihedral_atoms), + ) + + return atom_groups + + def method_res_pairs(self, data_container: Any, level: str) -> list[Any]: + """Return dihedral AtomGroups for a container at a given level. + Using the bond between residues (1, 2) and the centre of geometry of + each residue to identify 4 points to cast as a dihedral group at the + residue level. + + Args: + data_container: MDAnalysis container. + level: Either ``"united_atom"`` or ``"residue"``. + + Returns: + List of AtomGroups, each representing a dihedral definition. + """ + atom_groups: list[Any] = [] + + if level == "united_atom": + selected_indices = {int(index) for index in data_container.indices} + + for dihedral in data_container.dihedrals: + dihedral_atoms = dihedral.atoms + dihedral_indices = {int(index) for index in dihedral_atoms.indices} + + if len(dihedral_atoms) == 4 and dihedral_indices.issubset( + selected_indices + ): + atom_groups.append(dihedral_atoms) + + if level == "residue": + num_residues = len(data_container.residues) + if num_residues >= 2: + for residue in range(2, num_residues + 1): + residue1 = data_container.residues[residue - 2] + index1 = data_container.residues.resindices[residue - 2] + residue2 = data_container.residues[residue - 1] + index2 = data_container.residues.resindices[residue - 1] + + center = residue1.atoms.center_of_geometry() + atom_search = data_container.select_atoms( + f"point {center[0]} {center[1]} {center[2]} 1.5" + f" and resindex {index1}" + ) + atom1 = atom_search[0] + atom2 = self._atoms_in_source_bonded_to_target( + residue1, + residue2, + ) + atom3 = self._atoms_in_source_bonded_to_target( + residue2, + residue1, + ) + center = residue2.atoms.center_of_geometry() + atom_search = data_container.select_atoms( + f"point {center[0]} {center[1]} {center[2]} 1.5" + f" and resindex {index2}" + ) + atom4 = atom_search[0] + + dihedral_atoms = atom1 + atom2 + atom3 + atom4 + + if len(dihedral_atoms) == 4: + atom_groups.append(dihedral_atoms) + else: + logger.debug( + "Skipping residue-level dihedral for local residues " + "%s-%s because it produced %d atoms.", + residue - 2, + residue - 1, + len(dihedral_atoms), + ) + + return atom_groups + + def method_res_points(self, data_container: Any, level: str) -> list[Any]: + """Return dihedral AtomGroups for a container at a given level. + At the residue level, for each residue a point is defined as the + atom nearest the average position of the edge atoms (bonded to an atom + in a different residue). These points are then used for residue level + dihedral groups. + + Args: + data_container: MDAnalysis container (AtomGroup/Universe). + level: Either "united_atom" or "residue". + + Returns: + List of AtomGroups (each representing a dihedral definition). + """ + atom_groups: list[Any] = [] + + if level == "united_atom": + selected_indices = {int(index) for index in data_container.indices} + + for dihedral in data_container.dihedrals: + dihedral_atoms = dihedral.atoms + dihedral_indices = {int(index) for index in dihedral_atoms.indices} + + if len(dihedral_atoms) == 4 and dihedral_indices.issubset( + selected_indices + ): + atom_groups.append(dihedral_atoms) + + if level == "residue": + num_residues = len(data_container.residues) + point: list[Any] = {} + if num_residues >= 4: + for residue in range(num_residues): + atom_search = [] + index = data_container.residues.resindices[residue] + edges = data_container.select_atoms( + f"resindex {index} and bonded not resindex {index}" + ) + if len(edges) > 1: + center = edges.center_of_geometry() + atom_search = data_container.select_atoms( + f"point {center[0]} {center[1]} {center[2]} 1.3" + f" and resindex {residue}" + ) + if len(atom_search) == 0: + point[residue] = edges[0] + else: + point[residue] = atom_search[0] + + for index in range(3, num_residues): + atom1 = point[index - 3] + atom2 = point[index - 2] + atom3 = point[index - 1] + atom4 = point[index] + atom_groups.append(atom1 + atom2 + atom3 + atom4) + + return atom_groups + + def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: + """Return dihedral AtomGroups for a container at a given level. + For the residue level, use the heavy atoms from the backbone as the set + from which the dihedrals are found (gives secondary structure states). + + Args: + data_container: MDAnalysis container (AtomGroup/Universe). + level: Either "united_atom" or "residue". + + Returns: + List of AtomGroups (each representing a dihedral definition). + """ + atom_groups: list[Any] = [] + + if level == "united_atom": + selected_indices = {int(index) for index in data_container.indices} + + for dihedral in data_container.dihedrals: + dihedral_atoms = dihedral.atoms + dihedral_indices = {int(index) for index in dihedral_atoms.indices} + + if len(dihedral_atoms) == 4 and dihedral_indices.issubset( + selected_indices + ): + atom_groups.append(dihedral_atoms) + + if level == "residue": + num_residues = len(data_container.residues) + backbone = data_container.select_atoms("name H and not name H") + if num_residues >= 2: + for res_counter in range(num_residues): + residue = data_container.residues[res_counter] + index = data_container.residues.resindices[res_counter] + edges = data_container.select_atoms( + f"resindex {index} and bonded not resindex {index}" + ) + if len(edges) == 1: + backbone += edges + elif len(edges) == 2: + chain = self._axes.get_chain(residue, edges[0], edges[1]) + for atom in chain: + backbone += atom + + logger.debug("backbone = %s", backbone) + dihedrals = backbone.dihedrals + for d in dihedrals: + atom_groups.append(d.atoms) + + return atom_groups + + @staticmethod + def _atoms_in_source_bonded_to_target( + source_residue: Any, + target_residue: Any, + ) -> Any: + """Return source-residue atoms bonded to atoms in a target residue. + + This helper is used when constructing residue-level dihedral definitions + from lightweight molecule AtomGroups. It selects atoms from the source + residue that are bonded to any atom in the target residue without using + global ``resindex`` selection strings. + + Args: + source_residue: Residue whose atoms should be tested for bonds. + target_residue: Adjacent residue providing the target bonded atoms. + + Returns: + MDAnalysis AtomGroup containing atoms from ``source_residue`` that are + bonded to at least one atom in ``target_residue``. If no matching + atoms are found, an empty AtomGroup is returned. + """ + source_atoms = source_residue.atoms + target_indices = {int(index) for index in target_residue.atoms.indices} + selected_indices: list[int] = [] + + for atom in source_atoms: + bonded_atoms = getattr(atom, "bonded_atoms", None) + if bonded_atoms is None: + continue + + bonded_indices = {int(index) for index in bonded_atoms.indices} + if bonded_indices.intersection(target_indices): + selected_indices.append(int(atom.index)) + + return source_atoms.universe.atoms[selected_indices] diff --git a/CodeEntropy/levels/dihedrals/peak_detection.py b/CodeEntropy/levels/dihedrals/peak_detection.py index e87ac78a..fd2a2229 100644 --- a/CodeEntropy/levels/dihedrals/peak_detection.py +++ b/CodeEntropy/levels/dihedrals/peak_detection.py @@ -177,6 +177,9 @@ def _reduce_angle_observables_to_histograms( target_res[dihedral_index] + counts[dihedral_index] ) + logger.debug("Histogram UA: %s", hist_ua) + logger.debug("Histogram Res: %s", hist_res) + return DihedralHistogramData( num_residues=num_residues, num_dihedrals_ua=num_dihedrals_ua, diff --git a/CodeEntropy/levels/dihedrals/state_assignment.py b/CodeEntropy/levels/dihedrals/state_assignment.py index 09efb45d..b90860d8 100644 --- a/CodeEntropy/levels/dihedrals/state_assignment.py +++ b/CodeEntropy/levels/dihedrals/state_assignment.py @@ -71,6 +71,7 @@ def _assign_state_partial_from_observable( level_list: list[Any], peaks_ua: list[list[Any]], peaks_res: list[Any], + conf_type: str, ) -> ConformationStatePartial: """Assign chunk-local states from cached angle arrays and global peaks. @@ -113,6 +114,15 @@ def _assign_state_partial_from_observable( angles=observable.residue_angles, ) + # Flexible residues are used for an extra force halving relating + # to correlations between vibrations and conformational flexiblity + # This is a work arround for the "ua_backbone" type of dihedral finder + # because with the backbone set of united atoms being used for the + # residue level conformations, the number of dihedrals can exceed the + # number of residue bead vibrational degrees of freedom. + if "residue" in level_list and conf_type == "ua_backbone": + flex_res = 0 + return ConformationStatePartial( task=observable.task, state_res=state_res, diff --git a/CodeEntropy/levels/dihedrals/topology.py b/CodeEntropy/levels/dihedrals/topology.py index 31e35ffd..ff65633d 100644 --- a/CodeEntropy/levels/dihedrals/topology.py +++ b/CodeEntropy/levels/dihedrals/topology.py @@ -11,6 +11,8 @@ from dataclasses import dataclass from typing import Any +from CodeEntropy.levels.dihedrals.dihedral_finder import DihedralDefinitions + logger = logging.getLogger(__name__) @@ -44,6 +46,7 @@ def _discover_group_dihedral_topology( group_id: int, molecules: list[Any], level_list: list[Any], + conf_type: str, ) -> list[MoleculeDihedralTopology]: """Discover static conformational topology for a molecule group. @@ -70,10 +73,11 @@ def _discover_group_dihedral_topology( ua_dihedrals_by_residue[res_id] = self._get_dihedrals( heavy_res, "united_atom", + conf_type, ) if "residue" in level_list: - residue_dihedrals = self._get_dihedrals(mol, "residue") + residue_dihedrals = self._get_dihedrals(mol, "residue", conf_type) topologies.append( MoleculeDihedralTopology( @@ -128,7 +132,9 @@ def _select_heavy_residue(self, mol: Any, res_id: int) -> Any: ) return res_container.select_atoms("prop mass > 1.1", updating=False) - def _get_dihedrals(self, data_container: Any, level: str) -> list[Any]: + def _get_dihedrals( + self, data_container: Any, level: str, conf_type: str + ) -> list[Any]: """Return dihedral AtomGroups for a container at a given level. Args: @@ -139,59 +145,27 @@ def _get_dihedrals(self, data_container: Any, level: str) -> list[Any]: List of AtomGroups, each representing a dihedral definition. """ atom_groups: list[Any] = [] + self._dihedral_definitions = DihedralDefinitions() - if level == "united_atom": - selected_indices = {int(index) for index in data_container.indices} - - for dihedral in data_container.dihedrals: - dihedral_atoms = dihedral.atoms - dihedral_indices = {int(index) for index in dihedral_atoms.indices} - - if len(dihedral_atoms) == 4 and dihedral_indices.issubset( - selected_indices - ): - atom_groups.append(dihedral_atoms) - - if level == "residue": - num_residues = len(data_container.residues) - if num_residues >= 4: - for residue in range(4, num_residues + 1): - residue1 = data_container.residues[residue - 4] - residue2 = data_container.residues[residue - 3] - residue3 = data_container.residues[residue - 2] - residue4 = data_container.residues[residue - 1] - - atom1 = self._atoms_in_source_bonded_to_target( - residue1, - residue2, - ) - atom2 = self._atoms_in_source_bonded_to_target( - residue2, - residue1, - ) - atom3 = self._atoms_in_source_bonded_to_target( - residue3, - residue4, - ) - atom4 = self._atoms_in_source_bonded_to_target( - residue4, - residue3, - ) + if conf_type == "res_bonds": + atom_groups = self._dihedral_definitions.method_res_bonds( + data_container=data_container, level=level + ) - dihedral_atoms = atom1 + atom2 + atom3 + atom4 - - if len(dihedral_atoms) == 4: - atom_groups.append(dihedral_atoms) - else: - logger.debug( - "Skipping residue-level dihedral for local residues " - "%s-%s-%s-%s because it produced %d atoms.", - residue - 4, - residue - 3, - residue - 2, - residue - 1, - len(dihedral_atoms), - ) + elif conf_type == "res_pairs": + atom_groups = self._dihedral_definitions.method_res_pairs( + data_container=data_container, level=level + ) + + elif conf_type == "res_points": + atom_groups = self._dihedral_definitions.method_res_points( + data_container=data_container, level=level + ) + + elif conf_type == "ua_backbone": + atom_groups = self._dihedral_definitions.method_ua_backbone( + data_container=data_container, level=level + ) logger.debug("Level: %s, Dihedrals: %s", level, atom_groups) return atom_groups diff --git a/CodeEntropy/levels/graph/conformation_dag.py b/CodeEntropy/levels/graph/conformation_dag.py index 39a84b3b..04bd6191 100644 --- a/CodeEntropy/levels/graph/conformation_dag.py +++ b/CodeEntropy/levels/graph/conformation_dag.py @@ -63,6 +63,7 @@ def execute( groups = shared_data["groups"] frame_selection: FrameSelection = shared_data["frame_selection"] bin_width = int(shared_data["args"].bin_width) + conf_type = str(shared_data["args"].conf_type) chunk_size = self._policy.frame_chunk_size( shared_data, n_frames=frame_selection.n_frames, @@ -74,6 +75,7 @@ def execute( levels=levels, groups=groups, bin_width=bin_width, + conf_type=conf_type, frame_selection=frame_selection, progress=progress, chunk_size=chunk_size, diff --git a/docs/source/getting_started.rst b/docs/source/getting_started.rst index f601cec3..0131d9d8 100644 --- a/docs/source/getting_started.rst +++ b/docs/source/getting_started.rst @@ -179,7 +179,7 @@ The ``top_traj_file`` argument is required; other arguments have default values. - ``30`` - ``int`` * - ``--temperature`` - - Temperature for entropy calculation (K). + - Temperature for entropy calculation (K) is the same as the simulation temperature. - ``298.0`` - ``float`` * - ``--verbose`` @@ -224,6 +224,10 @@ The ``top_traj_file`` argument is required; other arguments have default values. - Method for finding neighbouring molecules. - ``RAD`` - ``str`` + * - ``--conf_type`` + - Method for identifying the residue level dihedrals for conformational entropy. + - ``ua_backbone`` + - ``str`` * - ``--parallel_frames`` - Execute frame-local covariance calculations in parallel. When enabled, frame-level work is submitted to Dask and reduced in the parent process. diff --git a/docs/source/science.rst b/docs/source/science.rst index b42af0ac..3bcc7f5e 100644 --- a/docs/source/science.rst +++ b/docs/source/science.rst @@ -87,8 +87,12 @@ This term is based on the intramolecular conformational states. The united atom level dihedrals are defined for every linear sequence of four bonded atoms, but only using the heavy atoms no hydrogens are involved. The MDAnalysis package is used to identify and calculate the united atom dihedral values. -For the residue level dihedrals, the bond between the first and second residues and the bond between the third and fourth residues are found. -The four atoms at the ends of these two bonds are used as points for the dihedral angle calculation. +For the residue level dihedrals, there is a choice of methods: + +- ua_backbone: the heavy backbone atoms from every residue, if there are two or more residues in the molecule, are collected into an atom group and the atomistic dihedrals from this group are used. +- res_pairs: four points are selected from two neighboring residues. These points are the atoms at the ends of the bond connecting the two residues and the center of geometry of each residue. +- res_bonds: the bond between the first and second residues and the bond between the third and fourth residues are found. The four atoms at the ends of these two bonds are used as points for the dihedral angle calculation. +- res_points: uses one point from each of four adjacent residues. This method uses the atoms bonded to other residues as edges and takes the center of the edges as the point for each residue. To discretise dihedrals, a histogram is constructed from each set of dihedral values and peaks are identified. Then at each timestep, every dihedral is assigned to its nearest peak and a state is created from all the assigned peaks in the residue (for united atom level) or molecule (for residue level). diff --git a/tests/regression/configs/dna/axes_off.yaml b/tests/regression/configs/dna/axes_off.yaml index 9c6e17bc..6cce990c 100644 --- a/tests/regression/configs/dna/axes_off.yaml +++ b/tests/regression/configs/dna/axes_off.yaml @@ -8,4 +8,5 @@ run1: start: 0 end: 5 step: 2 + conf_type: "res_bonds" axes: principal diff --git a/tests/regression/configs/dna/frame_window.yaml b/tests/regression/configs/dna/frame_window.yaml index c003f83e..f96c4345 100644 --- a/tests/regression/configs/dna/frame_window.yaml +++ b/tests/regression/configs/dna/frame_window.yaml @@ -8,3 +8,4 @@ run1: start: 0 end: 5 step: 2 + conf_type: "res_bonds" diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_conformational_state_builder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_conformational_state_builder.py index f413a620..cfcad126 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_conformational_state_builder.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_conformational_state_builder.py @@ -48,6 +48,7 @@ def test_build_conformational_states_defaults_chunk_size_to_selected_frame_count levels={7: ["residue"]}, groups={0: [7]}, bin_width=30.0, + conf_type="res_bonds", frame_selection=frame_selection, ) @@ -57,6 +58,7 @@ def test_build_conformational_states_defaults_chunk_size_to_selected_frame_count levels={7: ["residue"]}, groups={0: [7]}, bin_width=30.0, + conf_type="res_bonds", frame_selection=frame_selection, chunk_size=3, progress=None, @@ -75,6 +77,7 @@ def test_build_conformational_states_passes_explicit_chunk_size(): levels={7: ["residue"]}, groups={0: [7]}, bin_width=30.0, + conf_type="res_bonds", frame_selection=frame_selection, chunk_size=2, ) @@ -96,6 +99,7 @@ def test_chunked_serial_rejects_invalid_chunk_size(): levels={}, groups={}, bin_width=30.0, + conf_type="res_bonds", frame_selection=_make_frame_selection(start=0, stop=1, step=1), chunk_size=0, ) @@ -115,6 +119,7 @@ def test_build_conformational_states_with_progress_handles_no_groups(): levels={}, groups={}, bin_width=30.0, + conf_type="res_bonds", frame_selection=_make_frame_selection(start=0, stop=1, step=1), progress=progress, ) @@ -138,6 +143,7 @@ def test_build_conformational_states_with_progress_skips_empty_molecule_group(): levels={}, groups={0: []}, bin_width=30.0, + conf_type="res_bonds", frame_selection=_make_frame_selection(start=0, stop=1, step=1), progress=progress, ) @@ -173,6 +179,7 @@ def test_chunked_serial_group_flow_calls_domain_phases_in_order(): levels={7: ["united_atom"]}, groups={0: [7]}, bin_width=30.0, + conf_type="res_bonds", frame_selection=frame_selection, chunk_size=2, ) @@ -187,6 +194,7 @@ def test_chunked_serial_group_flow_calls_domain_phases_in_order(): group_id=0, molecules=[7], level_list=["united_atom"], + conf_type="res_bonds", ) builder._build_conformation_chunk_tasks.assert_called_once_with( topologies=[topology], @@ -209,6 +217,7 @@ def test_chunked_serial_group_flow_calls_domain_phases_in_order(): level_list=["united_atom"], peaks_ua=peak_data.peaks_ua, peaks_res=peak_data.peaks_res, + conf_type="res_bonds", ) builder._reduce_state_partials.assert_called_once_with([partial]) @@ -238,6 +247,7 @@ def test_chunked_serial_with_progress_updates_and_advances_non_empty_group(): levels={7: ["united_atom"]}, groups={0: [7]}, bin_width=30.0, + conf_type="res_bonds", frame_selection=frame_selection, chunk_size=2, progress=progress, diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py new file mode 100644 index 00000000..1656c1c2 --- /dev/null +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any +from unittest.mock import MagicMock + +from CodeEntropy.levels.dihedrals.dihedral_finder import DihedralDefinitions + + +@dataclass +class FakeAtom: + """Small test double for an MDAnalysis Atom.""" + + index: int + bonded_atoms: Any = None + + +class FakeUniverseAtoms: + """Indexable fake universe atom container.""" + + def __init__(self, universe: FakeUniverse) -> None: + self._universe = universe + + def __getitem__(self, indices: int | list[int] | tuple[int, ...]) -> Any: + if isinstance(indices, int): + return self._universe.atom_by_index[int(indices)] + + return FakeAtomGroup( + [self._universe.atom_by_index[int(index)] for index in indices], + universe=self._universe, + ) + + +class FakeUniverseDihedrals: + """Indexable fake dihedral list.""" + + def __init__(self, universe: FakeUniverse, atoms) -> None: + self._universe = universe + + def __getitem__(self, atoms) -> Any: + length = len(atoms) + if length < 4: + return [] + else: + dihedrals = [] + for group in range(4, length, 1): + dihedral = atoms[group - 4 : group] + dihedrals.append(dihedral) + return dihedrals + + +class FakeUniverse: + """Small fake universe supporting ``universe.atoms[indices]``.""" + + def __init__(self, atoms: list[FakeAtom]) -> None: + self.indices = {int(atom.index) for atom in atoms} + self.dihedrals = FakeUniverseDihedrals(self, atoms) + self.atom_by_index = {int(atom.index): atom for atom in atoms} + self.atoms = FakeUniverseAtoms(self) + + +class FakeAtomGroup: + """Small AtomGroup-like test double for topology discovery tests.""" + + def __init__( + self, + atoms: list[FakeAtom], + *, + residues: list[Any] | None = None, + dihedrals: list[Any] | None = None, + select_map: dict[str, Any] | None = None, + universe: FakeUniverse | None = None, + ) -> None: + self._atoms = list(atoms) + self.residues = list(residues or []) + self.dihedrals = list(dihedrals or []) + self._select_map = dict(select_map or {}) + self.universe = universe + + @property + def atoms(self) -> FakeAtomGroup: + return self + + @property + def indices(self) -> list[int]: + return [int(atom.index) for atom in self._atoms] + + def __iter__(self): + return iter(self._atoms) + + def __len__(self) -> int: + return len(self._atoms) + + def __add__(self, other: FakeAtomGroup) -> FakeAtomGroup: + return FakeAtomGroup( + self._atoms + other._atoms, + universe=self.universe or other.universe, + ) + + def select_atoms(self, select_string: str, updating: bool = False) -> Any: + if select_string.startswith("resindex"): + return self._select_map[select_string] + elif select_string not in self._select_map: + raise AssertionError(f"Unexpected selection: {select_string!r}") + return self._select_map[select_string] + + +@dataclass +class FakeResidue: + """Small residue test double.""" + + atoms: FakeAtomGroup + + +@dataclass +class FakeDihedral: + """Small dihedral topology object.""" + + atoms: FakeAtomGroup + + +def test_method_res_bonds_ua(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + universe = FakeUniverse(atoms) + atom_group = FakeAtomGroup(atoms, universe=universe) + dihedral = FakeDihedral(atom_group) + + data_container = FakeAtomGroup( + atoms, + dihedrals=[dihedral], + universe=universe, + ) + + result = dd.method_res_bonds(data_container, "united_atom") + + assert len(result) == 1 + assert result[0] is atom_group + assert result[0].indices == [0, 1, 2, 3] + + +def test_method_res_bonds_res(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + universe = FakeUniverse(atoms) + + # Create bonds between consecutive residues. + atoms[0].bonded_atoms = FakeAtomGroup([atoms[1]], universe=universe) + atoms[1].bonded_atoms = FakeAtomGroup([atoms[0]], universe=universe) + atoms[2].bonded_atoms = FakeAtomGroup([atoms[3]], universe=universe) + atoms[3].bonded_atoms = FakeAtomGroup([atoms[2]], universe=universe) + + residues = [FakeResidue(FakeAtomGroup([atom], universe=universe)) for atom in atoms] + + data_container = MagicMock() + data_container.residues = residues + + result = dd.method_res_bonds(data_container, "residue") + + assert len(result) == 1 + assert result[0].indices == [0, 1, 2, 3] + + +def test_method_res_points_ua(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + universe = FakeUniverse(atoms) + atom_group = FakeAtomGroup(atoms, universe=universe) + dihedral = FakeDihedral(atom_group) + + data_container = FakeAtomGroup( + atoms, + dihedrals=[dihedral], + universe=universe, + ) + + result = dd.method_res_points(data_container, "united_atom") + + assert len(result) == 1 + assert result[0] is atom_group + assert result[0].indices == [0, 1, 2, 3] + + +def test_method_res_points_res(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + universe = FakeUniverse(atoms) + atom_group = FakeAtomGroup(atoms, universe=universe) + dihedral = FakeDihedral(atom_group) + + # Create bonds between consecutive residues. + atoms[0].bonded_atoms = FakeAtomGroup([atoms[1]], universe=universe) + atoms[1].bonded_atoms = FakeAtomGroup([atoms[0], atoms[2]], universe=universe) + atoms[2].bonded_atoms = FakeAtomGroup([atoms[1], atoms[3]], universe=universe) + atoms[3].bonded_atoms = FakeAtomGroup([atoms[2]], universe=universe) + + residues = [FakeResidue(FakeAtomGroup([atom], universe=universe)) for atom in atoms] + + data_container = FakeAtomGroup( + atoms, + residues=residues, + dihedrals=[dihedral], + universe=universe, + ) + + result = dd.method_res_points(data_container, "residue") + + assert len(result) == 1 + assert result[0].indices == [0, 1, 2, 3] + + +def test_method_res_pairs_ua(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + universe = FakeUniverse(atoms) + atom_group = FakeAtomGroup(atoms, universe=universe) + dihedral = FakeDihedral(atom_group) + + data_container = FakeAtomGroup( + atoms, + dihedrals=[dihedral], + universe=universe, + ) + + result = dd.method_res_pairs(data_container, "united_atom") + + assert len(result) == 1 + assert result[0] is atom_group + assert result[0].indices == [0, 1, 2, 3] + + +def test_method_res_pairs_res(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(2)] + universe = FakeUniverse(atoms) + atom_group = FakeAtomGroup(atoms, universe=universe) + dihedral = FakeDihedral(atom_group) + + # Create bonds between consecutive residues. + atoms[0].bonded_atoms = FakeAtomGroup([atoms[1]], universe=universe) + atoms[1].bonded_atoms = FakeAtomGroup([atoms[0]], universe=universe) + + residues = [FakeResidue(FakeAtomGroup([atom], universe=universe)) for atom in atoms] + + data_container = FakeAtomGroup( + atoms, + residues=residues, + dihedrals=[dihedral], + universe=universe, + ) + + result = dd.method_res_pairs(data_container, "residue") + + assert len(result) == 1 + assert result[0].indices == [0, 1, 2, 3] + + +def test_method_ua_backbone_ua(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + universe = FakeUniverse(atoms) + atom_group = FakeAtomGroup(atoms, universe=universe) + dihedral = FakeDihedral(atom_group) + + data_container = FakeAtomGroup( + atoms, + dihedrals=[dihedral], + universe=universe, + ) + + result = dd.method_ua_backbone(data_container, "united_atom") + + assert len(result) == 1 + assert result[0] is atom_group + assert result[0].indices == [0, 1, 2, 3] + + +def test_method_ua_backbone_res(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + universe = FakeUniverse(atoms) + atom_group = FakeAtomGroup(atoms, universe=universe) + dihedral = FakeDihedral(atom_group) + + residues = [FakeResidue(FakeAtomGroup([atom], universe=universe)) for atom in atoms] + + backbone = FakeAtomGroup(atoms, dihedrals=[dihedral], universe=universe) + + data_container = FakeAtomGroup( + atoms, + dihedrals=[dihedral], + residues=residues, + select_map={"name H and not name H": backbone}, + universe=universe, + ) + + result = dd.method_ua_backbone(data_container, "residue") + + assert len(result) == 1 + assert result[0].indices == [0, 1, 2, 3] diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_state_assignment.py b/tests/unit/CodeEntropy/levels/dihedrals/test_state_assignment.py index 6ae22a57..9180ec86 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_state_assignment.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_state_assignment.py @@ -128,6 +128,7 @@ def test_assign_state_partial_from_observable_handles_ua_and_residue_levels(): level_list=["united_atom", "residue"], peaks_ua=[[[5.0, 15.0]], []], peaks_res=[[30.0, 40.0]], + conf_type="res_bonds", ) assert partial.states_ua_updates[(2, 0)] == ["0", "1"] diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_topology.py b/tests/unit/CodeEntropy/levels/dihedrals/test_topology.py index cbc38b19..18324618 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_topology.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_topology.py @@ -202,7 +202,7 @@ def test_get_dihedrals_united_atom_collects_atoms_from_dihedral_objects() -> Non universe=universe, ) - result = discovery._get_dihedrals(selected_heavy_atoms, "united_atom") + result = discovery._get_dihedrals(selected_heavy_atoms, "united_atom", "res_bonds") assert result == [valid_dihedral_atoms] @@ -223,7 +223,9 @@ def test_get_dihedrals_united_atom_returns_empty_when_no_valid_dihedrals() -> No universe=universe, ) - assert discovery._get_dihedrals(selected_heavy_atoms, "united_atom") == [] + assert ( + discovery._get_dihedrals(selected_heavy_atoms, "united_atom", "res_bonds") == [] + ) def test_get_dihedrals_residue_builds_one_dihedral_when_four_residues() -> None: @@ -257,7 +259,7 @@ def test_get_dihedrals_residue_builds_one_dihedral_when_four_residues() -> None: universe=universe, ) - result = discovery._get_dihedrals(mol, "residue") + result = discovery._get_dihedrals(mol, "residue", "res_bonds") assert len(result) == 1 assert result[0].indices == [10, 20, 30, 40] @@ -298,7 +300,7 @@ def test_get_dihedrals_residue_skips_invalid_four_residue_window( universe=universe, ) - result = discovery._get_dihedrals(mol, "residue") + result = discovery._get_dihedrals(mol, "residue", "res_bonds") assert result == [] assert "Skipping residue-level dihedral" in caplog.text @@ -317,7 +319,7 @@ def test_get_dihedrals_residue_returns_empty_when_fewer_than_four_residues() -> universe=universe, ) - assert discovery._get_dihedrals(mol, "residue") == [] + assert discovery._get_dihedrals(mol, "residue", "res_bonds") == [] def test_atoms_in_source_bonded_to_target_returns_matching_source_atoms() -> None: @@ -381,7 +383,9 @@ def test_discover_group_dihedral_topology_builds_one_entry_per_molecule( def fake_select_heavy_residue(mol: Any, res_id: int) -> str: return f"{mol.label}-heavy-{res_id}" - def fake_get_dihedrals(data_container: Any, level: str) -> list[str]: + def fake_get_dihedrals( + data_container: Any, level: str, conf_type: str + ) -> list[str]: if level == "united_atom": return [f"ua-{data_container}"] return [f"res-{data_container.label}"] @@ -402,6 +406,7 @@ def fake_get_dihedrals(data_container: Any, level: str) -> list[str]: group_id=9, molecules=[100, 200], level_list=["united_atom", "residue"], + conf_type="res_bonds", ) assert topologies == [ @@ -455,6 +460,7 @@ def test_discover_group_dihedral_topology_respects_enabled_levels( group_id=1, molecules=[0], level_list=["residue"], + conf_type="res_bonds", ) assert topologies == [ @@ -469,4 +475,4 @@ def test_discover_group_dihedral_topology_respects_enabled_levels( ] select_heavy_residue.assert_not_called() - get_dihedrals.assert_called_once_with(molecule, "residue") + get_dihedrals.assert_called_once_with(molecule, "residue", "res_bonds") diff --git a/tests/unit/CodeEntropy/levels/test_conformation_dag.py b/tests/unit/CodeEntropy/levels/test_conformation_dag.py index cb634fe8..a4990c17 100644 --- a/tests/unit/CodeEntropy/levels/test_conformation_dag.py +++ b/tests/unit/CodeEntropy/levels/test_conformation_dag.py @@ -52,7 +52,7 @@ def test_execute_uses_execution_policy_chunk_size_and_stores_outputs(): "levels": {7: ["united_atom"]}, "groups": {0: [7]}, "frame_selection": frame_selection, - "args": SimpleNamespace(bin_width=30), + "args": SimpleNamespace(bin_width=30, conf_type="res_bonds"), } out = dag.execute(shared_data, progress=progress) @@ -66,6 +66,7 @@ def test_execute_uses_execution_policy_chunk_size_and_stores_outputs(): levels={7: ["united_atom"]}, groups={0: [7]}, bin_width=30, + conf_type="res_bonds", frame_selection=frame_selection, progress=progress, chunk_size=2, @@ -96,7 +97,7 @@ def test_execute_converts_bin_width_to_int(): "levels": {}, "groups": {}, "frame_selection": frame_selection, - "args": SimpleNamespace(bin_width="45"), + "args": SimpleNamespace(bin_width="45", conf_type="res_bonds"), } dag.execute(shared_data) @@ -119,7 +120,7 @@ def test_execute_passes_real_frame_selection_to_builder(): "levels": {}, "groups": {}, "frame_selection": frame_selection, - "args": SimpleNamespace(bin_width=30), + "args": SimpleNamespace(bin_width=30, conf_type="res_bonds"), } dag.execute(shared_data)