Skip to content

Commit b32d03a

Browse files
committed
Add tests for CV wizards
1 parent b5ec9ce commit b32d03a

4 files changed

Lines changed: 133 additions & 32 deletions

File tree

‎paths_cli/parsing/tools.py‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import numpy as np
2+
13
def custom_eval(obj, named_objs=None):
24
string = str(obj)
35
# TODO: check that the only attribute access comes from a whitelist
@@ -11,10 +13,24 @@ def custom_eval(obj, named_objs=None):
1113
class UnknownAtomsError(RuntimeError):
1214
pass
1315

14-
def mdtraj_parse_atomlist(inp_str, topology):
16+
def mdtraj_parse_atomlist(inp_str, n_atoms, topology=None):
17+
"""
18+
n_atoms: int
19+
number of atoms expected
20+
"""
21+
# TODO: change n_atoms to the shape desired?
1522
# TODO: enable the parsing of either string-like atom labels or numeric
16-
try:
17-
arr = custom_eval(inp_str)
18-
except:
19-
pass # on any error, we do it the hard way
20-
pass
23+
indices = custom_eval(inp_str)
24+
25+
arr = np.array(indices)
26+
if arr.dtype != int:
27+
raise TypeError("Input is not integers")
28+
if arr.shape != (1, n_atoms):
29+
# try to clean it up
30+
if len(arr.shape) == 1 and arr.shape[0] == n_atoms:
31+
arr.shape = (1, n_atoms)
32+
else:
33+
raise TypeError(f"Invalid input. Requires {n_atoms} "
34+
"atoms.")
35+
36+
return arr

‎paths_cli/tests/wizard/test_cvs.py‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import pytest
2+
import mock
3+
import numpy as np
4+
5+
from functools import partial
6+
7+
from paths_cli.tests.wizard.mock_wizard import mock_wizard
8+
9+
from paths_cli.wizard.cvs import (
10+
_get_topology, _get_atom_indices, distance, angle, dihedral, rmsd,
11+
coordinate, cvs, SUPPORTED_CVS
12+
)
13+
14+
import openpathsampling as paths
15+
from openpathsampling.experimental.storage.collective_variables import \
16+
MDTrajFunctionCV
17+
from openpathsampling.tests.test_helpers import make_1d_traj
18+
19+
@pytest.mark.parametrize('n_engines', [0, 1, 2])
20+
def test_get_topology(ad_engine, n_engines):
21+
inputs = {0: [], 1: [], 2: ['1']}[n_engines]
22+
wizard = mock_wizard(inputs)
23+
engines = [ad_engine, paths.engines.NoEngine(None).named('foo')]
24+
wizard.engines = {eng.name: eng for eng in engines[:n_engines]}
25+
def mock_register(obj, obj_type, store_name):
26+
wizard.engines[obj.name] = obj
27+
wizard.register = mock_register
28+
29+
mock_engines = mock.Mock(return_value=ad_engine)
30+
patch_loc = 'paths_cli.wizard.engines.engines'
31+
with mock.patch(patch_loc, new=mock_engines):
32+
topology = _get_topology(wizard)
33+
assert isinstance(topology,
34+
paths.engines.openmm.topology.MDTrajTopology)
35+
36+
@pytest.mark.parametrize('inputs', [
37+
(['[[1, 2]]']), (['1, 2']),
38+
(['[[1, 2, 3]]', '[[1, 2]]']),
39+
])
40+
def test_get_atom_indices(ad_engine, inputs):
41+
wizard = mock_wizard(inputs)
42+
arr = _get_atom_indices(wizard, ad_engine.topology, 2, "use")
43+
np.testing.assert_array_equal(arr, np.array([[1, 2]]))
44+
assert wizard.console.input_call_count == len(inputs)
45+
if len(inputs) > 1:
46+
assert "I didn't understand" in wizard.console.log_text
47+
48+
def _mdtraj_function_test(wizard, func, md_func, ad_openmm, ad_engine):
49+
md = pytest.importorskip('mdtraj')
50+
wizard.engines[ad_engine.name] = ad_engine
51+
with ad_openmm.as_cwd():
52+
cv = func(wizard)
53+
pdb = md.load('ad.pdb')
54+
assert isinstance(cv, MDTrajFunctionCV)
55+
traj = paths.engines.openmm.trajectory_from_mdtraj(pdb)
56+
np.testing.assert_array_almost_equal(md_func(pdb)[0], cv(traj))
57+
58+
def test_distance(ad_openmm, ad_engine):
59+
md = pytest.importorskip('mdtraj')
60+
wizard = mock_wizard(['0, 1'])
61+
md_func = partial(md.compute_distances, atom_pairs=[[0, 1]])
62+
_mdtraj_function_test(wizard, distance, md_func, ad_openmm, ad_engine)
63+
64+
def test_angle(ad_openmm, ad_engine):
65+
md = pytest.importorskip('mdtraj')
66+
wizard = mock_wizard(['0, 1, 2'])
67+
md_func = partial(md.compute_angles, angle_indices=[[0, 1, 2]])
68+
_mdtraj_function_test(wizard, angle, md_func, ad_openmm, ad_engine)
69+
70+
def test_dihedral(ad_openmm, ad_engine):
71+
md = pytest.importorskip('mdtraj')
72+
wizard = mock_wizard(['0, 1, 2, 3'])
73+
md_func = partial(md.compute_dihedrals, indices=[[0, 1, 2, 3]])
74+
_mdtraj_function_test(wizard, dihedral, md_func, ad_openmm, ad_engine)
75+
76+
@pytest.mark.parametrize('inputs', [
77+
(['0', 'x']), ('foo', '0', 'x'), (['0', 'q', 'x'])
78+
])
79+
def test_coordinate(inputs):
80+
wizard = mock_wizard(inputs)
81+
cv = coordinate(wizard)
82+
traj = make_1d_traj([5.0])
83+
assert cv(traj[0]) == 5.0
84+
if 'foo' in inputs:
85+
assert "I can't make an atom index" in wizard.console.log_text
86+
if 'q' in inputs:
87+
assert "Please select one of" in wizard.console.log_text
88+
89+
@pytest.mark.parametrize('inputs', [(['foo', 'Distance']), (['Distance'])])
90+
def test_cvs(inputs):
91+
wizard = mock_wizard(inputs)
92+
say_hello = mock.Mock(return_value="hello")
93+
with mock.patch.dict(SUPPORTED_CVS, {'Distance': say_hello}):
94+
assert cvs(wizard) == "hello"
95+
assert wizard.console.input_call_count == len(inputs)

