1010from __future__ import annotations
1111
1212import logging
13- from dataclasses import dataclass
14- from typing import Any , Optional
13+ from typing import Any
1514
1615import numpy as np
1716
1817logger = logging .getLogger (__name__ )
1918
2019
21- @dataclass (frozen = True )
22- class ConformationConfig :
23- """Configuration for assigning conformational states from a dihedral.
24-
25- Attributes:
26- bin_width: Histogram bin width in degrees for peak detection.
27- start: Inclusive start frame index for trajectory slicing.
28- end: Exclusive end frame index for trajectory slicing.
29- step: Stride for trajectory slicing (must be positive).
30- """
31-
32- bin_width : int
33- start : int
34- end : int
35- step : int
36-
37-
3820class ConformationalEntropy :
39- """Assign dihedral conformational states and compute conformational entropy.
40-
41- This class contains two independent responsibilities:
42- 1) `assign_conformation`: Map a single dihedral angle time series to discrete
43- state labels by detecting histogram peaks and assigning the nearest peak.
44- 2) `conformational_entropy_calculation`: Compute Shannon entropy of the
45- state distribution (in J/mol/K).
46-
47- Notes:
48- `number_frames` is accepted by `conformational_entropy_calculation` for
49- compatibility with calling sites that track frame counts, but the entropy
50- is computed from the observed state counts (i.e., `len(states)`), which is
51- the correct normalization for the sampled distribution.
52- """
21+ """Compute conformational entropy from states information."""
5322
5423 _GAS_CONST : float = 8.3144598484848
5524
@@ -61,69 +30,7 @@ def __init__(self) -> None:
6130 """
6231 pass
6332
64- def assign_conformation (
65- self ,
66- data_container : Any ,
67- dihedral : Any ,
68- number_frames : int ,
69- bin_width : int ,
70- start : int ,
71- end : int ,
72- step : int ,
73- ) -> np .ndarray :
74- """Assign discrete conformational states for a single dihedral.
75-
76- The dihedral angle time series is:
77- 1) Collected across the trajectory slice [start:end:step].
78- 2) Converted to [0, 360) degrees.
79- 3) Histogrammed using `bin_width`.
80- 4) Peaks are identified as bins with locally maximal population.
81- 5) Each frame is assigned the index of the nearest peak.
82-
83- Args:
84- data_container: MDAnalysis Universe/AtomGroup with a trajectory.
85- dihedral: Object providing `value()` for the current frame dihedral.
86- number_frames: Provided for call-site compatibility; not used for sizing.
87- bin_width: Histogram bin width in degrees.
88- start: Inclusive start frame index.
89- end: Exclusive end frame index.
90- step: Stride for trajectory slicing.
91-
92- Returns:
93- Array of integer state labels of length equal to the trajectory slice.
94- Returns an empty array if the slice is empty.
95-
96- Raises:
97- ValueError: If `bin_width` or `step` are invalid.
98- """
99- _ = number_frames
100-
101- config = ConformationConfig (
102- bin_width = int (bin_width ),
103- start = int (start ),
104- end = int (end ),
105- step = int (step ),
106- )
107- self ._validate_assignment_config (config )
108-
109- traj_slice = data_container .trajectory [config .start : config .end : config .step ]
110- n_slice = len (traj_slice )
111- if n_slice <= 0 :
112- return np .array ([], dtype = int )
113-
114- phi = self ._collect_dihedral_angles (traj_slice , dihedral )
115- peak_values = self ._find_histogram_peaks (phi , config .bin_width )
116-
117- if peak_values .size == 0 :
118- return np .zeros (n_slice , dtype = int )
119-
120- states = self ._assign_nearest_peaks (phi , peak_values )
121- logger .debug ("Final conformations: %s" , states )
122- return states
123-
124- def conformational_entropy_calculation (
125- self , states : Any , number_frames : int
126- ) -> float :
33+ def conformational_entropy_calculation (self , states : Any ) -> float :
12734 """Compute conformational entropy for a sequence of state labels.
12835
12936 Entropy is computed as:
@@ -139,8 +46,6 @@ def conformational_entropy_calculation(
13946 Returns:
14047 float: Conformational entropy in J/mol/K.
14148 """
142- _ = number_frames
143-
14449 arr = self ._to_1d_array (states )
14550 if arr is None or arr .size == 0 :
14651 return 0.0
@@ -154,96 +59,11 @@ def conformational_entropy_calculation(
15459 probs = probs [probs > 0.0 ]
15560
15661 s_conf = - self ._GAS_CONST * float (np .sum (probs * np .log (probs )))
157- logger .debug ("Total conformational entropy: %s" , s_conf )
62+ logger .debug (f "Total conformational entropy: { s_conf } " )
15863 return s_conf
15964
16065 @staticmethod
161- def _validate_assignment_config (config : ConformationConfig ) -> None :
162- """Validate conformation assignment configuration.
163-
164- Args:
165- config: Assignment configuration.
166-
167- Raises:
168- ValueError: If configuration values are invalid.
169- """
170- if config .step <= 0 :
171- raise ValueError ("step must be a positive integer" )
172- if config .bin_width <= 0 or config .bin_width > 360 :
173- raise ValueError ("bin_width must be in the range (0, 360]" )
174- if 360 % config .bin_width != 0 :
175- logger .warning (
176- "bin_width=%s does not evenly divide 360; histogram bins will be "
177- "uneven." ,
178- config .bin_width ,
179- )
180-
181- @staticmethod
182- def _collect_dihedral_angles (traj_slice : Any , dihedral : Any ) -> np .ndarray :
183- """Collect dihedral angles for each frame in the trajectory slice.
184-
185- Args:
186- traj_slice: Slice of a trajectory iterable where iterating advances frames.
187- dihedral: Object with `value()` returning the dihedral in degrees.
188-
189- Returns:
190- Array of dihedral values mapped into [0, 360).
191- """
192- phi = np .zeros (len (traj_slice ), dtype = float )
193- for i , _ts in enumerate (traj_slice ):
194- value = float (dihedral .value ())
195- if value < 0.0 :
196- value += 360.0
197- phi [i ] = value
198- return phi
199-
200- @staticmethod
201- def _find_histogram_peaks (phi : np .ndarray , bin_width : int ) -> np .ndarray :
202- """Identify peak bin centers from a histogram of dihedral angles.
203-
204- A peak is defined as a bin whose population is greater than or equal to
205- its immediate neighbors (with circular handling at the final bin).
206-
207- Args:
208- phi: Dihedral angles in degrees, in [0, 360).
209- bin_width: Histogram bin width in degrees.
210-
211- Returns:
212- 1D array of peak bin center values (degrees). Empty if no peaks found.
213- """
214- number_bins = int (360 / bin_width )
215- popul , bin_edges = np .histogram (phi , bins = number_bins , range = (0.0 , 360.0 ))
216- bin_centers = 0.5 * (bin_edges [:- 1 ] + bin_edges [1 :])
217-
218- peaks : list [float ] = []
219- for idx in range (number_bins ):
220- if popul [idx ] == 0 :
221- continue
222-
223- left = popul [idx - 1 ] if idx > 0 else popul [number_bins - 1 ]
224- right = popul [idx + 1 ] if idx < number_bins - 1 else popul [0 ]
225-
226- if popul [idx ] >= left and popul [idx ] > right :
227- peaks .append (float (bin_centers [idx ]))
228-
229- return np .asarray (peaks , dtype = float )
230-
231- @staticmethod
232- def _assign_nearest_peaks (phi : np .ndarray , peak_values : np .ndarray ) -> np .ndarray :
233- """Assign each phi value to the index of its nearest peak.
234-
235- Args:
236- phi: Dihedral angles in degrees.
237- peak_values: Peak centers (degrees).
238-
239- Returns:
240- Integer state labels aligned with `phi`.
241- """
242- distances = np .abs (phi [:, None ] - peak_values [None , :])
243- return np .argmin (distances , axis = 1 ).astype (int )
244-
245- @staticmethod
246- def _to_1d_array (states : Any ) -> Optional [np .ndarray ]:
66+ def _to_1d_array (states : Any ) -> np .ndarray | None :
24767 """Convert a state sequence into a 1D numpy array.
24868
24969 Args:
0 commit comments