-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathparse_functional.py
More file actions
69 lines (52 loc) · 1.98 KB
/
Copy pathparse_functional.py
File metadata and controls
69 lines (52 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
__author__ = "Patrick Farrell"
__license__ = "LGPL"
__credits__ = ["Patrick Farrell", "David Ham"]
__blame__ = ["Patrick Farrell"]
import re
def parse(code):
"""Given the string containing code for a functional or its derivative, work out
what dependencies on which state it has. E.g., if the code was
from math import sin, pi
coord = states[n]["Fluid"].vector_fields["Coordinate"]
u = states[n+1]["Fluid"].scalar_fields["Velocity"]
du = states[n-1]["Fluid"].scalar_fields["VelocityDerivative"]
for i in range(du.node_count):
x = coord.node_val[i][0]
du.set(i, 0.01125*pi**2*sin(3.0/20*(x + 10)*pi)
then this routine should return the list
[-1, 0, +1]."""
# My beautiful regex, made with the help of http://re.dabase.com/
regex = re.compile(r"""states\[(?P<n>[n0-9+-]*)\]""")
return sorted(set(map(eval, re.findall(regex, code))))
if __name__ == "__main__":
code = """
from math import sin, pi
coord = states[n]["Fluid"].vector_fields["Coordinate"]
u = states[n+1]["Fluid"].scalar_fields["Velocity"]
du = states[n-1]["Fluid"].scalar_fields["VelocityDerivative"]
for i in range(du.node_count):
x = coord.node_val[i][0]
du.set(i, 0.01125*pi**2*sin(3.0/20*(x + 10)*pi)
"""
print(parse(code))
def make_adj_variables(d):
"""d is a dict like
{"Fluid::Velocity": [0, 3, 4],
"Fluid::Pressure": [2, 3, 5]}
Take this, and make a list of things we can easily convert into adj_variables.
Aside: #python on freenode is exceptionally unhelpful."""
varlist = []
for key in d:
for timestep in d[key]:
if timestep < 0:
print(
"Warning: dependencies function returned a variable with "
f"timestep {timestep}."
)
else:
newd = {}
newd["name"] = key
newd["timestep"] = timestep
varlist.append(newd)
return varlist