‎paths_cli/wizard/cvs.py‎

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from paths_cli.wizard.engines import engines
2-
from paths_cli.parsing.tools import custom_eval
2+
from paths_cli.parsing.tools import custom_eval, mdtraj_parse_atomlist
33
from paths_cli.wizard.load_from_ops import load_from_ops
44
from paths_cli.wizard.load_from_ops import LABEL as _load_label
55
from paths_cli.wizard.core import get_object
@@ -59,26 +59,9 @@ def _get_atom_indices(wizard, topology, n_atoms, cv_user_str):
5959
atoms_str = wizard.ask(f"Which atoms do you want to {cv_user_str}?",
6060
helper=helper)
6161
try:
62-
indices = custom_eval(atoms_str)
62+
arr = mdtraj_parse_atomlist(atoms_str, n_atoms, topology)
6363
except Exception as e:
64-
wizard.exception(f"Sorry, I did't understand '{atoms_str}'.", e)
65-
mdtraj_atom_helper(wizard, '?', n_atoms)
66-
return
67-
68-
try:
69-
# move this logic to parsing.tools
70-
arr = np.array(indices)
71-
if arr.dtype != int:
72-
raise TypeError("Input is not integers")
73-
if arr.shape != (1, n_atoms):
74-
# try to clean it up
75-
if len(arr.shape) == 1 and arr.shape[0] == n_atoms:
76-
arr.shape = (1, n_atoms)
77-
else:
78-
raise TypeError(f"Invalid input. Requires {n_atoms} "
79-
"atoms.")
80-
except Exception as e:
81-
wizard.exception(f"Sorry, I did't understand '{atoms_str}'", e)
64+
wizard.exception(f"Sorry, I didn't understand '{atoms_str}'.", e)
8265
mdtraj_atom_helper(wizard, '?', n_atoms)
8366
return
8467

@@ -144,6 +127,8 @@ def rmsd(wizard):
144127

145128
def coordinate(wizard):
146129
# TODO: atom_index should be from wizard.ask_custom_eval
130+
from openpathsampling.experimental.storage.collective_variables import \
131+
CoordinateFunctionCV
147132
atom_index = coord = None
148133
while atom_index is None:
149134
idx = wizard.ask("For which atom do you want to get the "
@@ -162,6 +147,10 @@ def coordinate(wizard):
162147
except KeyError as e:
163148
wizard.bad_input("Please select one of 'x', 'y', or 'z'")
164149

150+
cv = CoordinateFunctionCV(lambda snap: snap.xyz[atom_index][coord])
151+
return cv
152+
153+
165154
def _get_period(wizard):
166155
# to be used in custom CVs ... or maybe just in the file CV itself?
167156
is_periodic = period_min = period_max = None
@@ -206,14 +195,12 @@ def cvs(wizard):
206195
"collective variables (CVs). We'll use these to define "
207196
"things like stable states.")
208197
cv_names = list(SUPPORTED_CVS.keys())
209-
cv = None
210-
while cv is None:
211-
cv_type = wizard.ask_enumerate("What kind of CV do you want to "
212-
"define?", options=cv_names)
213-
cv = SUPPORTED_CVS[cv_type](wizard)
198+
cv_type = wizard.ask_enumerate("What kind of CV do you want to "
199+
"define?", options=cv_names)
200+
cv = SUPPORTED_CVS[cv_type](wizard)
214201
return cv
215202

216-
if __name__ == "__main__":
203+
if __name__ == "__main__": # no-cov
217204
from paths_cli.wizard.wizard import Wizard
218205
wiz = Wizard({})
219206
cvs(wiz)

‎paths_cli/wizard/wizard.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ def ask_enumerate(self, question, options):
101101
choice = self.ask("Please select a number:",
102102
options=[str(i+1)
103103
for i in range(len(options))])
104+
if choice in options:
105+
return choice
106+
104107
try:
105108
num = int(choice) - 1
106109
result = options[num]

0 commit comments

Comments
 (0)