-
Notifications
You must be signed in to change notification settings - Fork 1
/
evaluation.py
84 lines (66 loc) · 2.27 KB
/
evaluation.py
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import sympy as sp
def calculate(equation, mapping, error=''):
solution = ''
try:
sympy_expr = sp.simplify(sp.sympify(equation, evaluate=True))
except:
error = "Sympifying equation failed"
return solution, error
variables = []
for k, v in mapping.items():
variables.append(sp.Symbol(v))
return sympy_expr.evalf(), error
def polynomial(expression, mapping):
solution, error = '', ''
if '=' not in expression:
equation = expression
else:
splitted_expr = expression.split('=')
if len(splitted_expr) != 2 or splitted_expr[0] == '' or splitted_expr[1] == '':
error = 'Missing left or right side'
return solution, error
lhs, rhs = splitted_expr[0], splitted_expr[1]
# Move the right-hand side to the left-hand side with negative sign
equation = lhs + '- (' + rhs + ')'
try:
sympy_eqn = sp.simplify(sp.sympify(equation))
except:
error = "Sympifying equation failed"
return solution, error
if len(mapping) == 0:
return calculate(expression, mapping, error)
variables = []
for k, v in mapping.items():
variables.append(sp.Symbol(v))
return sp.solve(sympy_eqn, variables), error
def differentiate(expression, mapping):
solution, error = '', ''
try:
sympy_eqn = sp.sympify(expression)
except:
error = "Sympifying equation failed"
return solution, error
if len(mapping) > 1:
error = 'Wrong number of variables to differentiate with respect to'
return solution, error
elif len(mapping) == 1:
variable = ''
for k, v in mapping.items():
variable = sp.Symbol(v)
return sp.diff(sympy_eqn, variable), error
else:
return sp.diff(sympy_eqn), error
def integrate(expression, mapping):
solution, error = '', ''
try:
sympy_eqn = sp.sympify(expression)
except:
error = "Sympifying equation failed"
return solution, error
if len(mapping) != 1:
error = 'Wrong number of variables to integrate with respect to'
return solution, error
variable = ''
for k, v in mapping.items():
variable = sp.Symbol(v)
return sp.integrate(sympy_eqn, variable), error