Skip to content

Commit eedd9d1

Browse files
committed
adding basic orientational entropy
1 parent 8e5a901 commit eedd9d1

12 files changed

Lines changed: 666 additions & 117 deletions

File tree

‎CodeEntropy/config/argparse.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,12 @@ class ArgSpec:
142142
default=True,
143143
help="Use bonded axes to rotate forces for UA level vibrational entropies",
144144
),
145+
"search_type": ArgSpec(
146+
type=str,
147+
default="RAD",
148+
help="Type of neighbor search to use."
149+
"Default RAD; grid search is also available",
150+
),
145151
}
146152

147153

‎CodeEntropy/entropy/configurational.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def _find_histogram_peaks(phi: np.ndarray, bin_width: int) -> np.ndarray:
221221
left = popul[idx - 1] if idx > 0 else popul[number_bins - 1]
222222
right = popul[idx + 1] if idx < number_bins - 1 else popul[0]
223223

224-
if popul[idx] >= left and popul[idx] >= right:
224+
if popul[idx] >= left and popul[idx] > right:
225225
peaks.append(float(bin_centers[idx]))
226226

227227
return np.asarray(peaks, dtype=float)

‎CodeEntropy/entropy/graph.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
from CodeEntropy.entropy.nodes.aggregate import AggregateEntropyNode
2323
from CodeEntropy.entropy.nodes.configurational import ConfigurationalEntropyNode
24+
from CodeEntropy.entropy.nodes.orientational import OrientationalEntropyNode
2425
from CodeEntropy.entropy.nodes.vibrational import VibrationalEntropyNode
2526

2627
logger = logging.getLogger(__name__)
@@ -68,10 +69,15 @@ def build(self) -> "EntropyGraph":
6869
specs = (
6970
NodeSpec("vibrational_entropy", VibrationalEntropyNode()),
7071
NodeSpec("configurational_entropy", ConfigurationalEntropyNode()),
72+
NodeSpec("orientational_entropy", OrientationalEntropyNode()),
7173
NodeSpec(
7274
"aggregate_entropy",
7375
AggregateEntropyNode(),
74-
deps=("vibrational_entropy", "configurational_entropy"),
76+
deps=(
77+
"vibrational_entropy",
78+
"configurational_entropy",
79+
"orientational_entropy",
80+
),
7581
),
7682
)
7783

‎CodeEntropy/entropy/nodes/aggregate.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class AggregateEntropyNode:
2525

2626
vibrational_key: str = "vibrational_entropy"
2727
configurational_key: str = "configurational_entropy"
28+
orientational_key: str = "orientational_entropy"
2829
output_key: str = "entropy_results"
2930

