Skip to content

Commit 44bd758

Browse files
committed
tidy up code
1 parent a694bd0 commit 44bd758

38 files changed

Lines changed: 562 additions & 685 deletions

‎CodeEntropy/config/argparse.py‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
import logging
2626
import os
2727
from dataclasses import dataclass
28-
from typing import Any, Dict, Optional, Set
28+
from typing import Any
2929

3030
import yaml
3131

@@ -48,11 +48,11 @@ class ArgSpec:
4848
help: str
4949
default: Any = None
5050
type: Any = None
51-
action: Optional[str] = None
52-
nargs: Optional[str] = None
51+
action: str | None = None
52+
nargs: str | None = None
5353

5454

55-
ARG_SPECS: Dict[str, ArgSpec] = {
55+
ARG_SPECS: dict[str, ArgSpec] = {
5656
"top_traj_file": ArgSpec(
5757
type=str,
5858
nargs="+",
@@ -165,7 +165,7 @@ class ConfigResolver:
165165
- validating trajectory-related numeric parameters
166166
"""
167167

168-
def __init__(self, arg_specs: Optional[Dict[str, ArgSpec]] = None) -> None:
168+
def __init__(self, arg_specs: dict[str, ArgSpec] | None = None) -> None:
169169
"""Initialize the manager.
170170
171171
Args:
@@ -174,7 +174,7 @@ def __init__(self, arg_specs: Optional[Dict[str, ArgSpec]] = None) -> None:
174174
"""
175175
self._arg_specs = dict(arg_specs or ARG_SPECS)
176176

177-
def load_config(self, directory_path: str) -> Dict[str, Any]:
177+
def load_config(self, directory_path: str) -> dict[str, Any]:
178178
"""Load the first YAML config file found in a directory.
179179
180180
The current behavior matches your existing workflow:
@@ -194,7 +194,7 @@ def load_config(self, directory_path: str) -> Dict[str, Any]:
194194

195195
config_path = yaml_files[0]
196196
try:
197-
with open(config_path, "r", encoding="utf-8") as file:
197+
with open(config_path, encoding="utf-8") as file:
198198
config = yaml.safe_load(file) or {"run1": {}}
199199
logger.info("Loaded configuration from: %s", config_path)
200200
return config
@@ -259,7 +259,7 @@ def build_parser(self) -> argparse.ArgumentParser:
259259
)
260260
continue
261261

262-
kwargs: Dict[str, Any] = {}
262+
kwargs: dict[str, Any] = {}
263263
if spec.type is not None:
264264
kwargs["type"] = spec.type
265265
if spec.default is not None:
@@ -272,7 +272,7 @@ def build_parser(self) -> argparse.ArgumentParser:
272272
return parser
273273

274274
def resolve(
275-
self, args: argparse.Namespace, run_config: Optional[Dict[str, Any]]
275+
self, args: argparse.Namespace, run_config: dict[str, Any] | None
276276
) -> argparse.Namespace:
277277
"""Merge CLI arguments with YAML configuration and adjust logging level.
278278
@@ -312,8 +312,8 @@ def resolve(
312312

313313
@staticmethod
314314
def _detect_cli_overrides(
315-
args_dict: Dict[str, Any], default_dict: Dict[str, Any]
316-
) -> Set[str]:
315+
args_dict: dict[str, Any], default_dict: dict[str, Any]
316+
) -> set[str]:
317317
"""Detect which args were explicitly overridden in the CLI.
318318
319319
Args:
@@ -328,8 +328,8 @@ def _detect_cli_overrides(
328328
def _apply_yaml_defaults(
329329
self,
330330
args: argparse.Namespace,
331-
run_config: Dict[str, Any],
332-
cli_provided: Set[str],
331+
run_config: dict[str, Any],
332+
cli_provided: set[str],
333333
) -> None:
334334
"""Apply YAML values onto args for keys not provided by CLI.
335335
@@ -342,7 +342,7 @@ def _apply_yaml_defaults(
342342
if yaml_value is None or key in cli_provided:
343343
continue
344344
if key in self._arg_specs:
345-
logger.debug("Using YAML value for %s: %s", key, yaml_value)
345+
logger.debug(f"Using YAML value for {key}: {yaml_value}")
346346
setattr(args, key, yaml_value)
347347

348348
def _ensure_defaults(self, args: argparse.Namespace) -> None:

‎CodeEntropy/config/runtime.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import logging
1919
import os
2020
import pickle
21-
from typing import Any, Dict, Optional
21+
from typing import Any
2222

2323
import MDAnalysis as mda
2424
import requests
@@ -112,7 +112,7 @@ def create_job_folder() -> str:
112112

113113
return new_folder_path
114114

115-
def load_citation_data(self) -> Optional[Dict[str, Any]]:
115+
def load_citation_data(self) -> dict[str, Any] | None:
116116
"""Load CITATION.cff from GitHub.
117117
118118
If the request fails (offline, blocked, etc.), returns None.
@@ -335,7 +335,7 @@ def _build_universe(
335335
kcal_units = args.kcal_force_units
336336

337337
if forcefile is None:
338-
logger.debug("Loading Universe with %s and %s", tprfile, trrfile)
338+
logger.debug(f"Loading Universe with {tprfile} and {trrfile}")
339339
return mda.Universe(tprfile, trrfile, format=fileformat)
340340

341341
return universe_operations.merge_forces(

‎CodeEntropy/core/logging.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616

1717
import logging
1818
import os
19-
from typing import Dict, Optional
2019

2120
from rich.console import Console
2221
from rich.logging import RichHandler
@@ -55,7 +54,7 @@ class LoggingConfig:
5554
handlers: Mapping of handler name to handler instance.
5655
"""
5756

58-
_console: Optional[Console] = None
57+
_console: Console | None = None
5958

6059
@classmethod
6160
def get_console(cls) -> Console:
@@ -80,7 +79,7 @@ def __init__(self, folder: str, level: int = logging.INFO) -> None:
8079

8180
self.level = level
8281
self.console = self.get_console()
83-
self.handlers: Dict[str, logging.Handler] = {}
82+
self.handlers: dict[str, logging.Handler] = {}
8483

8584
self._setup_handlers()
8685

‎CodeEntropy/entropy/configurational.py‎

Lines changed: 5 additions & 185 deletions
Original file line numberDiff line numberDiff line change
@@ -10,46 +10,15 @@
1010
from __future__ import annotations
1111

1212
import logging
13-
from dataclasses import dataclass
14-
from typing import Any, Optional
13+
from typing import Any
1514

1615
import numpy as np
1716

1817
logger = 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-
3820
class 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

Comments
 (0)