Skip to content

Commit 7af7eae

Browse files
committed
Add start to wizard
1 parent 9d20fb0 commit 7af7eae

11 files changed

Lines changed: 842 additions & 0 deletions

File tree

‎paths_cli/parsing/tools.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def custom_eval(obj, named_objs=None):
2+
string = str(obj)
3+
# TODO: check that the only attribute access comes from a whitelist
4+
namespace = {
5+
'np': __import__('numpy'),
6+
'math': __import__('math'),
7+
}
8+
return eval(string, namespace)
9+
10+
11+
class UnknownAtomsError(RuntimeError):
12+
pass
13+
14+
def mdtraj_parse_atomlist(inp_str, topology):
15+
# 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

‎paths_cli/wizard/core.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import random
2+
from joke import name_joke
3+
from tools import a_an
4+
5+
def name(wizard, obj, obj_type, store_name, default=None):
6+
wizard.say(f"Now let's name your {obj_type}.")
7+
name = None
8+
while name is None:
9+
name = wizard.ask("What do you want to call it?")
10+
if name in getattr(wizard, store_name):
11+
wizard.bad_input(f"Sorry, you already have {a_an(obj_type)} "
12+
f"named {name}. Please try another name.")
13+
name = None
14+
15+
obj = obj.named(name)
16+
17+
wizard.say(f"'{name}' is a good name for {a_an(obj_type)} {obj_type}. "
18+
+ name_joke(name, obj_type))
19+
return obj
20+
21+
def abort_retry_quit(wizard, obj_type):
22+
a_an = 'an' if obj_type[0] in 'aeiou' else 'a'
23+
retry = wizard.ask(f"Do you want to try again to make {a_an} "
24+
f"{obj_type}, do you want to continue without, or "
25+
f"do you want to quit?",
26+
options=["[R]etry", "[C]ontinue", "[Q]uit"])
27+
if retry == 'q':
28+
exit()
29+
elif retry == 'r':
30+
return
31+
elif retry == 'c':
32+
return "continue"
33+
else:
34+
raise ImpossibleError()
35+
36+
37+
def interpret_req(req):
38+
_, num, direction = req
39+
dir_str = {'+': 'at least ', '=': '', '-': 'at most '}[direction]
40+
return dir_str + str(num)
41+