3031
def run(
@@ -69,6 +70,9 @@ def _collect_entropy_results(
6970
"configurational_entropy": self._get_optional(
7071
shared_data, self.configurational_key
7172
),
73+
"orientational_entropy": self._get_optional(
74+
shared_data, self.orientational_key
75+
),
7276
}
7377

7478
@staticmethod
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
"""Node for computing orientational entropy from neighbors."""
2+
3+
from __future__ import annotations
4+
5+
import logging
6+
from typing import (
7+
Any,
8+
Dict,
9+
MutableMapping,
10+
Sequence,
11+
Tuple,
12+
Union,
13+
)
14+
15+
import numpy as np
16+
17+
from CodeEntropy.entropy.orientational import OrientationalEntropy
18+
19+
logger = logging.getLogger(__name__)
20+
21+
GroupId = int
22+
ResidueId = int
23+
StateKey = Tuple[GroupId, ResidueId]
24+
StateSequence = Union[Sequence[Any], np.ndarray]
25+
26+
27+
class OrientationalEntropyNode:
28+
"""Compute orientational entropy using precomputed neighbors and symmetry.
29+
30+
This node reads number of neighbors and symmetry from ``shared_data`` and
31+
computes entropy contributions at the molecular (highest) level.
32+
33+
Results are written back into ``shared_data["orientational_entropy"]``.
34+
"""
35+
36+
def run(self, shared_data: MutableMapping[str, Any], **_: Any) -> Dict[str, Any]:
37+
"""Execute orientational entropy calculation.
38+
39+
Args:
40+
shared_data: Shared workflow state dictionary.
41+
42+
Returns:
43+
Dictionary containing orientational entropy results.
44+
45+
Raises:
46+
KeyError: If required keys are missing.
47+
"""
48+
groups = shared_data["groups"]
49+
levels = shared_data["levels"]
50+
neighbors = shared_data["neighbors"]
51+
symmetry_number = shared_data["symmetry_number"]
52+
linear = shared_data["linear"]
53+
reporter = shared_data.get("reporter")
54+
55+
oe = self._build_entropy_engine()
56+
57+
results: Dict[int, float] = {}
58+
59+
for group_id, mol_ids in groups.items():
60+
rep_mol_id = mol_ids[0]
61+
highest_level = levels[rep_mol_id][-1]
62+
63+
neighbor = neighbors[group_id]
64+
symmetry = symmetry_number[group_id]
65+
line = linear[group_id]
66+
67+
results[group_id] = oe.calculate_orientational(
68+
neighbor,
69+
symmetry,
70+
line,
71+
)
72+
73+
if reporter is not None:
74+
reporter.add_results_data(
75+
group_id, highest_level, "Orientational", results
76+
)
77+
78+
shared_data["orientational_entropy"] = results
79+
80+
return {"orientational_entropy": results}
81+
82+
def _build_entropy_engine(self) -> OrientationalEntropy:
83+
"""Create the entropy calculation engine."""
84+
return OrientationalEntropy()
Lines changed: 38 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
11
"""Orientational entropy calculations.
22
33
This module defines `OrientationalEntropy`, which computes orientational entropy
4-
from a neighbor-count mapping.
5-
6-
The current implementation supports non-water neighbors. Water-specific behavior
7-
can be implemented later behind an interface so the core calculation remains
8-
stable and testable.
4+
from a neighbour count and symmetry information.
95
"""
106

117
from __future__ import annotations
128

139
import logging
1410
import math
1511
from dataclasses import dataclass
16-
from typing import Any, Mapping
1712

1813
import numpy as np
1914

@@ -48,111 +43,77 @@ class OrientationalEntropy:
4843

4944
def __init__(
5045
self,
51-
run_manager: Any,
52-
args: Any,
53-
universe: Any,
54-
reporter: Any,
55-
group_molecules: Any,
5646
gas_constant: float = _GAS_CONST_J_PER_MOL_K,
5747
) -> None:
5848
"""Initialize the orientational entropy calculator.
5949
6050
Args:
61-
run_manager: Run manager (currently unused by this class).
62-
args: User arguments (currently unused by this class).
63-
universe: MDAnalysis Universe (currently unused by this class).
64-
reporter: Data logger (currently unused by this class).
65-
group_molecules: Grouping helper (currently unused by this class).
6651
gas_constant: Gas constant in J/(mol*K).
6752
"""
68-
self._run_manager = run_manager
69-
self._args = args
70-
self._universe = universe
71-
self._reporter = reporter
72-
self._group_molecules = group_molecules
7353
self._gas_constant = float(gas_constant)
7454

75-
def calculate(self, neighbours: Mapping[str, int]) -> OrientationalEntropyResult:
76-
"""Calculate orientational entropy from neighbor counts.
77-
78-
For each neighbor species (except water), the number of orientations is
79-
estimated as:
55+
def calculate_orientational(
56+
self,
57+
neighbour_count: float,
58+
symmetry_number: int,
59+
linear: bool,
60+
) -> OrientationalEntropyResult:
61+
"""Calculate orientational entropy from neighbour counts.
8062
81-
Ω = sqrt(Nc^3 * π)
63+
The number of orientations is estimated as:
64+
Ω = sqrt(N_av^3 * π)/symmetry_number for non-linear molecules
65+
Ω = N_av / symmetry_number for linear molecules
8266
8367
and the entropy contribution is:
8468
8569
S = R * ln(Ω)
8670
87-
where Nc is the neighbor count and R is the gas constant.
71+
where N_av is the average number of neighbours and R is the gas constant.
8872
8973
Args:
90-
neighbours: Mapping of neighbor species name to count.
74+
neighbours: average number of neighbours
75+
symmetry_number: symmetry number of molecule of interest
76+
linear: True if molecule of interest is linear
9177
9278
Returns:
9379
OrientationalEntropyResult containing the total entropy in J/mol/K.
94-
"""
95-
total = 0.0
96-
for species, count in neighbours.items():
97-
if self._is_water(species):
98-
logger.debug(
99-
"Skipping water species %s in orientational entropy.", species
100-
)
101-
continue
102-
103-
contribution = self._entropy_contribution(count)
104-
logger.debug(
105-
"Orientational entropy contribution for %s: %s", species, contribution
106-
)
107-
total += contribution
108-
109-
logger.debug("Final orientational entropy total: %s", total)
110-
return OrientationalEntropyResult(total=float(total))
111-
112-
@staticmethod
113-
def _is_water(species: str) -> bool:
114-
"""Return True if the species should be treated as water.
115-
116-
Args:
117-
species: Species identifier.
118-
119-
Returns:
120-
True if the species is considered water.
121-
"""
122-
return species in {"H2O", "WAT", "HOH"}
123-
124-
def _entropy_contribution(self, neighbour_count: int) -> float:
125-
"""Compute the entropy contribution for a single neighbor count.
126-
127-
Args:
128-
neighbour_count: Number of neighbors (Nc).
129-
130-
Returns:
131-
Entropy contribution in J/mol/K.
13280
13381
Raises:
134-
ValueError: If neighbour_count is negative.
82+
ValueError if number of neighbours is negative.
13583
"""
13684
if neighbour_count < 0:
13785
raise ValueError(f"neighbour_count must be >= 0, got {neighbour_count}")
13886

139-
if neighbour_count == 0:
140-
return 0.0
87+
omega = self._omega(neighbour_count, symmetry_number, linear)
14188

142-
omega = self._omega(neighbour_count)
143-
if omega <= 0.0:
144-
return 0.0
89+
total = self._gas_constant * math.log(omega)
90+
logger.debug("Orientational entropy total: %s", total)
14591

146-
return self._gas_constant * math.log(omega)
92+
return OrientationalEntropyResult(total=float(total))
14793

14894
@staticmethod
149-
def _omega(neighbour_count: int) -> float:
95+
def _omega(neighbour_count: int, symmetry: int, linear: bool) -> float:
15096
"""Compute the number of orientations Ω.
15197
15298
Args:
153-
neighbour_count: Number of neighbors (Nc).
99+
neighbour_count: average number of neighbours.
100+
symmetry_number: The symmetry number of the molecule.
101+
linear: Is the molecule linear (True or False).
154102
155103
Returns:
156104
Ω (unitless).
157105
"""
158-
return float(np.sqrt((neighbour_count**3) * math.pi))
106+
# symmetry number 0 = spherically symmetric = no orientational entropy
107+
if symmetry == 0:
108+
omega = 1
109+
else:
110+
if linear:
111+
omega = neighbour_count / symmetry
112+
else:
113+
omega = np.sqrt((neighbour_count**3) * math.pi) / symmetry
114+
115+
# avoid negative orientational entropy
116+
if omega < 1:
117+
omega = 1
118+
119+
return omega

‎CodeEntropy/levels/dihedrals.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -362,13 +362,13 @@ def _find_histogram_peaks(popul, bin_value):
362362
if bin_index == number_bins - 1:
363363
if (
364364
popul[bin_index] >= popul[bin_index - 1]
365-
and popul[bin_index] >= popul[0]
365+
and popul[bin_index] > popul[0]
366366
):
367367
peaks.append(bin_value[bin_index])
368368
else:
369369
if (
370370
popul[bin_index] >= popul[bin_index - 1]
371-
and popul[bin_index] >= popul[bin_index + 1]
371+
and popul[bin_index] > popul[bin_index + 1]
372372
):
373373
peaks.append(bin_value[bin_index])
374374

‎CodeEntropy/levels/level_dag.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from CodeEntropy.levels.nodes.conformations import ComputeConformationalStatesNode
2929
from CodeEntropy.levels.nodes.detect_levels import DetectLevelsNode
3030
from CodeEntropy.levels.nodes.detect_molecules import DetectMoleculesNode
31+
from CodeEntropy.levels.nodes.find_neighbors import ComputeNeighborsNode
3132

3233
logger = logging.getLogger(__name__)
3334

@@ -81,6 +82,9 @@ def build(self) -> "LevelDAG":
8182
ComputeConformationalStatesNode(self._universe_operations),
8283
deps=["detect_levels"],
8384
)
85+
self._add_static(
86+
"find_neighbors", ComputeNeighborsNode(), deps=["detect_levels"]
87+
)
8488

8589
self._frame_dag.build()
8690
return self

0 commit comments

Comments
 (0)