diff --git a/CodeEntropy/config/argparse.py b/CodeEntropy/config/argparse.py index 781cdb98..9fdd37a6 100644 --- a/CodeEntropy/config/argparse.py +++ b/CodeEntropy/config/argparse.py @@ -170,6 +170,16 @@ class ArgSpec: help="Type of neighbour search to use. Default is RAD; grid search is also " "available.", ), + "symmetry_number": ArgSpec( + type=str, + nargs="+", + default=None, + help="Rotational symmetry number (integer >= 0) for the orientational " + "entropy. VALUE applies to all molecule groups; RESNAME:VALUE applies to " + "molecules whose first residue has that name (e.g. 12 or MET:12 NH3:3). " + "0 means spherical (no orientational entropy). Default: computed from " + "the bond graph.", + ), "parallel_frames": ArgSpec( type=bool, default=False, @@ -263,6 +273,40 @@ class ArgSpec: } +def parse_symmetry_number(raw: Any) -> dict[str | None, int]: + """Parse the ``symmetry_number`` option. + + Each entry is either ``VALUE`` (applies to all molecule groups) or + ``RESNAME:VALUE`` (applies to molecules whose first residue has that name). + + Args: + raw: ``None``, a single value, or a list of entries from the CLI or YAML. + + Returns: + Mapping of residue name to symmetry number. The key ``None`` holds the + value for all groups. Empty if ``raw`` is ``None``. + + Raises: + ValueError: If an entry is malformed, negative, not an integer, or + duplicated. + """ + if raw is None: + return {} + result: dict[str | None, int] = {} + for item in raw if isinstance(raw, list) else [raw]: + name, sep, value = str(item).strip().rpartition(":") + name = name.strip() or None + if (sep and name is None) or not value.strip().isdigit(): + raise ValueError( + f"Invalid 'symmetry_number' entry: {item!r}. " + "Use an integer >= 0 or RESNAME:VALUE." + ) + if name in result: + raise ValueError(f"Duplicate 'symmetry_number' entry: {item!r}.") + result[name] = int(value) + return result + + class ConfigResolver: """Load, merge, and validate CodeEntropy configuration.""" @@ -515,6 +559,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_symmetry_number(args) @staticmethod def _check_input_axes(args: argparse.Namespace) -> None: @@ -588,6 +633,17 @@ def _check_input_force_partitioning(self, args: argparse.Namespace) -> None: default_value, ) + @staticmethod + def _check_input_symmetry_number(args: argparse.Namespace) -> None: + """Check symmetry_number entries are valid; warn on unusually large values.""" + values = parse_symmetry_number(getattr(args, "symmetry_number", None)) + for name, value in values.items(): + if value > 24: + logger.warning( + f"'symmetry_number' for {name or 'all groups'} is {value}; " + "values above 24 are unusual." + ) + @staticmethod def _check_parallel_frame_options(args: argparse.Namespace) -> None: """Validate local Dask, HPC Dask, and submit-related options.""" diff --git a/CodeEntropy/levels/graph/level_dag.py b/CodeEntropy/levels/graph/level_dag.py index e333c772..e5f6eeed 100644 --- a/CodeEntropy/levels/graph/level_dag.py +++ b/CodeEntropy/levels/graph/level_dag.py @@ -11,6 +11,7 @@ import networkx as nx +from CodeEntropy.config.argparse import parse_symmetry_number from CodeEntropy.levels.axes import AxesCalculator from CodeEntropy.levels.execution.policy import ExecutionPolicy from CodeEntropy.levels.execution.reducers import NeighborReducer @@ -189,7 +190,10 @@ def _initialise_neighbor_metadata(shared_data: dict[str, Any]) -> None: Args: shared_data: Shared workflow data containing ``groups`` and either ``reduced_universe`` or ``universe``. The method writes - ``symmetry_number`` and ``linear``. + ``symmetry_number`` and ``linear``. Values from + ``args.symmetry_number`` replace the computed symmetry numbers, + matched on the first residue name of each group's representative + molecule. Raises: KeyError: If ``groups`` is missing from ``shared_data``. @@ -202,5 +206,16 @@ def _initialise_neighbor_metadata(shared_data: dict[str, Any]) -> None: groups=shared_data["groups"], ) + overrides = parse_symmetry_number( + getattr(shared_data.get("args"), "symmetry_number", None) + ) + for group_id, mol_ids in shared_data["groups"].items(): + if not overrides or not mol_ids: + continue + resname = universe.atoms.fragments[mol_ids[0]].residues.resnames[0] + value = overrides.get(resname, overrides.get(None)) + if value is not None: + symmetry_number[group_id] = value + shared_data["symmetry_number"] = symmetry_number shared_data["linear"] = linear diff --git a/docs/source/getting_started.rst b/docs/source/getting_started.rst index f601cec3..c1413024 100644 --- a/docs/source/getting_started.rst +++ b/docs/source/getting_started.rst @@ -224,6 +224,14 @@ The ``top_traj_file`` argument is required; other arguments have default values. - Method for finding neighbouring molecules. - ``RAD`` - ``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 + molecule groups and ``RESNAME:VALUE`` to one residue name (e.g. ``12`` or + ``MET:12 NH3:3``). ``0`` means spherical (no orientational entropy). See + :ref:`symmetry-number`. + - computed + - ``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. @@ -509,6 +517,77 @@ There are currently two options, chosen by the ``search_type`` argument. * ``RAD`` (default): Uses the relative angular distance method. * ``grid``: Uses the MDAnalysis NeighborSearch method. +.. _symmetry-number: + +Symmetry Number +--------------- + +The orientational entropy is divided by the symmetry number :math:`\sigma` of the +molecule. By default, :math:`\sigma` is computed with RDKit as the number of ways the +molecule's bond graph can be mapped onto itself. This count includes reflections and +does not depend on the molecule's conformation, so it can be larger than the +rotational symmetry number (for example 24 instead of 12 for methane, and 6 instead +of 3 for ammonia). + +The ``symmetry_number`` argument replaces the computed value with the rotational +symmetry number, which is the order of the rotational subgroup of the molecule's +point group: + +.. list-table:: + :header-rows: 1 + + * - Point group + - :math:`\sigma` + - Example + * - C\ :sub:`1`, C\ :sub:`s` + - 1 + - methanol + * - C\ :sub:`2v` + - 2 + - water + * - C\ :sub:`3v` + - 3 + - ammonia + * - T\ :sub:`d` + - 12 + - methane + * - D\ :sub:`6h` + - 12 + - benzene + +``0`` is a special case for spherical molecules (for example, single atoms or ions), +which have no orientational entropy. Values for common liquids are between 1 and 12. +Values above 24 are rare (the largest is 60, for icosahedral molecules), so +CodeEntropy logs a warning for them. + +Each entry is either ``VALUE``, which applies to every molecule group, or +``RESNAME:VALUE``, which applies to molecules whose first residue has that name. A +``RESNAME:VALUE`` entry takes precedence over a plain ``VALUE``, and molecule groups +that match no entry keep the computed value. Residue names are matched on the +representative molecule of each group. + +.. code-block:: bash + + CodeEntropy --symmetry_number 12 # all molecule groups + CodeEntropy --symmetry_number MET:12 NH3:3 # per residue name + CodeEntropy --symmetry_number 1 MET:12 # 12 for MET, 1 for all others + +The same forms can be used in ``config.yaml``: + +.. code-block:: yaml + + run1: + top_traj_file: ["methane.tpr", "methane.trr"] + symmetry_number: 12 + + run2: + top_traj_file: ["mixture.tpr", "mixture.trr"] + symmetry_number: ["MET:12", "NH3:3"] + +.. note:: + + A plain ``VALUE`` also applies to water unless ``water_entropy`` is enabled. + Examples -------- diff --git a/docs/source/science.rst b/docs/source/science.rst index b42af0ac..9d69729f 100644 --- a/docs/source/science.rst +++ b/docs/source/science.rst @@ -126,6 +126,12 @@ CodeEntropy is using the united atom beads to determine if a molecule is treated where N is the number of neighbours the molecule has averaged over the number of frames and :math:`\sigma` is the symmetry number of the molecule. The max of 1 or the number of neighbours expression prevents the resulting orientational entropy value being less than zero. +By default, :math:`\sigma` is computed from the molecule's bond graph using RDKit. +This counts all permutations of the graph, including those that correspond to reflections, +so it can be larger than the rotational symmetry number of the point group (for example 24 instead of 12 for methane). +If :math:`\sigma` becomes larger than the neighbour term, :math:`\Omega_{\mathrm{orient}}` is limited to 1 and the orientational entropy is zero. +The rotational symmetry number can be set with the ``symmetry_number`` option, either as one value for all molecules or per residue name; a value of 0 is used for spherical molecules and gives zero orientational entropy. + .. math:: S_{\mathrm{orient}} = R \ln{ \Omega_{\mathrm{orient}} } diff --git a/tests/unit/CodeEntropy/config/argparse/test_argparse_build_parser.py b/tests/unit/CodeEntropy/config/argparse/test_argparse_build_parser.py index 3e55ce15..4cee696b 100644 --- a/tests/unit/CodeEntropy/config/argparse/test_argparse_build_parser.py +++ b/tests/unit/CodeEntropy/config/argparse/test_argparse_build_parser.py @@ -50,3 +50,34 @@ def test_version_flag_prints_installed_version_and_exits(capsys): assert exc.value.code == 0 assert f"CodeEntropy {__version__}" in capsys.readouterr().out + + +def test_build_parser_symmetry_number_defaults_to_none(): + parser = ConfigResolver().build_parser() + + args = parser.parse_args([]) + + assert args.symmetry_number is None + + +def test_build_parser_parses_single_symmetry_number(): + parser = ConfigResolver().build_parser() + + args = parser.parse_args(["--symmetry_number", "12"]) + + assert args.symmetry_number == ["12"] + + +def test_build_parser_parses_per_residue_symmetry_numbers(): + parser = ConfigResolver().build_parser() + + args = parser.parse_args(["--symmetry_number", "MET:12", "NH3:3"]) + + assert args.symmetry_number == ["MET:12", "NH3:3"] + + +def test_build_parser_symmetry_number_requires_a_value(): + parser = ConfigResolver().build_parser() + + with pytest.raises(SystemExit): + parser.parse_args(["--symmetry_number"]) 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 6fe60d63..4725f9e4 100644 --- a/tests/unit/CodeEntropy/config/argparse/test_argparse_validate_inputs.py +++ b/tests/unit/CodeEntropy/config/argparse/test_argparse_validate_inputs.py @@ -1,7 +1,10 @@ import logging +from types import SimpleNamespace import pytest +from CodeEntropy.config.argparse import parse_symmetry_number + def test_validate_inputs_valid_does_not_raise(resolver, dummy_universe, make_args): args = make_args() @@ -301,3 +304,86 @@ def test_check_input_axes_raises_for_invalid_values(resolver, make_args, value): with pytest.raises(ValueError, match="Invalid 'axes'"): resolver._check_input_axes(args) + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + (None, {}), + ([], {}), + (0, {None: 0}), + (12, {None: 12}), + ("12", {None: 12}), + (["12"], {None: 12}), + ([" 12 "], {None: 12}), + (["MET:12", "NH3:3"], {"MET": 12, "NH3": 3}), + ([" MET : 12 "], {"MET": 12}), + (["1", "MET:12"], {None: 1, "MET": 12}), + (["MET:0"], {"MET": 0}), + ], +) +def test_parse_symmetry_number_accepts_valid_entries(raw, expected): + assert parse_symmetry_number(raw) == expected + + +@pytest.mark.parametrize( + "raw", + [ + -1, + True, + 12.5, + "abc", + ["-1"], + ["MET:"], + [":3"], + ["MET:abc"], + ["MET:-1"], + ["MET:1", "MET:2"], + ["1", "2"], + ], +) +def test_parse_symmetry_number_rejects_invalid_entries(raw): + with pytest.raises(ValueError, match="'symmetry_number' entry"): + parse_symmetry_number(raw) + + +def test_check_input_symmetry_number_missing_attribute_does_not_raise(resolver): + resolver._check_input_symmetry_number(SimpleNamespace()) + + +@pytest.mark.parametrize("raw", [None, ["0"], ["24"], ["MET:12", "NH3:3"]]) +def test_check_input_symmetry_number_valid_does_not_warn( + resolver, make_args, raw, caplog +): + args = make_args(symmetry_number=raw) + + with caplog.at_level(logging.WARNING): + resolver._check_input_symmetry_number(args) + + assert args.symmetry_number == raw + assert "symmetry_number" not in caplog.text + + +@pytest.mark.parametrize( + ("raw", "label"), + [(["25"], "all groups"), ([60], "all groups"), (["MET:25"], "MET")], +) +def test_check_input_symmetry_number_large_value_logs_warning( + resolver, make_args, raw, label, caplog +): + args = make_args(symmetry_number=raw) + + with caplog.at_level(logging.WARNING): + resolver._check_input_symmetry_number(args) + + assert f"'symmetry_number' for {label}" in caplog.text + assert "values above 24 are unusual" in caplog.text + + +def test_validate_inputs_rejects_invalid_symmetry_number( + resolver, dummy_universe, make_args +): + args = make_args(symmetry_number=-1) + + with pytest.raises(ValueError, match="Invalid 'symmetry_number'"): + resolver.validate_inputs(dummy_universe, args) diff --git a/tests/unit/CodeEntropy/levels/test_level_dag.py b/tests/unit/CodeEntropy/levels/test_level_dag.py index 51674c73..88936d63 100644 --- a/tests/unit/CodeEntropy/levels/test_level_dag.py +++ b/tests/unit/CodeEntropy/levels/test_level_dag.py @@ -2,8 +2,11 @@ from __future__ import annotations +from types import SimpleNamespace from unittest.mock import MagicMock, call, patch +import pytest + from CodeEntropy.levels.graph.level_dag import LevelDAG @@ -204,6 +207,95 @@ def test_initialise_neighbor_metadata_writes_symmetry_and_linearity(): assert shared_data["linear"] == {0: False, 1: True} +def test_initialise_neighbor_metadata_keeps_computed_symmetry_when_unset(): + groups = {0: [0], 1: [1]} + shared_data = { + "reduced_universe": object(), + "groups": groups, + "args": SimpleNamespace(symmetry_number=None), + } + + with patch("CodeEntropy.levels.graph.level_dag.Neighbors") as Neighbors: + Neighbors.return_value.get_symmetry.return_value = ( + {0: 12, 1: 2}, + {0: False, 1: True}, + ) + + LevelDAG._initialise_neighbor_metadata(shared_data) + + assert shared_data["symmetry_number"] == {0: 12, 1: 2} + + +def _universe_with_resnames(*resnames_per_fragment): + fragments = [ + SimpleNamespace(residues=SimpleNamespace(resnames=list(resnames))) + for resnames in resnames_per_fragment + ] + return SimpleNamespace(atoms=SimpleNamespace(fragments=fragments)) + + +def _run_with_symmetry_override(universe, groups, computed, raw): + shared_data = { + "reduced_universe": universe, + "groups": groups, + "args": SimpleNamespace(symmetry_number=raw), + } + linear = dict.fromkeys(computed, False) + + with patch("CodeEntropy.levels.graph.level_dag.Neighbors") as Neighbors: + Neighbors.return_value.get_symmetry.return_value = (dict(computed), linear) + + LevelDAG._initialise_neighbor_metadata(shared_data) + + assert shared_data["linear"] == linear + return shared_data["symmetry_number"] + + +@pytest.mark.parametrize("value", [0, 1, 3, 60]) +def test_initialise_neighbor_metadata_applies_value_to_all_groups(value): + universe = _universe_with_resnames(["MET"], ["MET"], ["SOL"]) + groups = {0: [0, 1], 2: [2], 3: []} + + result = _run_with_symmetry_override( + universe, groups, {0: 24, 2: 6, 3: 0}, [str(value)] + ) + + assert result == {0: value, 2: value, 3: 0} + + +def test_initialise_neighbor_metadata_applies_per_residue_values(): + universe = _universe_with_resnames(["MET"], ["NH3"], ["SOL"]) + groups = {0: [0], 1: [1], 2: [2]} + + result = _run_with_symmetry_override( + universe, groups, {0: 24, 1: 6, 2: 2}, ["MET:12", "NH3:3", "XYZ:5"] + ) + + assert result == {0: 12, 1: 3, 2: 2} + + +def test_initialise_neighbor_metadata_residue_value_takes_precedence(): + universe = _universe_with_resnames(["MET"], ["SOL"]) + groups = {0: [0], 1: [1]} + + result = _run_with_symmetry_override( + universe, groups, {0: 24, 1: 2}, ["1", "MET:12"] + ) + + assert result == {0: 12, 1: 1} + + +def test_initialise_neighbor_metadata_matches_first_residue_of_representative(): + universe = _universe_with_resnames(["SOL"], ["LIG", "MET"]) + groups = {0: [1, 0]} + + matched = _run_with_symmetry_override(universe, groups, {0: 6}, ["LIG:2"]) + unmatched = _run_with_symmetry_override(universe, groups, {0: 6}, ["MET:2"]) + + assert matched == {0: 2} + assert unmatched == {0: 6} + + def test_initialise_neighbor_metadata_falls_back_to_universe_key(): universe = object() shared_data = {"universe": universe, "groups": {0: [0]}}