Coverage for ase/utils/parsemath.py: 85.42%
96 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""A Module to safely parse/evaluate Mathematical Expressions"""
3import ast
4import math
5import operator as op
7from numpy import int64
9# Sets the limit of how high the number can get to prevent DNS attacks
10max_value = 1e17
13# Redefine mathematical operations to prevent DNS attacks
14def add(a, b):
15 """Redefine add function to prevent too large numbers"""
16 if any(abs(n) > max_value for n in [a, b]):
17 raise ValueError((a, b))
18 return op.add(a, b)
21def sub(a, b):
22 """Redefine sub function to prevent too large numbers"""
23 if any(abs(n) > max_value for n in [a, b]):
24 raise ValueError((a, b))
25 return op.sub(a, b)
28def mul(a, b):
29 """Redefine mul function to prevent too large numbers"""
30 if a == 0.0 or b == 0.0:
31 pass
32 elif math.log10(abs(a)) + math.log10(abs(b)) > math.log10(max_value):
33 raise ValueError((a, b))
34 return op.mul(a, b)
37def div(a, b):
38 """Redefine div function to prevent too large numbers"""
39 if b == 0.0:
40 raise ValueError((a, b))
41 elif a == 0.0:
42 pass
43 elif math.log10(abs(a)) - math.log10(abs(b)) > math.log10(max_value):
44 raise ValueError((a, b))
45 return op.truediv(a, b)
48def power(a, b):
49 """Redefine pow function to prevent too large numbers"""
50 if a == 0.0:
51 return 0.0
52 elif b / math.log(max_value, abs(a)) >= 1:
53 raise ValueError((a, b))
54 return op.pow(a, b)
57def exp(a):
58 """Redefine exp function to prevent too large numbers"""
59 if a > math.log(max_value):
60 raise ValueError(a)
61 return math.exp(a)
64# The list of allowed operators with defined functions they should operate on
65operators = {
66 ast.Add: add,
67 ast.Sub: sub,
68 ast.Mult: mul,
69 ast.Div: div,
70 ast.Pow: power,
71 ast.USub: op.neg,
72 ast.Mod: op.mod,
73 ast.FloorDiv: op.ifloordiv,
74}
76# Take all functions from math module as allowed functions
77allowed_math_fxn = {
78 'sin': math.sin,
79 'cos': math.cos,
80 'tan': math.tan,
81 'asin': math.asin,
82 'acos': math.acos,
83 'atan': math.atan,
84 'atan2': math.atan2,
85 'hypot': math.hypot,
86 'sinh': math.sinh,
87 'cosh': math.cosh,
88 'tanh': math.tanh,
89 'asinh': math.asinh,
90 'acosh': math.acosh,
91 'atanh': math.atanh,
92 'radians': math.radians,
93 'degrees': math.degrees,
94 'sqrt': math.sqrt,
95 'log': math.log,
96 'log10': math.log10,
97 'log2': math.log2,
98 'fmod': math.fmod,
99 'abs': math.fabs,
100 'ceil': math.ceil,
101 'floor': math.floor,
102 'round': round,
103 'exp': exp,
104}
107def get_function(node):
108 """Get the function from an ast.node"""
110 # The function call can be to a bare function or a module.function
111 if isinstance(node.func, ast.Name):
112 return node.func.id
113 elif isinstance(node.func, ast.Attribute):
114 return node.func.attr
115 else:
116 raise TypeError('node.func is of the wrong type')
119def limit(max_=None):
120 """Return decorator that limits allowed returned values."""
121 import functools
123 def decorator(func):
124 @functools.wraps(func)
125 def wrapper(*args, **kwargs):
126 ret = func(*args, **kwargs)
127 try:
128 mag = abs(ret)
129 except TypeError:
130 pass # not applicable
131 else:
132 if mag > max_:
133 raise ValueError(ret)
134 if isinstance(ret, int):
135 ret = int64(ret)
136 return ret
138 return wrapper
140 return decorator
143@limit(max_=max_value)
144def _eval(node):
145 """Evaluate a mathematical expression string parsed by ast"""
146 # Allow evaluate certain types of operators
147 if isinstance(node, ast.Constant) and isinstance(node.value, (float, int)):
148 return node.value
149 elif isinstance(node, ast.BinOp): # <left> <operator> <right>
150 return operators[type(node.op)](_eval(node.left), _eval(node.right))
151 elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
152 return operators[type(node.op)](_eval(node.operand))
153 elif isinstance(node, ast.Call): # using math.function
154 func = get_function(node)
155 # Evaluate all arguments
156 evaled_args = [_eval(arg) for arg in node.args]
157 return allowed_math_fxn[func](*evaled_args)
158 elif isinstance(node, ast.Name):
159 if node.id.lower() == 'pi':
160 return math.pi
161 elif node.id.lower() == 'e':
162 return math.e
163 elif node.id.lower() == 'tau':
164 return math.pi * 2.0
165 else:
166 raise TypeError(
167 'Found a str in the expression, either param_dct/the '
168 'expression has a mistake in the parameter names or '
169 'attempting to parse non-mathematical code'
170 )
171 else:
172 raise TypeError(node)
175def eval_expression(expression, param_dct=None):
176 """Parse a mathematical expression,
178 Replaces variables with the values in param_dict and solves the expression
180 """
181 if param_dct is None:
182 param_dct = {}
183 if not isinstance(expression, str):
184 raise TypeError('The expression must be a string')
185 if len(expression) > 1e4:
186 raise ValueError('The expression is too long.')
188 expression_rep = expression.strip()
190 if '()' in expression_rep:
191 raise ValueError('Invalid operation in expression')
193 for key, val in param_dct.items():
194 expression_rep = expression_rep.replace(key, str(val))
196 return _eval(ast.parse(expression_rep, mode='eval').body)