From 2a4bf2f8267943192db30183bfbcfc4ed4abd812 Mon Sep 17 00:00:00 2001 From: skfegan Date: Mon, 27 Jul 2026 11:07:16 +0100 Subject: [PATCH 1/8] 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 2/8] 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 3/8] 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 4/8] 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 5/8] 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 6/8] 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 7/8] 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 8/8] 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).