‎paths_cli/wizard/cvs.py‎

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
from paths_cli.wizard.engines import engines
2+
from paths_cli.parsing.tools import custom_eval
3+
from paths_cli.wizard.load_from_ops import load_from_ops
4+
from paths_cli.wizard.load_from_ops import LABEL as _load_label
5+
from functools import partial
6+
import numpy as np
7+
8+
try:
9+
import mdtraj as md
10+
except ImportError:
11+
HAS_MDTRAJ = False
12+
else:
13+
HAS_MDTRAJ = True
14+
15+
def mdtraj_atom_helper(wizard, user_input, n_atoms):
16+
wizard.say("You should specify atom indices enclosed in double "
17+
"brackets, e.g, [" + str(list(range(n_atoms))) + "]")
18+
# TODO: implement the following:
19+
# wizard.say("You can specify atoms either as atom indices (which count "
20+
# "from zero) or as atom labels of the format "
21+
# "CHAIN:RESIDUE-ATOM, e.g., '0:ALA1-CA' for the alpha carbon "
22+
# "of alanine 1 (this time counting from one, as in the PDB) "
23+
# "of the 0th chain in the topology. You can also use letters "
24+
# "for chain IDs, but note that A corresponds to the first "
25+
# "chain in your topology, even if its name in the PDB file "
26+
# "is B.")
27+
28+
def _get_topology(wizard):
29+
from paths_cli.wizard.engines import engines
30+
topology = None
31+
while topology is None:
32+
if len(wizard.engines) == 0:
33+
# SHOULD NEVER GET HERE
34+
wizard.say("Hey, you need to define an MD engine before you "
35+
"create CVs that refer to it. Let's do that now!")
36+
engine = engines(wizard)
37+
wizard.register(engine, 'engine', 'engines')
38+
wizard.say("Now let's get back to defining your CV")
39+
elif len(wizard.engines) == 1:
40+
topology = list(wizard.engines.values())[0].topology
41+
else:
42+
engines = list(wizard.engines.keys)
43+
name = wizard.ask("You have defined multiple engines. Which one "
44+
"should I use to define your CV?",
45+
options=engines)
46+
topology = wizard.engines[name].topology
47+
48+
return topology
49+
50+
def _get_atom_indices(wizard, topology, cv_type):
51+
# TODO: move the logic here to parsing.tools
52+
n_atoms = {'distance': 2,
53+
'angle': 3,
54+
'dihedral': 4}[cv_type]
55+
arr = None
56+
helper = partial(mdtraj_atom_helper, n_atoms=n_atoms)
57+
while arr is None:
58+
atoms_str = wizard.ask("Which atoms do you want to measure the "
59+
"{cv_type} between?", helper=helper)
60+
try:
61+
indices = custom_eval(atoms_str)
62+
except Exception as e:
63+
wizard.exception(f"Sorry, I did't understand '{atoms_str}'", e)
64+
mdtraj_atom_helper(wizard, '?', n_atoms)
65+
continue
66+
67+
try:
68+
arr = np.array(indices)
69+
if arr.dtype != int:
70+
raise TypeError("Input is not integers")
71+
if arr.shape != (1, n_atoms):
72+
# try to clean it up
73+
if len(arr.shape) == 1 and arr.shape[0] == n_atoms:
74+
arr.shape = (1, n_atoms)
75+
else:
76+
raise TypeError(f"Invalid input. Requires {n_atoms} "
77+
"atoms.")
78+
except Exception as e:
79+
wizard.exception(f"Sorry, I did't understand '{atoms_str}'", e)
80+
mdtraj_atom_helper(wizard, '?', n_atoms)
81+
arr = None
82+
continue
83+
84+
if arr is not None:
85+
atom_names = [str(topology.mdtraj.atom(i)) for i in arr[0]]
86+
wizard.say("Using atoms: " + " ".join(atom_names))
87+
return arr
88+
89+
def _mdtraj_function_cv(wizard, cv_does_str, cv_user_prompt, func,
90+
kwarg_name, n_atoms):
91+
from openpathsampling.experimental.storage.collective_variables import \
92+
MDTrajFunctionCV
93+
wizard.say("We'll make a CV that measures the distance between two "
94+
"atoms.")
95+
topology = _get_topology(wizard)
96+
indices = _get_atom_indices(wizard, topology, n_atoms=n_atoms)
97+
kwargs = {kwarg_name: indices}
98+
99+
return MDTrajFunctionCV(func, topology, **kwargs)
100+
101+
def distance(wizard):
102+
return _mdtraj_function_cv(
103+
wizard=wizard,
104+
cv_does_str="distance between two atoms",
105+
cv_user_prompt="measure the distance between",
106+
func=md.compute_distances,
107+
kwarg_name='atom_pairs',
108+
n_atoms=2
109+
)
110+
111+
def angle(wizard):
112+
return _mdtraj_function_cv(
113+
wizard=wizard,
114+
cv_does_str="angle made by three atoms",
115+
cv_user_prompt="use to define the angle",
116+
func=md.compute_angles,
117+
kwarg_name='angle_indices',
118+
n_atoms=3
119+
)
120+
121+
def dihedral(wizard):
122+
return _mdtraj_function_cv(
123+
wizard=wizard,
124+
cv_does_str="dihedral made by four atoms",
125+
cv_user_prompt="use to define the dihedral angle",
126+
func=md.compute_dihedrals,
127+
kwarg_name='indices',
128+
n_atoms=4
129+
)
130+
131+
def rmsd(wizard):
132+
raise NotImplementedError("RMSD has not yet been implemented")
133+
134+
def coordinate(wizard):
135+
atom_index = coord = None
136+
while atom_index is None:
137+
idx = wizard.ask("For which atom do you want to get the "
138+
"coordinate? (counting from zero)")
139+
try:
140+
atom_index = int(idx)
141+
except Exception as e:
142+
wizard.exception("Sorry, I can't make an atom index from "
143+
f"'{idx}'", e)
144+
145+
while coord is None:
146+
xyz = wizard.ask("Which coordinate (x, y, or z) do you want for "
147+
f"atom {atom_index}?")
148+
try:
149+
coord = {'x': 0, 'y': 1, 'z': 2}[xyz]
150+
except KeyError as e:
151+
wizard.bad_input("Please select one of 'x', 'y', or 'z'")
152+
153+
SUPPORTED_CVS = {}
154+
155+
if HAS_MDTRAJ:
156+
SUPPORTED_CVS.update({
157+
'Distance': distance,
158+
'Angle': angle,
159+
'Dihedral': dihedral,
160+
'RMSD': rmsd,
161+
})
162+
163+
SUPPORTED_CVS.update({
164+
'Coordinate': coordinate,
165+
'Python script': ...,
166+
_load_label: partial(load_from_ops,
167+
store_name='cvs',
168+
obj_name='CV'),
169+
})
170+
171+
def cvs(wizard):
172+
wizard.say("You'll need to describe your system in terms of "
173+
"collective variables (CVs). We'll use these to define "
174+
"things like stable states.")
175+
cv_names = list(SUPPORTED_CVS.keys())
176+
cv = None
177+
while cv is None:
178+
cv_type = wizard.ask_enumerate("What kind of CV do you want to "
179+
"define?", options=cv_names)
180+
cv = SUPPORTED_CVS[cv_type](wizard)
181+
return cv
182+
183+
if __name__ == "__main__":
184+
from paths_cli.wizard.wizard import Wizard
185+
wiz = Wizard({})
186+
cvs(wiz)

