from sympy import symbols, Function, preorder_traversal, Integer, Rational, Float, Pow
from collections.abc import Iterable
tab = " "
x, y, z = symbols("x y z", real=True)
ppow = Function("PPow")
ddelta = Function("ddelta")
ssqrt = Function("ssqrt")
powm1 = Function("powm1")
sgn = Function("sgn")
powN = list(Function("pow" + str(i)) for i in range(9))
def zero_function(*args):
"""
This function returns zero, and is used in various places to simplify expressions
by replacing the Dirac Delta and its derivatives with zero.
"""
return 0
def fortran_substitutions(deriv):
"""
Makes various substitutions to an expression to ensure compatibility with
CRLIBM and to improve performance.
"""
deriv = substitute_pow(deriv)
deriv = substitute_rational(deriv)
deriv = substitute_dp(deriv)
deriv = deriv.replace(Pow, ppow)
return deriv
def substitute_rational(expr):
"""
Substitutes i/j for float(i)/float(j) for all integers i,j.
This avoids Fortran integer division from ruining our expressions through rounding.
"""
to_sub = [
p
for p in preorder_traversal(expr)
if isinstance(p, Rational) and p != 1 and p != -1
]
new_ex = [symbols(str(float(p)) + "_dp") for p in to_sub]
expr = expr.xreplace(dict({old: new for old, new in zip(*(to_sub, new_ex))}))
return expr
def substitute_dp(expr):
"""
Substitutes x_dp for x whenever x is a type Float.
This makes all constant declarations type-unambiguous and ensures bit-for-bit compatibility.
"""
to_sub = [p for p in preorder_traversal(expr) if isinstance(p, Float)]
new_ex = [symbols(str(float(p)) + "_dp") for p in to_sub]
expr = expr.xreplace(dict({old: new for old, new in zip(*(to_sub, new_ex))}))
return expr
def substitute_pow(expr):
"""
Replaces instances of x**N with powN(x) for integer N.
Only does this for N small enough for math_lib to provide a powN function.
Also replaces instances of pow(x, N/2) with powN(sqrt(x)) because this gives better performance.
(pow(x,y) gets evaluated roughly as exp(y*log(x)), which is costly because both log and exp are expensive,
whereas powN(sqrt(x)) gets evaluated with a faster sqrt routine followed by a fast powN)
"""
expr_prev = None
while expr_prev != expr:
expr_prev = expr
to_sub = [p for p in preorder_traversal(expr) if p.func == Pow]
to_sub = [p for p in to_sub if isinstance(p.args[1], Rational)]
to_sub = [p for p in to_sub if p.args[1].q == Integer(2)]
new_ex = [Pow(ssqrt(p.args[0]), p.args[1].p) for p in to_sub]
expr = expr.xreplace(dict({old: new for old, new in zip(*(to_sub, new_ex))}))
to_sub = [p for p in preorder_traversal(expr) if p.func == Pow]
to_sub = [p for p in to_sub if isinstance(p.args[1], Integer)]
to_sub = [p for p in to_sub if p.args[1] < 0]
new_ex = [powm1(Pow(p.args[0], -p.args[1])) for p in to_sub]
expr = expr.xreplace(dict({old: new for old, new in zip(*(to_sub, new_ex))}))
to_sub = [p for p in preorder_traversal(expr) if p.func == Pow]
to_sub = [p for p in to_sub if isinstance(p.args[1], Integer)]
to_sub = [p for p in to_sub if p.args[1] > 0 and p.args[1] <= 8]
new_ex = [powN[p.args[1]](p.args[0]) for p in to_sub]
expr = expr.xreplace(dict({old: new for old, new in zip(*(to_sub, new_ex))}))
return expr
def py_to_fort(expr):
"""
Turns a sympy expression into valid fortran.
In various places we have used a non-standard expression to ensure that sympy gets
the right behaviour. E.g. we called pow -> PPow and sqrt -> ssqrt. This gives us
more control over the result by preventing sympy from trying to simplify things too far.
At this stage we're generating a string, so we have to undo those substitutions
to get valid fortran code.
We also take the opportunity to use the fact that MESA has pre-computed ln(10)
and so make that substitution too.
"""
expr = expr.replace("PPow", "pow")
expr = expr.replace("ssqrt", "sqrt")
expr = expr.replace("safe_log(10.0_dp)", "ln10")
expr = expr.replace("log(10.0_dp)", "ln10")
expr = expr.replace("colon", ":")
return expr
def wrap_element(x):
if isinstance(x, Iterable):
return x
else:
return [x]
def indent_list(lines):
"""
Indent every string in a list of strings.
"""
return [tab + l for l in lines]
def indent_list_of_str(strings):
"""
Indents every line in a multi-line string.
"""
ret = []
for s in strings:
s = s.split("\n")
s = "\n".join(tab + l for l in s)
ret.append(s)
return ret