diff --git a/CodeEntropy/config/argparse.py b/CodeEntropy/config/argparse.py index 9fdd37a6..3a3652f9 100644 --- a/CodeEntropy/config/argparse.py +++ b/CodeEntropy/config/argparse.py @@ -170,6 +170,13 @@ 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="Method for identifying the residue-level dihedrals for " + "conformational entropy. One of ua_backbone, res_pairs, res_bonds or " + "res_points. Default is ua_backbone.", + ), "symmetry_number": ArgSpec( type=str, nargs="+", @@ -559,6 +566,7 @@ def validate_inputs(self, u: Any, args: argparse.Namespace) -> None: self._check_input_force_partitioning(args) self._check_parallel_frame_options(args) self._check_input_axes(args) + self._check_input_conf_type(args) self._check_input_symmetry_number(args) @staticmethod @@ -572,6 +580,18 @@ def _check_input_axes(args: argparse.Namespace) -> None: ) args.axes = axes + @staticmethod + def _check_input_conf_type(args: argparse.Namespace) -> None: + """Check that the conformational dihedral method is supported.""" + valid = ("ua_backbone", "res_pairs", "res_bonds", "res_points") + conf_type = str(args.conf_type).strip().lower() + if conf_type not in valid: + raise ValueError( + f"Invalid 'conf_type': {args.conf_type!r}. " + f"Must be one of {', '.join(valid)}." + ) + args.conf_type = conf_type + @staticmethod def _check_input_start(u: Any, args: argparse.Namespace) -> None: """Check that the start index does not exceed the trajectory length.""" diff --git a/CodeEntropy/levels/dihedrals/conformational_state_builder.py b/CodeEntropy/levels/dihedrals/conformational_state_builder.py index 7c9c03f2..8a1b96e7 100644 --- a/CodeEntropy/levels/dihedrals/conformational_state_builder.py +++ b/CodeEntropy/levels/dihedrals/conformational_state_builder.py @@ -13,6 +13,7 @@ from rich.progress import TaskID +from CodeEntropy.levels.dihedrals.dihedral_finder import DihedralDefinitions from CodeEntropy.levels.dihedrals.peak_detection import ConformationPeakDetector from CodeEntropy.levels.dihedrals.state_assignment import ( ConformationStateAssigner, @@ -36,6 +37,7 @@ def __init__(self, universe_operations: Any) -> None: - select_atoms(atomgroup, selection_string) """ self._universe_operations = universe_operations + self._dihedral_definitions = DihedralDefinitions() def build_conformational_states( self, @@ -43,6 +45,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 +81,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 +93,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 +161,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 +194,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..2541520d --- /dev/null +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -0,0 +1,309 @@ +"""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 + +import numpy as np + +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 == "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 == "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] + + atom1 = self._atom_near_center(data_container, residue1, index1) + atom2 = self._atoms_in_source_bonded_to_target( + residue1, + residue2, + ) + atom3 = self._atoms_in_source_bonded_to_target( + residue2, + residue1, + ) + atom4 = self._atom_near_center(data_container, residue2, index2) + + 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 == "residue": + num_residues = len(data_container.residues) + point: dict[int, 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 {index}" + ) + 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 == "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]) + # since get_chain returns chain[1:-1] + full_chain = [] + full_chain.append(edges[0]) + full_chain.append(chain) + full_chain.append(edges[1]) + for atom in chain: + backbone += atom + + logger.debug("backbone = %s", backbone) + # ``AtomGroup.dihedrals`` includes every dihedral touching any + # backbone atom, so keep only those lying wholly on the backbone. + backbone_indices = {int(index) for index in backbone.indices} + for dihedral in backbone.dihedrals: + dihedral_atoms = dihedral.atoms + dihedral_indices = {int(index) for index in dihedral_atoms.indices} + if dihedral_indices.issubset(backbone_indices): + atom_groups.append(dihedral_atoms) + + return atom_groups + + @staticmethod + def _atom_near_center( + data_container: Any, + residue: Any, + resindex: int, + radius: float = 1.5, + ) -> Any: + """Return an atom near the centre of geometry of a residue. + + The first atom of the residue within ``radius`` of its centre of + geometry is returned. If no atom lies within ``radius`` (for example, + when the centre falls in empty space in a large or ring residue), the + atom of the residue nearest the centre is returned instead. + + Args: + data_container: MDAnalysis container used for the point selection. + residue: Residue whose centre of geometry is used. + resindex: Global residue index of ``residue``. + radius: Search radius around the centre of geometry, in Angstrom. + + Returns: + MDAnalysis Atom near the centre of geometry of ``residue``. + """ + residue_atoms = residue.atoms + center = residue_atoms.center_of_geometry() + atom_search = data_container.select_atoms( + f"point {center[0]} {center[1]} {center[2]} {radius}" + f" and resindex {resindex}" + ) + if len(atom_search) > 0: + return atom_search[0] + + distances = np.linalg.norm( + np.asarray(residue_atoms.positions) - np.asarray(center), axis=1 + ) + return residue_atoms[int(np.argmin(distances))] + + @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..d636ea57 100644 --- a/CodeEntropy/levels/dihedrals/topology.py +++ b/CodeEntropy/levels/dihedrals/topology.py @@ -44,6 +44,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 +71,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 +130,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: @@ -144,54 +148,34 @@ def _get_dihedrals(self, data_container: Any, level: str) -> list[Any]: 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} + dihedral_indices = {int(index) for index in dihedral.atoms.indices} - if len(dihedral_atoms) == 4 and dihedral_indices.issubset( + 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, - ) + atom_groups.append(dihedral.atoms) + logger.debug("Level: %s, Dihedrals: %s", level, atom_groups) + return atom_groups + + 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 c1413024..f202cb70 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,12 @@ 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. + One of ``ua_backbone``, ``res_pairs``, ``res_bonds`` or ``res_points``. See + the conformational entropy section of :doc:`science` for details. + - ``ua_backbone`` + - ``str`` * - ``--symmetry_number`` - Rotational symmetry number (integer >= 0) used in the orientational entropy, replacing the value computed from the bond graph. ``VALUE`` applies to all diff --git a/docs/source/science.rst b/docs/source/science.rst index 9d69729f..73bdbabe 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/pyproject.toml b/pyproject.toml index fdfb407a..0842b5c7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -96,6 +96,9 @@ markers = [ "slow: long-running regression tests (20-30+ minutes)", ] +[tool.coverage.run] +source = ["CodeEntropy"] + [tool.ruff] line-length = 88 target-version = "py311" 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/config/argparse/conftest.py b/tests/unit/CodeEntropy/config/argparse/conftest.py index 0c3f8b59..b1c8e283 100644 --- a/tests/unit/CodeEntropy/config/argparse/conftest.py +++ b/tests/unit/CodeEntropy/config/argparse/conftest.py @@ -36,6 +36,7 @@ def _make(**overrides): temperature=298.0, force_partitioning=0.5, axes="local", + conf_type="ua_backbone", ) base.update(overrides) # validation functions only require attribute access; SimpleNamespace is ideal diff --git a/tests/unit/CodeEntropy/config/argparse/test_argparse_validate_inputs.py b/tests/unit/CodeEntropy/config/argparse/test_argparse_validate_inputs.py index 4725f9e4..2d885f01 100644 --- a/tests/unit/CodeEntropy/config/argparse/test_argparse_validate_inputs.py +++ b/tests/unit/CodeEntropy/config/argparse/test_argparse_validate_inputs.py @@ -306,6 +306,34 @@ def test_check_input_axes_raises_for_invalid_values(resolver, make_args, value): resolver._check_input_axes(args) +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("ua_backbone", "ua_backbone"), + ("res_pairs", "res_pairs"), + ("res_bonds", "res_bonds"), + ("res_points", "res_points"), + (" RES_POINTS ", "res_points"), + ], +) +def test_check_input_conf_type_accepts_and_normalises_valid_values( + resolver, make_args, value, expected +): + args = make_args(conf_type=value) + + resolver._check_input_conf_type(args) + + assert args.conf_type == expected + + +@pytest.mark.parametrize("value", ["ua-backbone", "res_point", "", None]) +def test_check_input_conf_type_raises_for_invalid_values(resolver, make_args, value): + args = make_args(conf_type=value) + + with pytest.raises(ValueError, match="Invalid 'conf_type'"): + resolver._check_input_conf_type(args) + + @pytest.mark.parametrize( ("raw", "expected"), [ 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..bd524155 --- /dev/null +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -0,0 +1,428 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any +from unittest.mock import MagicMock + +import numpy as np + +from CodeEntropy.levels.dihedrals.dihedral_finder import DihedralDefinitions + + +@dataclass +class FakeAtom: + """Small test double for an MDAnalysis Atom.""" + + index: int + bonded_atoms: Any = None + position: tuple[float, float, float] = (0.0, 0.0, 0.0) + + +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 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.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 = FakeResidueGroup(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 __getitem__(self, index: int) -> FakeAtomGroup: + return FakeAtomGroup([self._atoms[index]], universe=self.universe) + + @property + def positions(self) -> np.ndarray: + return np.array([atom.position for atom in self._atoms], dtype=float) + + def center_of_geometry(self) -> tuple[float, float, float]: + n_atoms = len(self._atoms) + return tuple( + sum(atom.position[axis] for atom in self._atoms) / n_atoms + for axis in range(3) + ) + + def __len__(self) -> int: + return len(self._atoms) + + def __add__(self, other: FakeAtomGroup) -> FakeAtomGroup: + dihedrals = list(self.dihedrals) + dihedrals += [ + dihedral + for dihedral in other.dihedrals + if not any(dihedral is existing for existing in dihedrals) + ] + return FakeAtomGroup( + self._atoms + other._atoms, + dihedrals=dihedrals, + 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 + resindex: int = 0 + + +class FakeResidueGroup(list): + """List of residues exposing ``resindices`` like an MDAnalysis ResidueGroup.""" + + @property + def resindices(self) -> list[int]: + return [int(residue.resindex) for residue in self] + + +@dataclass +class FakeDihedral: + """Small dihedral topology object.""" + + atoms: FakeAtomGroup + + +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_res(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + universe = FakeUniverse(atoms) + + residues = [ + FakeResidue(FakeAtomGroup([atom], universe=universe), resindex=atom.index) + for atom in atoms + ] + + # Each single-atom residue has exactly one edge atom, so that atom is used + # as the residue's point. + select_map = { + f"resindex {atom.index} and bonded not resindex {atom.index}": FakeAtomGroup( + [atom], universe=universe + ) + for atom in atoms + } + + data_container = FakeAtomGroup( + atoms, + residues=residues, + select_map=select_map, + 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_points_res_uses_global_resindex_for_point_search(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index, position=(float(index), 0.0, 0.0)) for index in range(8)] + universe = FakeUniverse(atoms) + + # Four two-atom residues whose global resindices do not start at zero, as + # for any molecule after the first in a multi-molecule system. + resindices = [10, 11, 12, 13] + residues = [ + FakeResidue( + FakeAtomGroup(atoms[2 * i : 2 * i + 2], universe=universe), + resindex=resindex, + ) + for i, resindex in enumerate(resindices) + ] + + select_map = {} + for i, resindex in enumerate(resindices): + first, second = atoms[2 * i], atoms[2 * i + 1] + # Two edge atoms, so the point is searched near their centre. + select_map[f"resindex {resindex} and bonded not resindex {resindex}"] = ( + FakeAtomGroup([first, second], universe=universe) + ) + select_map[f"point {2 * i + 0.5} 0.0 0.0 1.3 and resindex {resindex}"] = ( + FakeAtomGroup([second], universe=universe) + ) + + data_container = FakeAtomGroup( + atoms, + residues=residues, + select_map=select_map, + universe=universe, + ) + + result = dd.method_res_points(data_container, "residue") + + assert len(result) == 1 + assert result[0].indices == [1, 3, 5, 7] + + +def test_method_res_pairs_res(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index, position=(float(index), 0.0, 0.0)) for index in range(4)] + universe = FakeUniverse(atoms) + + # Two residues of two atoms each, joined by a bond between atoms 1 and 2. + 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(atoms[0:2], universe=universe), resindex=0), + FakeResidue(FakeAtomGroup(atoms[2:4], universe=universe), resindex=1), + ] + + # Atoms nearest each residue's centre of geometry. + select_map = { + "point 0.5 0.0 0.0 1.5 and resindex 0": FakeAtomGroup( + [atoms[0]], universe=universe + ), + "point 2.5 0.0 0.0 1.5 and resindex 1": FakeAtomGroup( + [atoms[3]], universe=universe + ), + } + + data_container = FakeAtomGroup( + atoms, + residues=residues, + select_map=select_map, + 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_res_pairs_res_falls_back_to_nearest_atom_to_center(): + dd = DihedralDefinitions() + x_positions = [0.0, 1.0, 5.0, 6.0, 10.0, 11.0] + atoms = [ + FakeAtom(index, position=(x, 0.0, 0.0)) for index, x in enumerate(x_positions) + ] + universe = FakeUniverse(atoms) + + # Residues joined by a bond between atoms 2 and 3. + atoms[2].bonded_atoms = FakeAtomGroup([atoms[3]], universe=universe) + atoms[3].bonded_atoms = FakeAtomGroup([atoms[2]], universe=universe) + + residues = [ + FakeResidue(FakeAtomGroup(atoms[0:3], universe=universe), resindex=0), + FakeResidue(FakeAtomGroup(atoms[3:6], universe=universe), resindex=1), + ] + + # No atom lies within 1.5 A of either centre (x = 2.0 and x = 9.0), so + # the atoms nearest each centre (atoms 1 and 4) are used instead. + select_map = { + "point 2.0 0.0 0.0 1.5 and resindex 0": FakeAtomGroup([], universe=universe), + "point 9.0 0.0 0.0 1.5 and resindex 1": FakeAtomGroup([], universe=universe), + } + + data_container = FakeAtomGroup( + atoms, + residues=residues, + select_map=select_map, + universe=universe, + ) + + result = dd.method_res_pairs(data_container, "residue") + + assert len(result) == 1 + assert result[0].indices == [1, 2, 3, 4] + + +def test_method_res_pairs_res_skips_pairs_with_multiple_bonds(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index, position=(float(index), 0.0, 0.0)) for index in range(4)] + universe = FakeUniverse(atoms) + + # Two bonds between the residues (0-2 and 1-3) give more than four atoms. + atoms[0].bonded_atoms = FakeAtomGroup([atoms[2]], universe=universe) + atoms[1].bonded_atoms = FakeAtomGroup([atoms[3]], universe=universe) + atoms[2].bonded_atoms = FakeAtomGroup([atoms[0]], universe=universe) + atoms[3].bonded_atoms = FakeAtomGroup([atoms[1]], universe=universe) + + residues = [ + FakeResidue(FakeAtomGroup(atoms[0:2], universe=universe), resindex=0), + FakeResidue(FakeAtomGroup(atoms[2:4], universe=universe), resindex=1), + ] + + select_map = { + "point 0.5 0.0 0.0 1.5 and resindex 0": FakeAtomGroup( + [atoms[0]], universe=universe + ), + "point 2.5 0.0 0.0 1.5 and resindex 1": FakeAtomGroup( + [atoms[3]], universe=universe + ), + } + + data_container = FakeAtomGroup( + atoms, + residues=residues, + select_map=select_map, + universe=universe, + ) + + result = dd.method_res_pairs(data_container, "residue") + + assert result == [] + + +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), resindex=atom.index) + for atom in atoms + ] + + # Backbone selection starts empty; each residue contributes its single + # edge atom, which takes part in the backbone dihedral. + select_map = {"name H and not name H": FakeAtomGroup([], universe=universe)} + select_map.update( + { + f"resindex {atom.index} and bonded not resindex {atom.index}": ( + FakeAtomGroup([atom], dihedrals=[dihedral], universe=universe) + ) + for atom in atoms + } + ) + + data_container = FakeAtomGroup( + atoms, + residues=residues, + select_map=select_map, + universe=universe, + ) + + result = dd.method_ua_backbone(data_container, "residue") + + assert len(result) == 1 + assert result[0].indices == [0, 1, 2, 3] + + +def test_method_ua_backbone_res_uses_chain_and_excludes_off_backbone_dihedrals(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(6)] + universe = FakeUniverse(atoms) + + def group(indices: list[int], **kwargs: Any) -> FakeAtomGroup: + return FakeAtomGroup([atoms[i] for i in indices], universe=universe, **kwargs) + + # Atoms 0-4 form the backbone; atom 5 is a side-chain atom on residue 1. + backbone_dihedrals = [ + FakeDihedral(group([0, 1, 2, 3])), + FakeDihedral(group([1, 2, 3, 4])), + ] + side_chain_dihedral = FakeDihedral(group([5, 2, 3, 4])) + all_dihedrals = backbone_dihedrals + [side_chain_dihedral] + + def touching(indices: list[int]) -> list[FakeDihedral]: + """Dihedrals involving any of the atoms, as ``AtomGroup.dihedrals``.""" + return [d for d in all_dihedrals if set(d.atoms.indices) & set(indices)] + + residues = [ + FakeResidue(group([0]), resindex=0), + FakeResidue(group([1, 2, 3, 5]), resindex=1), + FakeResidue(group([4]), resindex=2), + ] + + # Residue 1 has two edge atoms, so the backbone chain between them is used. + chain = [group([i], dihedrals=touching([i])) for i in (1, 2, 3)] + dd._axes = MagicMock() + dd._axes.get_chain.return_value = chain + + select_map = { + "name H and not name H": group([]), + "resindex 0 and bonded not resindex 0": group([0], dihedrals=touching([0])), + "resindex 1 and bonded not resindex 1": group([1, 3]), + "resindex 2 and bonded not resindex 2": group([4], dihedrals=touching([4])), + } + + data_container = group( + list(range(6)), + residues=residues, + select_map=select_map, + ) + + result = dd.method_ua_backbone(data_container, "residue") + + dd._axes.get_chain.assert_called_once() + assert dd._axes.get_chain.call_args.args[0] is residues[1] + assert [d.indices for d in result] == [[0, 1, 2, 3], [1, 2, 3, 4]] 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)