‎paths_cli/wizard/engines.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import paths_cli.wizard.openmm as openmm
2+
from load_from_ops import load_from_ops, LABEL as load_label
3+
from functools import partial
4+
5+
SUPPORTED_ENGINES = {}
6+
for module in [openmm]:
7+
SUPPORTED_ENGINES.update(module.SUPPORTED)
8+
9+
SUPPORTED_ENGINES[load_label] = partial(load_from_ops,
10+
store_name='engines',
11+
obj_name='engine')
12+
13+
def engines(wizard):
14+
wizard.say("Let's make an engine. An engine describes how you'll do "
15+
"the actual dynamics. Most of the details are given "
16+
"in files that depend on the specific type of engine.")
17+
engine_names = list(SUPPORTED_ENGINES.keys())
18+
eng_name = wizard.ask_enumerate(
19+
"What will you use for the underlying engine?",
20+
options=engine_names
21+
)
22+
engine = SUPPORTED_ENGINES[eng_name](wizard)
23+
return engine
24+
25+
if __name__ == "__main__":
26+
from paths_cli.wizard import wizard
27+
wiz = wizard.Wizard({'engines': ('engines', 1, '=')})
28+
wiz.run_wizard()
29+

‎paths_cli/wizard/errors.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class ImpossibleError(Exception):
2+
def __init__(self, msg=None):
3+
if msg is None:
4+
msg = "Something went really wrong. You should never see this."
5+
super().__init__(msg)
6+
7+
def not_installed(package, obj_type):
8+
retry = wizard.ask("Hey, it looks like you don't have {package} "
9+
"installed. Do you want to try a different "
10+
"{obj_type}, or do you want to quit?",
11+
options=["[R]etry", "[Q]uit"])
12+
if retry == 'r':
13+
return
14+
elif retry == 'q':
15+
exit()
16+
else:
17+
raise ImpossibleError()
18+
19+
20+
FILE_LOADING_ERROR_MSG = ("Sorry, something went wrong when loading that "
21+
"file.")

