Skip to content

Commit 636500e

Browse files
committed
test(core): add atomic pytest unit tests for the entropy modules
1 parent e96b2df commit 636500e

17 files changed

Lines changed: 1635 additions & 0 deletions
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
from types import SimpleNamespace
2+
from unittest.mock import MagicMock
3+
4+
import pytest
5+
6+
7+
class FakeResidue:
8+
def __init__(self, resname="RES"):
9+
self.resname = resname
10+
11+
12+
class FakeMol:
13+
def __init__(self, residues=None):
14+
self.residues = residues or [FakeResidue("ALA"), FakeResidue("GLY")]
15+
16+
17+
class FakeAtoms:
18+
def __init__(self, fragments):
19+
self.fragments = fragments
20+
21+
22+
class FakeUniverse:
23+
def __init__(self, n_frames=10, fragments=None):
24+
self.trajectory = list(range(n_frames))
25+
self.atoms = FakeAtoms(fragments or [FakeMol()])
26+
27+
28+
@pytest.fixture()
29+
def args():
30+
# Only fields used by entropy modules.
31+
return SimpleNamespace(
32+
temperature=298.0,
33+
bin_width=30,
34+
grouping="molecules",
35+
water_entropy=False,
36+
combined_forcetorque=True,
37+
selection_string="all",
38+
start=0,
39+
end=-1,
40+
step=1,
41+
)
42+
43+
44+
@pytest.fixture()
45+
def reporter():
46+
return MagicMock()
47+
48+
49+
@pytest.fixture()
50+
def run_manager():
51+
rm = MagicMock()
52+
rm.change_lambda_units.side_effect = lambda x: x
53+
rm.get_KT2J.return_value = 2.479e-21
54+
return rm
55+
56+
57+
@pytest.fixture()
58+
def reduced_universe():
59+
return FakeUniverse(n_frames=12, fragments=[FakeMol()])
60+
61+
62+
@pytest.fixture()
63+
def shared_data(args, reporter, run_manager, reduced_universe):
64+
return {
65+
"args": args,
66+
"reporter": reporter,
67+
"run_manager": run_manager,
68+
"reduced_universe": reduced_universe,
69+
"universe": reduced_universe,
70+
"groups": {0: [0]},
71+
"levels": {0: ["united_atom", "residue"]},
72+
"start": 0,
73+
"end": 12,
74+
"step": 1,
75+
"n_frames": 12,
76+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from CodeEntropy.entropy.nodes.aggregate import AggregateEntropyNode
2+
3+
4+
def test_aggregate_node_collects_values_and_writes_shared_data():
5+
node = AggregateEntropyNode()
6+
shared = {"vibrational_entropy": {"v": 1}, "configurational_entropy": {"c": 2}}
7+
8+
out = node.run(shared)
9+
10+
assert out["entropy_results"]["vibrational_entropy"] == {"v": 1}
11+
assert out["entropy_results"]["configurational_entropy"] == {"c": 2}
12+
assert shared["entropy_results"] == out["entropy_results"]
13+
14+
15+
def test_aggregate_node_missing_upstreams_yields_none_values():
16+
node = AggregateEntropyNode()
17+
shared = {}
18+
19+
out = node.run(shared)
20+
21+
assert out["entropy_results"]["vibrational_entropy"] is None
22+
assert out["entropy_results"]["configurational_entropy"] is None
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import logging
2+
from types import SimpleNamespace
3+
from unittest.mock import MagicMock
4+
5+
import numpy as np
6+
import pytest
7+
8+
from CodeEntropy.entropy.configurational import ConformationalEntropy
9+
10+
11+
def test_validate_assignment_config_step_must_be_positive():
12+
ce = ConformationalEntropy()
13+
with pytest.raises(ValueError):
14+
ce.assign_conformation(
15+
data_container=SimpleNamespace(trajectory=list(range(5))),
16+
dihedral=MagicMock(value=lambda: 10.0),
17+
number_frames=5,
18+
bin_width=30,
19+
start=0,
20+
end=5,
21+
step=0,
22+
)
23+
24+
25+
def test_validate_assignment_config_bin_width_out_of_range():
26+
ce = ConformationalEntropy()
27+
with pytest.raises(ValueError):
28+
ce.assign_conformation(
29+
data_container=SimpleNamespace(trajectory=list(range(5))),
30+
dihedral=MagicMock(value=lambda: 10.0),
31+
number_frames=5,
32+
bin_width=0,
33+
start=0,
34+
end=5,
35+
step=1,
36+
)
37+
38+
39+
def test_validate_assignment_config_warns_when_bin_width_not_dividing_360(caplog):
40+
ce = ConformationalEntropy()
41+
caplog.set_level(logging.WARNING)
42+
43+
data_container = SimpleNamespace(trajectory=list(range(5)))
44+
dihedral = MagicMock()
45+
dihedral.value.return_value = 10.0
46+
47+
ce.assign_conformation(
48+
data_container=data_container,
49+
dihedral=dihedral,
50+
number_frames=5,
51+
bin_width=7,
52+
start=0,
53+
end=5,
54+
step=1,
55+
)
56+
57+
assert any("does not evenly divide 360" in r.message for r in caplog.records)
58+
59+
60+
def test_collect_dihedral_angles_normalizes_negative_values():
61+
ce = ConformationalEntropy()
62+
63+
traj_slice = list(range(3))
64+
dihedral = MagicMock()
65+
dihedral.value.side_effect = [-10.0, 0.0, 10.0]
66+
67+
phi = ce._collect_dihedral_angles(traj_slice, dihedral)
68+
69+
assert phi[0] == pytest.approx(350.0)
70+
71+
72+
def test_to_1d_array_returns_none_for_non_iterable_state_input():
73+
ce = ConformationalEntropy()
74+
# int is not iterable -> list(states) raises TypeError -> returns None
75+
assert ce._to_1d_array(123) is None
76+
77+
78+
def test_find_histogram_peaks_skips_zero_population_bins():
79+
ce = ConformationalEntropy()
80+
81+
phi = np.zeros(50, dtype=float)
82+
83+
peaks = ce._find_histogram_peaks(phi, bin_width=30)
84+
85+
assert peaks.size >= 1
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
from types import SimpleNamespace
2+
from unittest.mock import MagicMock
3+
4+
import numpy as np
5+
import pytest
6+
7+
from CodeEntropy.entropy.configurational import ConformationalEntropy
8+
9+
10+
def test_find_histogram_peaks_empty_histogram_returns_empty():
11+
ce = ConformationalEntropy()
12+
phi = np.zeros(100, dtype=float)
13+
14+
peaks = ce._find_histogram_peaks(phi, bin_width=30)
15+
16+
assert isinstance(peaks, np.ndarray)
17+
assert peaks.dtype == float
18+
19+
20+
def test_find_histogram_peaks_returns_empty_for_empty_phi():
21+
ce = ConformationalEntropy()
22+
phi = np.array([], dtype=float)
23+
24+
peaks = ce._find_histogram_peaks(phi, bin_width=30)
25+
26+
assert isinstance(peaks, np.ndarray)
27+
assert peaks.size == 0
28+
29+
30+
def test_assign_nearest_peaks_with_single_peak_assigns_all_zero():
31+
ce = ConformationalEntropy()
32+
phi = np.array([0.0, 10.0, 20.0], dtype=float)
33+
peak_values = np.array([15.0], dtype=float)
34+
35+
states = ce._assign_nearest_peaks(phi, peak_values)
36+
37+
assert np.all(states == 0)
38+
39+
40+
def test_assign_conformation_no_peaks_returns_all_zero():
41+
ce = ConformationalEntropy()
42+
43+
data_container = SimpleNamespace(trajectory=[])
44+
dihedral = MagicMock()
45+
46+
states = ce.assign_conformation(
47+
data_container=data_container,
48+
dihedral=dihedral,
49+
number_frames=0,
50+
bin_width=30,
51+
start=0,
52+
end=0,
53+
step=1,
54+
)
55+
56+
assert states.size == 0
57+
58+
59+
def test_assign_conformation_fallback_when_peak_finder_returns_empty(monkeypatch):
60+
ce = ConformationalEntropy()
61+
data_container = SimpleNamespace(trajectory=list(range(5)))
62+
dihedral = MagicMock()
63+
dihedral.value.return_value = 10.0
64+
65+
monkeypatch.setattr(
66+
ce, "_find_histogram_peaks", lambda phi, bw: np.array([], dtype=float)
67+
)
68+
69+
states = ce.assign_conformation(
70+
data_container=data_container,
71+
dihedral=dihedral,
72+
number_frames=5,
73+
bin_width=30,
74+
start=0,
75+
end=5,
76+
step=1,
77+
)
78+
assert np.all(states == 0)
79+
80+
81+
def test_assign_conformation_detects_multiple_states():
82+
ce = ConformationalEntropy()
83+
84+
values = [0.0] * 50 + [180.0] * 50
85+
data_container = SimpleNamespace(trajectory=list(range(len(values))))
86+
dihedral = MagicMock()
87+
dihedral.value.side_effect = values
88+
89+
states = ce.assign_conformation(
90+
data_container=data_container,
91+
dihedral=dihedral,
92+
number_frames=len(values),
93+
bin_width=30,
94+
start=0,
95+
end=len(values),
96+
step=1,
97+
)
98+
99+
assert len(np.unique(states)) >= 2
100+
101+
102+
def test_conformational_entropy_empty_returns_zero():
103+
ce = ConformationalEntropy()
104+
assert ce.conformational_entropy_calculation([], number_frames=10) == 0.0
105+
106+
107+
def test_conformational_entropy_single_state_returns_zero():
108+
ce = ConformationalEntropy()
109+
assert ce.conformational_entropy_calculation([0, 0, 0], number_frames=3) == 0.0
110+
111+
112+
def test_conformational_entropy_known_distribution_matches_expected():
113+
ce = ConformationalEntropy()
114+
states = np.array([0, 0, 1, 1, 1, 2])
115+
116+
probs = np.array([2 / 6, 3 / 6, 1 / 6], dtype=float)
117+
expected = -ce._GAS_CONST * float(np.sum(probs * np.log(probs)))
118+
119+
got = ce.conformational_entropy_calculation(states, number_frames=6)
120+
assert got == pytest.approx(expected)
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import pytest
2+
3+
from CodeEntropy.entropy.nodes.configurational import ConfigurationalEntropyNode
4+
5+
6+
def test_config_node_raises_if_frame_count_missing():
7+
node = ConfigurationalEntropyNode()
8+
with pytest.raises(KeyError):
9+
node._get_n_frames({})
10+
11+
12+
def test_config_node_run_writes_results(shared_data):
13+
node = ConfigurationalEntropyNode()
14+
15+
shared_data["conformational_states"] = {
16+
"ua": {(0, 0): [0, 0, 1, 1]},
17+
"res": {0: [0, 1, 1, 1]},
18+
}
19+
20+
shared_data["levels"] = {0: ["united_atom", "residue"]}
21+
shared_data["groups"] = {0: [0]}
22+
23+
out = node.run(shared_data)
24+
25+
assert "configurational_entropy" in out
26+
assert "configurational_entropy" in shared_data
27+
assert 0 in shared_data["configurational_entropy"]
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from unittest.mock import MagicMock
2+
3+
import numpy as np
4+
5+
from CodeEntropy.entropy.nodes.configurational import ConfigurationalEntropyNode
6+
7+
8+
def test_run_skips_empty_mol_ids_group():
9+
node = ConfigurationalEntropyNode()
10+
11+
shared_data = {
12+
"n_frames": 5,
13+
"groups": {0: []},
14+
"levels": {0: ["united_atom"]},
15+
"reduced_universe": MagicMock(),
16+
"conformational_states": {"ua": {}, "res": {}},
17+
"reporter": None,
18+
}
19+
20+
out = node.run(shared_data)
21+
22+
assert "configurational_entropy" in out
23+
assert out["configurational_entropy"][0]["ua"] == 0.0
24+
25+
26+
def test_get_group_states_sequence_in_range_returns_value():
27+
states_res = [None, [1, 2, 3]]
28+
out = ConfigurationalEntropyNode._get_group_states(states_res, group_id=1)
29+
assert out == [1, 2, 3]
30+
31+
32+
def test_get_group_states_sequence_out_of_range_returns_none():
33+
states_res = [None]
34+
out = ConfigurationalEntropyNode._get_group_states(states_res, group_id=2)
35+
assert out is None
36+
37+
38+
def test_has_state_data_numpy_array_uses_np_any_branch():
39+
assert ConfigurationalEntropyNode._has_state_data(np.array([0, 0, 1])) is True
40+
assert ConfigurationalEntropyNode._has_state_data(np.array([0, 0, 0])) is False
41+
42+
43+
def test_has_state_data_noniterable_hits_typeerror_fallback():
44+
# any(0) raises TypeError -> returns bool(0) == False
45+
assert ConfigurationalEntropyNode._has_state_data(0) is False
46+
# any(1) raises TypeError -> returns bool(1) == True
47+
assert ConfigurationalEntropyNode._has_state_data(1) is True

0 commit comments

Comments
 (0)