From 2a4bf2f8267943192db30183bfbcfc4ed4abd812 Mon Sep 17 00:00:00 2001 From: skfegan Date: Mon, 27 Jul 2026 11:07:16 +0100 Subject: [PATCH 01/16] conformational options --- CodeEntropy/config/argparse.py | 6 + CodeEntropy/levels/axes.py | 75 ++++++ .../dihedrals/conformational_state_builder.py | 4 + .../levels/dihedrals/dihedral_finder.py | 242 ++++++++++++++++++ CodeEntropy/levels/dihedrals/topology.py | 80 ++---- CodeEntropy/levels/graph/conformation_dag.py | 2 + .../test_conformational_state_builder.py | 9 + .../levels/dihedrals/test_topology.py | 20 +- .../levels/test_conformation_dag.py | 7 +- 9 files changed, 382 insertions(+), 63 deletions(-) create mode 100644 CodeEntropy/levels/dihedrals/dihedral_finder.py diff --git a/CodeEntropy/config/argparse.py b/CodeEntropy/config/argparse.py index 80fe63dd..4bdd50cd 100644 --- a/CodeEntropy/config/argparse.py +++ b/CodeEntropy/config/argparse.py @@ -153,6 +153,12 @@ class ArgSpec: help="Type of neighbour search to use. Default is RAD; grid search is also " "available.", ), + "conf_type": ArgSpec( + type=str, + default="res_bonds", + help="Dihedral definition to use for conformational entropy." + "Default is res_bonds.", + ), "parallel_frames": ArgSpec( type=bool, default=False, diff --git a/CodeEntropy/levels/axes.py b/CodeEntropy/levels/axes.py index 4d4cf89c..8e2d8614 100644 --- a/CodeEntropy/levels/axes.py +++ b/CodeEntropy/levels/axes.py @@ -849,3 +849,78 @@ def get_UA_masses(self, molecule) -> list[float]: ua_mass += float(h.mass) ua_masses.append(ua_mass) return ua_masses + + def get_chain(self, residue, first, last): + """ + For a given MDAnalysis AtomGroup and two given heavy atoms + within that AtomGroup, return the + shortest path between the two atoms. + + Args: + residue: MDAnalysis AtomGroup representing + the residue/monomer of interest. + first: First heavy atom in the chain + last: Last heavy atom in the chain + + Returns: + chain: Array containing chain atoms. + """ + + chain = [] + # at the beggining we've only visited the first atom + visited_dict = {first: True} + # keep the previous atom to trace back the path + prev = {} + # queue of next heavy atoms to visit + next_to_visit = [first] + # all others heavy atoms in the residue, we have not yet visited + remaining_heavy_atoms = residue.atoms.select_atoms( + f"(mass 2 to 999) and not index {first.index}" + ) + for atom in remaining_heavy_atoms: + visited_dict[atom] = False + current = first + + while not visited_dict[last]: + # we haven't found a path to the last residue + next_to_visit.pop(0) + # we're visiting the current atom => we remove it from the queue + bonded_atoms = residue.atoms.select_atoms( + f"(mass 2 to 999) and bonded index {current.index}" + ) + + if last in bonded_atoms: + # we found a path to the last atom + visited_dict[last] = True + chain.append(last) + prev[last] = current + + else: + for bonded_atom in bonded_atoms: + # look for unvisited bonded atoms to the current atom we're visiting + if not visited_dict[bonded_atom]: + # we're going to want to visit the atoms + next_to_visit.append(bonded_atom) + prev[bonded_atom] = current + # we visit the next atom in the queue + current = next_to_visit[0] + visited_dict[current] = True + + # we track the previous atom back to the first atom now + current = last + chain = [last] + # subtract index of first atom in resid + # most likely will coincide with first + # but this will work even if it doesn't + # accout for in-residue index + # start from last atom in chain + while chain[-1] != first: + # we haven't yet returned to the first atom + current = prev[current] + chain.append(current) + + chain = np.flip(chain) + # only get in between residues + chain = chain[1:-1] + # accout for in-residue index + return chain diff --git a/CodeEntropy/levels/dihedrals/conformational_state_builder.py b/CodeEntropy/levels/dihedrals/conformational_state_builder.py index a944201e..1fa68c53 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, @@ -73,6 +74,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, @@ -84,6 +86,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, @@ -147,6 +150,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, diff --git a/CodeEntropy/levels/dihedrals/dihedral_finder.py b/CodeEntropy/levels/dihedrals/dihedral_finder.py new file mode 100644 index 00000000..bc65d089 --- /dev/null +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -0,0 +1,242 @@ +"""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. + + 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), + ) + + logger.debug("Level: %s, Dihedrals: %s", level, atom_groups) + 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. + + 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": + dihedrals = data_container.dihedrals + for d in dihedrals: + atom_groups.append(d.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. + + 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": + dihedrals = data_container.dihedrals + for d in dihedrals: + atom_groups.append(d.atoms) + + if level == "residue": + num_residues = len(data_container.residues) + backbone = data_container.select_atoms("name H and not name H") + if num_residues >= 4: + for index in range(num_residues): + residue = data_container.residues[index] + 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]) + backbone += chain + + logger.debug(f"backbone = {backbone}") + dihedrals = backbone.dihedrals + for d in dihedrals: + atom_groups.append(d.atoms) + + return atom_groups + + def method_ua_whole(self, data_container: Any, level: str) -> list[Any]: + """Return dihedral AtomGroups for a container at a given level. + + 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": + dihedrals = data_container.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/topology.py b/CodeEntropy/levels/dihedrals/topology.py index 31e35ffd..2827bb19 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_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 + ) + + elif conf_type == "ua_whole": + atom_groups = self._dihedral_definitions.method_ua_whole( + 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/tests/unit/CodeEntropy/levels/dihedrals/test_conformational_state_builder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_conformational_state_builder.py index 1ac72cc5..f7bd4346 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], @@ -238,6 +246,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_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) From f0f0d975d13a76c300529054481bdd75e03a3b05 Mon Sep 17 00:00:00 2001 From: skfegan Date: Thu, 27 Aug 2026 13:54:27 +0100 Subject: [PATCH 02/16] Adapting flexible dihedrals for conf_type=ua_backbone. --- .../dihedrals/conformational_state_builder.py | 1 + .../levels/dihedrals/dihedral_finder.py | 22 ++----------------- .../levels/dihedrals/state_assignment.py | 10 +++++++++ 3 files changed, 13 insertions(+), 20 deletions(-) diff --git a/CodeEntropy/levels/dihedrals/conformational_state_builder.py b/CodeEntropy/levels/dihedrals/conformational_state_builder.py index 1fa68c53..91921d64 100644 --- a/CodeEntropy/levels/dihedrals/conformational_state_builder.py +++ b/CodeEntropy/levels/dihedrals/conformational_state_builder.py @@ -183,6 +183,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 index bc65d089..efc43791 100644 --- a/CodeEntropy/levels/dihedrals/dihedral_finder.py +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -177,7 +177,8 @@ def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: backbone += edges elif len(edges) == 2: chain = self._axes.get_chain(residue, edges[0], edges[1]) - backbone += chain + for atom in chain: + backbone += atom logger.debug(f"backbone = {backbone}") dihedrals = backbone.dihedrals @@ -186,25 +187,6 @@ def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: return atom_groups - def method_ua_whole(self, data_container: Any, level: str) -> list[Any]: - """Return dihedral AtomGroups for a container at a given level. - - 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": - dihedrals = data_container.dihedrals - for d in dihedrals: - atom_groups.append(d.atoms) - - return atom_groups - @staticmethod def _atoms_in_source_bonded_to_target( source_residue: Any, diff --git a/CodeEntropy/levels/dihedrals/state_assignment.py b/CodeEntropy/levels/dihedrals/state_assignment.py index d2a1bd6d..d95450d8 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, From 675b50da68da4eff6771a1526b0499f9c63b0862 Mon Sep 17 00:00:00 2001 From: skfegan Date: Fri, 23 Oct 2026 08:42:24 +0100 Subject: [PATCH 03/16] adding res_pairs option --- .../dihedrals/conformational_state_builder.py | 3 +- .../levels/dihedrals/dihedral_finder.py | 116 ++++++++++++++++-- .../levels/dihedrals/peak_detection.py | 3 + CodeEntropy/levels/dihedrals/topology.py | 10 +- 4 files changed, 114 insertions(+), 18 deletions(-) diff --git a/CodeEntropy/levels/dihedrals/conformational_state_builder.py b/CodeEntropy/levels/dihedrals/conformational_state_builder.py index 91921d64..269a9905 100644 --- a/CodeEntropy/levels/dihedrals/conformational_state_builder.py +++ b/CodeEntropy/levels/dihedrals/conformational_state_builder.py @@ -111,9 +111,8 @@ def _build_conformational_states_serial_chunked( if chunk_size < 1: raise ValueError("chunk_size must be >= 1") - number_groups = len(groups) states_ua: dict[UAKey, list[str]] = {} - states_res: list[list[str]] = [[] for _ in range(number_groups)] + states_res: list[list[str]] = [] flexible_ua: dict[UAKey, int] = {} flexible_res: list[int] = [] diff --git a/CodeEntropy/levels/dihedrals/dihedral_finder.py b/CodeEntropy/levels/dihedrals/dihedral_finder.py index efc43791..32aaf7fb 100644 --- a/CodeEntropy/levels/dihedrals/dihedral_finder.py +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -34,6 +34,8 @@ def __init__(self) -> None: 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. @@ -97,11 +99,86 @@ def method_res_bonds(self, data_container: Any, level: str) -> list[Any]: len(dihedral_atoms), ) - logger.debug("Level: %s, Dihedrals: %s", level, atom_groups) + 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). @@ -113,9 +190,16 @@ def method_res_points(self, data_container: Any, level: str) -> list[Any]: atom_groups: list[Any] = [] if level == "united_atom": - dihedrals = data_container.dihedrals - for d in dihedrals: - atom_groups.append(d.atoms) + 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) @@ -149,6 +233,8 @@ def method_res_points(self, data_container: Any, level: str) -> list[Any]: 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). @@ -160,16 +246,24 @@ def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: atom_groups: list[Any] = [] if level == "united_atom": - dihedrals = data_container.dihedrals - for d in dihedrals: - atom_groups.append(d.atoms) + 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 >= 4: - for index in range(num_residues): - residue = data_container.residues[index] + 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}" ) @@ -180,7 +274,7 @@ def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: for atom in chain: backbone += atom - logger.debug(f"backbone = {backbone}") + logger.debug("backbone = %s", backbone) dihedrals = backbone.dihedrals for d in dihedrals: atom_groups.append(d.atoms) 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/topology.py b/CodeEntropy/levels/dihedrals/topology.py index 2827bb19..ff65633d 100644 --- a/CodeEntropy/levels/dihedrals/topology.py +++ b/CodeEntropy/levels/dihedrals/topology.py @@ -152,6 +152,11 @@ def _get_dihedrals( data_container=data_container, level=level ) + 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 @@ -162,11 +167,6 @@ def _get_dihedrals( data_container=data_container, level=level ) - elif conf_type == "ua_whole": - atom_groups = self._dihedral_definitions.method_ua_whole( - data_container=data_container, level=level - ) - logger.debug("Level: %s, Dihedrals: %s", level, atom_groups) return atom_groups From 80bfa2f7aa95bbcaf06d9513176ce53ac9fd0a25 Mon Sep 17 00:00:00 2001 From: skfegan Date: Fri, 23 Oct 2026 14:33:00 +0100 Subject: [PATCH 04/16] fixing existing tests, setting conf_type default to ua_backbone --- CodeEntropy/config/argparse.py | 4 ++-- tests/regression/configs/dna/axes_off.yaml | 1 + tests/regression/configs/dna/frame_window.yaml | 1 + .../levels/dihedrals/test_conformational_state_builder.py | 1 + .../CodeEntropy/levels/dihedrals/test_state_assignment.py | 1 + 5 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CodeEntropy/config/argparse.py b/CodeEntropy/config/argparse.py index 017f4607..9ba9ade3 100644 --- a/CodeEntropy/config/argparse.py +++ b/CodeEntropy/config/argparse.py @@ -156,9 +156,9 @@ class ArgSpec: ), "conf_type": ArgSpec( type=str, - default="res_bonds", + default="ua_backbone", help="Dihedral definition to use for conformational entropy." - "Default is res_bonds.", + "Default is ua_backbone.", ), "parallel_frames": ArgSpec( type=bool, diff --git a/tests/regression/configs/dna/axes_off.yaml b/tests/regression/configs/dna/axes_off.yaml index 4f5de407..fb61779e 100644 --- a/tests/regression/configs/dna/axes_off.yaml +++ b/tests/regression/configs/dna/axes_off.yaml @@ -9,3 +9,4 @@ run1: end: 5 step: 2 customised_axes: false + conf_type: "res_bonds" 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 b4ce2bb5..cfcad126 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_conformational_state_builder.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_conformational_state_builder.py @@ -217,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]) 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"] From 02840b8c5a9d93359c0bdee82664654f329b7802 Mon Sep 17 00:00:00 2001 From: skfegan Date: Tue, 10 Nov 2026 16:18:43 +0000 Subject: [PATCH 05/16] starting unit tests for levels/dihedrals/dihedral_finder.py --- .../levels/dihedrals/test_dihedral_finder.py | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py 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..6f0a6966 --- /dev/null +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -0,0 +1,142 @@ +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 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)] + data_container = MagicMock() + data_container.atoms = atoms + data_container.dihedrals = MagicMock() + data_container.dihedrals.atoms.return_value = [0, 1, 2, 3] + + result = dd.method_res_bonds(data_container, "united_atom") + + assert result == [0, 1, 2, 3] + + +def test_method_res_bonds_res(): + dd = DihedralDefinitions() + atoms = [FakeAtom(index) for index in range(4)] + data_container = MagicMock() + data_container.atoms = atoms + data_container.residues = [0, 1, 2, 3] + + result = dd.method_res_bonds(data_container, "residue") + + assert result == [0, 1, 2, 3] From 839536dae22a91eafa013ed75fb0c00966a495c5 Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Thu, 12 Nov 2026 11:30:25 +0000 Subject: [PATCH 06/16] tests(unit): fix residue-level dihedral bond detection test --- .../levels/dihedrals/test_dihedral_finder.py | 33 ++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py index 6f0a6966..f602e3a0 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -120,23 +120,40 @@ class FakeDihedral: def test_method_res_bonds_ua(): dd = DihedralDefinitions() atoms = [FakeAtom(index) for index in range(4)] - data_container = MagicMock() - data_container.atoms = atoms - data_container.dihedrals = MagicMock() - data_container.dihedrals.atoms.return_value = [0, 1, 2, 3] + 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 result == [0, 1, 2, 3] + 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.atoms = atoms - data_container.residues = [0, 1, 2, 3] + data_container.residues = residues result = dd.method_res_bonds(data_container, "residue") - assert result == [0, 1, 2, 3] + assert len(result) == 1 + assert result[0].indices == [0, 1, 2, 3] From 5ea1ef78bfab821378d2f14564816aaa13cf1ded Mon Sep 17 00:00:00 2001 From: skfegan Date: Thu, 12 Nov 2026 16:23:45 +0000 Subject: [PATCH 07/16] unit tests for levels/dihedrals/dihedral_finder.py --- .../levels/dihedrals/test_dihedral_finder.py | 143 +++++++++++++++++- 1 file changed, 142 insertions(+), 1 deletion(-) diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py index f602e3a0..1656c1c2 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -98,7 +98,9 @@ def __add__(self, other: FakeAtomGroup) -> FakeAtomGroup: ) def select_atoms(self, select_string: str, updating: bool = False) -> Any: - if select_string not in self._select_map: + 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] @@ -157,3 +159,142 @@ def test_method_res_bonds_res(): 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] From c4217ed7d3f6f6b0cca340786c6501085d70da73 Mon Sep 17 00:00:00 2001 From: skfegan Date: Fri, 13 Nov 2026 12:57:33 +0000 Subject: [PATCH 08/16] updating docs --- docs/source/getting_started.rst | 6 +++++- docs/source/science.rst | 8 ++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/source/getting_started.rst b/docs/source/getting_started.rst index 609bae07..6250b4fb 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`` @@ -220,6 +220,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). From bb1067579dabd16e0b0240a1cc80f6beef379019 Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Mon, 30 Nov 2026 11:14:48 +0000 Subject: [PATCH 09/16] tests(unit): mock the full residues path like in MDAnlaysis --- .../levels/dihedrals/test_dihedral_finder.py | 100 ++++++++++++++---- 1 file changed, 78 insertions(+), 22 deletions(-) diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py index 1656c1c2..8723c767 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -13,6 +13,7 @@ class FakeAtom: index: int bonded_atoms: Any = None + position: tuple[float, float, float] = (0.0, 0.0, 0.0) class FakeUniverseAtoms: @@ -72,7 +73,7 @@ def __init__( universe: FakeUniverse | None = None, ) -> None: self._atoms = list(atoms) - self.residues = list(residues or []) + self.residues = FakeResidueGroup(residues or []) self.dihedrals = list(dihedrals or []) self._select_map = dict(select_map or {}) self.universe = universe @@ -88,12 +89,29 @@ def indices(self) -> list[int]: def __iter__(self): return iter(self._atoms) + def __getitem__(self, index: int) -> FakeAtomGroup: + return FakeAtomGroup([self._atoms[index]], universe=self.universe) + + 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, ) @@ -110,6 +128,15 @@ 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 @@ -185,21 +212,25 @@ 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), resindex=atom.index) + for atom in atoms + ] - residues = [FakeResidue(FakeAtomGroup([atom], universe=universe)) 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, - dihedrals=[dihedral], + select_map=select_map, universe=universe, ) @@ -231,21 +262,34 @@ def test_method_res_pairs_ua(): def test_method_res_pairs_res(): dd = DihedralDefinitions() - atoms = [FakeAtom(index) for index in range(2)] + atoms = [FakeAtom(index, position=(float(index), 0.0, 0.0)) for index in range(4)] universe = FakeUniverse(atoms) - atom_group = FakeAtomGroup(atoms, universe=universe) - dihedral = FakeDihedral(atom_group) - # Create bonds between consecutive residues. + # 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]], 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] + 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, - dihedrals=[dihedral], + select_map=select_map, universe=universe, ) @@ -282,15 +326,27 @@ def test_method_ua_backbone_res(): 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) + 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, - dihedrals=[dihedral], residues=residues, - select_map={"name H and not name H": backbone}, + select_map=select_map, universe=universe, ) From 858373a932538b4a8e1643f0e6dbee72e71ac2a5 Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Mon, 30 Nov 2026 11:20:51 +0000 Subject: [PATCH 10/16] fix(dihedrals): use global resindex in `res_points` point search --- .../levels/dihedrals/dihedral_finder.py | 2 +- .../levels/dihedrals/test_dihedral_finder.py | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/CodeEntropy/levels/dihedrals/dihedral_finder.py b/CodeEntropy/levels/dihedrals/dihedral_finder.py index 32aaf7fb..32ffbc4e 100644 --- a/CodeEntropy/levels/dihedrals/dihedral_finder.py +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -215,7 +215,7 @@ def method_res_points(self, data_container: Any, level: str) -> list[Any]: 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}" + f" and resindex {index}" ) if len(atom_search) == 0: point[residue] = edges[0] diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py index 8723c767..5b7aa341 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -240,6 +240,46 @@ def test_method_res_points_res(): 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_ua(): dd = DihedralDefinitions() atoms = [FakeAtom(index) for index in range(4)] From 862829322284c0830c2004d4f3bb8d872a39005b Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Mon, 30 Nov 2026 11:38:29 +0000 Subject: [PATCH 11/16] fix(dihedrals): restrict residue-level `ua_backbone` dihedrals to the backbone --- .../levels/dihedrals/dihedral_finder.py | 66 ++++++-- .../levels/dihedrals/test_dihedral_finder.py | 150 +++++++++++++++--- 2 files changed, 181 insertions(+), 35 deletions(-) diff --git a/CodeEntropy/levels/dihedrals/dihedral_finder.py b/CodeEntropy/levels/dihedrals/dihedral_finder.py index 32ffbc4e..a7cd7906 100644 --- a/CodeEntropy/levels/dihedrals/dihedral_finder.py +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -18,6 +18,8 @@ import logging from typing import Any +import numpy as np + from CodeEntropy.levels.axes import AxesCalculator logger = logging.getLogger(__name__) @@ -137,12 +139,7 @@ def method_res_pairs(self, data_container: Any, level: str) -> list[Any]: 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] + atom1 = self._atom_near_center(data_container, residue1, index1) atom2 = self._atoms_in_source_bonded_to_target( residue1, residue2, @@ -151,12 +148,7 @@ def method_res_pairs(self, data_container: Any, level: str) -> list[Any]: 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] + atom4 = self._atom_near_center(data_container, residue2, index2) dihedral_atoms = atom1 + atom2 + atom3 + atom4 @@ -203,7 +195,7 @@ def method_res_points(self, data_container: Any, level: str) -> list[Any]: if level == "residue": num_residues = len(data_container.residues) - point: list[Any] = {} + point: dict[int, Any] = {} if num_residues >= 4: for residue in range(num_residues): atom_search = [] @@ -275,12 +267,54 @@ def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: backbone += atom logger.debug("backbone = %s", backbone) - dihedrals = backbone.dihedrals - for d in dihedrals: - atom_groups.append(d.atoms) + # ``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, diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py index 5b7aa341..cfd697e6 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -4,6 +4,8 @@ from typing import Any from unittest.mock import MagicMock +import numpy as np + from CodeEntropy.levels.dihedrals.dihedral_finder import DihedralDefinitions @@ -32,30 +34,11 @@ def __getitem__(self, indices: int | list[int] | tuple[int, ...]) -> Any: ) -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) @@ -92,6 +75,10 @@ def __iter__(self): 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( @@ -339,6 +326,80 @@ def test_method_res_pairs_res(): 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_ua(): dd = DihedralDefinitions() atoms = [FakeAtom(index) for index in range(4)] @@ -394,3 +455,54 @@ def test_method_ua_backbone_res(): 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]] From 090413322127d4558667f61f89c4642216c33aae Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Mon, 30 Nov 2026 12:03:05 +0000 Subject: [PATCH 12/16] fix(config): validate `conf_type` and repair its docs entryi --- CodeEntropy/config/argparse.py | 18 ++++++++++-- docs/source/getting_started.rst | 5 +++- .../CodeEntropy/config/argparse/conftest.py | 1 + .../argparse/test_argparse_validate_inputs.py | 28 +++++++++++++++++++ 4 files changed, 49 insertions(+), 3 deletions(-) diff --git a/CodeEntropy/config/argparse.py b/CodeEntropy/config/argparse.py index 497db316..3a3652f9 100644 --- a/CodeEntropy/config/argparse.py +++ b/CodeEntropy/config/argparse.py @@ -173,8 +173,9 @@ class ArgSpec: "conf_type": ArgSpec( type=str, default="ua_backbone", - help="Dihedral definition to use for conformational entropy." - "Default is 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, @@ -565,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 @@ -578,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/docs/source/getting_started.rst b/docs/source/getting_started.rst index 716035cf..f202cb70 100644 --- a/docs/source/getting_started.rst +++ b/docs/source/getting_started.rst @@ -225,8 +225,11 @@ The ``top_traj_file`` argument is required; other arguments have default values. - ``RAD`` - ``str`` * - ``--conf_type`` - - Method for identifying the residue level dihedrals for conformational entropy. + - 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/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"), [ From f33963f7e23af5cab6ecb75ddaca27b4717d3ad0 Mon Sep 17 00:00:00 2001 From: harryswift01 Date: Mon, 30 Nov 2026 12:46:26 +0000 Subject: [PATCH 13/16] chore(test): restrict coverage measurement to `CodeEntropy` package --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) 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" From d56c95595d56302281bf8e119d7cca01c48e7709 Mon Sep 17 00:00:00 2001 From: skfegan Date: Mon, 30 Nov 2026 16:45:50 +0000 Subject: [PATCH 14/16] Tidying up --- .../levels/dihedrals/dihedral_finder.py | 49 +----------- CodeEntropy/levels/dihedrals/topology.py | 17 +++- .../levels/dihedrals/test_dihedral_finder.py | 80 ------------------- 3 files changed, 17 insertions(+), 129 deletions(-) diff --git a/CodeEntropy/levels/dihedrals/dihedral_finder.py b/CodeEntropy/levels/dihedrals/dihedral_finder.py index a7cd7906..bb025a19 100644 --- a/CodeEntropy/levels/dihedrals/dihedral_finder.py +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -48,18 +48,6 @@ def method_res_bonds(self, data_container: Any, level: str) -> list[Any]: """ 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: @@ -118,18 +106,6 @@ def method_res_pairs(self, data_container: Any, level: str) -> list[Any]: """ 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: @@ -181,18 +157,6 @@ def method_res_points(self, data_container: Any, level: str) -> list[Any]: """ 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: dict[int, Any] = {} @@ -237,18 +201,6 @@ def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: """ 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") @@ -263,6 +215,7 @@ def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: backbone += edges elif len(edges) == 2: chain = self._axes.get_chain(residue, edges[0], edges[1]) + chain.append(edges) # since get_chain returns chain[1:-1] for atom in chain: backbone += atom diff --git a/CodeEntropy/levels/dihedrals/topology.py b/CodeEntropy/levels/dihedrals/topology.py index ff65633d..ca54c467 100644 --- a/CodeEntropy/levels/dihedrals/topology.py +++ b/CodeEntropy/levels/dihedrals/topology.py @@ -40,6 +40,9 @@ class MoleculeDihedralTopology: class DihedralTopologyDiscovery: """Discover molecule-level dihedral definitions for conformational analysis.""" + def __init__(self): + self._dihedral_definitions = DihedralDefinitions() + def _discover_group_dihedral_topology( self, data_container: Any, @@ -145,7 +148,19 @@ def _get_dihedrals( 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_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) + 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( diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py index cfd697e6..bd524155 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_dihedral_finder.py @@ -133,26 +133,6 @@ class FakeDihedral: 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)] @@ -175,26 +155,6 @@ def test_method_res_bonds_res(): 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)] @@ -267,26 +227,6 @@ def test_method_res_points_res_uses_global_resindex_for_point_search(): assert result[0].indices == [1, 3, 5, 7] -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, position=(float(index), 0.0, 0.0)) for index in range(4)] @@ -400,26 +340,6 @@ def test_method_res_pairs_res_skips_pairs_with_multiple_bonds(): assert result == [] -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)] From ce6d23d086e1fb0b10678ee07f9abdbf235a5644 Mon Sep 17 00:00:00 2001 From: skfegan Date: Mon, 30 Nov 2026 17:32:29 +0000 Subject: [PATCH 15/16] fixing set up of DihedralDefinitions --- .../levels/dihedrals/conformational_state_builder.py | 2 ++ CodeEntropy/levels/dihedrals/dihedral_finder.py | 6 +++++- CodeEntropy/levels/dihedrals/topology.py | 5 ----- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CodeEntropy/levels/dihedrals/conformational_state_builder.py b/CodeEntropy/levels/dihedrals/conformational_state_builder.py index c96b7f2c..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, diff --git a/CodeEntropy/levels/dihedrals/dihedral_finder.py b/CodeEntropy/levels/dihedrals/dihedral_finder.py index bb025a19..2541520d 100644 --- a/CodeEntropy/levels/dihedrals/dihedral_finder.py +++ b/CodeEntropy/levels/dihedrals/dihedral_finder.py @@ -215,7 +215,11 @@ def method_ua_backbone(self, data_container: Any, level: str) -> list[Any]: backbone += edges elif len(edges) == 2: chain = self._axes.get_chain(residue, edges[0], edges[1]) - chain.append(edges) # since get_chain returns chain[1:-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 diff --git a/CodeEntropy/levels/dihedrals/topology.py b/CodeEntropy/levels/dihedrals/topology.py index ca54c467..d636ea57 100644 --- a/CodeEntropy/levels/dihedrals/topology.py +++ b/CodeEntropy/levels/dihedrals/topology.py @@ -11,8 +11,6 @@ from dataclasses import dataclass from typing import Any -from CodeEntropy.levels.dihedrals.dihedral_finder import DihedralDefinitions - logger = logging.getLogger(__name__) @@ -40,9 +38,6 @@ class MoleculeDihedralTopology: class DihedralTopologyDiscovery: """Discover molecule-level dihedral definitions for conformational analysis.""" - def __init__(self): - self._dihedral_definitions = DihedralDefinitions() - def _discover_group_dihedral_topology( self, data_container: Any, From c9e197af309bbde0164743b5f6971763ff08644b Mon Sep 17 00:00:00 2001 From: skfegan Date: Tue, 1 Dec 2026 09:09:27 +0000 Subject: [PATCH 16/16] fixing unit tests --- tests/unit/CodeEntropy/levels/dihedrals/test_topology.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/unit/CodeEntropy/levels/dihedrals/test_topology.py b/tests/unit/CodeEntropy/levels/dihedrals/test_topology.py index 18324618..187e8fa0 100644 --- a/tests/unit/CodeEntropy/levels/dihedrals/test_topology.py +++ b/tests/unit/CodeEntropy/levels/dihedrals/test_topology.py @@ -8,6 +8,7 @@ import pytest +from CodeEntropy.levels.dihedrals.dihedral_finder import DihedralDefinitions from CodeEntropy.levels.dihedrals.topology import ( DihedralTopologyDiscovery, MoleculeDihedralTopology, @@ -109,6 +110,7 @@ def _make_discovery( ) -> DihedralTopologyDiscovery: discovery = DihedralTopologyDiscovery() discovery._universe_operations = universe_operations or Mock() + discovery._dihedral_definitions = DihedralDefinitions() return discovery