‎paths_cli/wizard/joke.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import random
2+
3+
from paths_cli.wizard.tools import a_an
4+
5+
_NAMES = ['Fred', 'Winston', 'Agnes', "Millicent", "Ophelia", "Laszlo",
6+
"Werner"]
7+
_THINGS = ['pet spider', 'teddy bear', 'close friend', 'school teacher',
8+
'iguana']
9+
_SPAWN = ['daughter', 'son', 'first-born']
10+
11+
_MISC = [
12+
"Named after its father, perhaps?",
13+
"Isn't '{name}' also the name of a village in Tuscany?",
14+
"Didn't Johnny Cash write a song about {a_an_thing} called '{name}'?",
15+
"I think I'm going to start rapping as 'DJ {name}'.",
16+
]
17+
18+
def _joke1(name, obj_type):
19+
return (f"I probably would have named it something like "
20+
f"'{random.choice(_NAMES)}'.")
21+
22+
def _joke2(name, obj_type):
23+
thing = random.choice(_THINGS)
24+
joke = (f"I had {a_an(thing)} {thing} named '{name}' "
25+
f"when I was young.")
26+
return joke
27+
28+
def _joke3(name, obj_type):
29+
return (f"I wanted to name my {random.choice(_SPAWN)} '{name}', but my "
30+
f"wife wouldn't let me.")
31+
32+
def _joke4(name, obj_type):
33+
a_an_thing = a_an(obj_type) + f" {obj_type}"
34+
return random.choice(_MISC).format(name=name, obj_type=obj_type,
35+
a_an_thing=a_an_thing)
36+
37+
def name_joke(name, obj_type):
38+
rnd = random.random()
39+
if 0 <= rnd < 0.30:
40+
joke = _joke1
41+
elif 0.30 <= rnd < 0.70:
42+
joke = _joke2
43+
elif 0.70 <= rnd < 0.85:
44+
joke = _joke4
45+
else:
46+
joke = _joke3
47+
return joke(name, obj_type)
48+
49+
if __name__ == "__main__":
50+
for _ in range(5):
51+
print()
52+
print(name_joke('AD_300K', 'engine'))
53+
print()
54+
print(name_joke('C_7eq', 'state'))

‎paths_cli/wizard/load_from_ops.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
LABEL = "Load existing from OPS file"
2+
from paths_cli.parameters import INPUT_FILE
3+
4+
def named_objs_helper(storage, store_name):
5+
def list_items(wizard, user_input):
6+
store = getattr(storage, store_name)
7+
names = [obj for obj in store if obj.is_named]
8+
outstr = "\n".join(['* ' + obj.name for obj in names])
9+
wizard.say("Here's what I found:\n\n" + outstr)
10+
11+
return list_items
12+
13+
14+
def load_from_ops(wizard, store_name, obj_name):
15+
wizard.say("Okay, we'll load it from an OPS file.")
16+
storage = None
17+
while storage is None:
18+
filename = wizard.ask("What file can it be found in?",
19+
default='filename')
20+
try:
21+
storage = INPUT_FILE.get(filename)
22+
except Exception as e:
23+
wizard.exception(FILE_LOADING_ERROR_MSG, e)
24+
# TODO: error handling
25+
26+
obj = None
27+
while obj is None:
28+
name = wizard.ask(f"What's the name of the {obj_name} you want to "
29+
"load? (Type '?' to get a list of them)",
30+
helper=named_objs_helper(storage, store_name))
31+
if name:
32+
try:
33+
obj = getattr(storage, store_name)[name]
34+
except Exception as e:
35+
wizard.exception("Something went wrong when loading "
36+
f"{name}. Maybe check the spelling?", e)
37+
return obj

0 commit comments

Comments
 (0)