Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions CodeEntropy/config/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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."""
Expand Down
17 changes: 16 additions & 1 deletion CodeEntropy/levels/graph/level_dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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``.
Expand All @@ -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
79 changes: 79 additions & 0 deletions docs/source/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
--------
Expand Down
6 changes: 6 additions & 0 deletions docs/source/science.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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}} }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -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)
Loading
Loading