MathJSON Solver is a Python module to numerically evaluate MathJSON expressions, like ["Add", 1, 2]. It is developed by Longenesis to enable numerical evaluation of user provided mathematical expressions in Longenesis digital health products. Its development was inspired by CortexJS Compute Engine.
Please ask questions and share feedback in our Gitter chat https://gitter.im/mathjson-solver/community.
from mathjson_solver import create_solver
parameters = {"x": 2, "y": 3}
expression = ["Add", "x", "y", 4]
solver = create_solver(parameters)
answer = solver(expression)
print(answer)
# 9, because 2+3+4=9Find the full list of supported constructs in the docs/README.md.
A MathJSONException is raised when expression cannot be evaluated. Import MathJSONException to handle it:
from mathjson_solver import create_solver, MathJSONException
solver = create_solver({})
try:
solver(["Divide", 1, 0])
except MathJSONException:
pass
# invoke your own exception logger hereLeft unhandled, the exception will look like MathJSONException("Problem in Divide. ['Divide', 1, 0]. division by zero").
By default, a parameter that is not defined evaluates to its own name, as a string, and each operator handles that string its own way (comparisons return False, Add skips it). Use create_solver(parameters, strict=True) to raise instead:
from mathjson_solver import create_solver, MathJSONException
solver = create_solver({"a": 0.7, "b": None}, strict=True)
solver(["Greater", "c", 0.6]) # MathJSONException: Parameter 'c' is not defined
solver(["Add", "a", "b"]) # MathJSONException: Parameter 'b' is NoneThe exception's e is a MathJSONUnresolvedParameter (a KeyError), and its expr / construct are the innermost expression containing the parameter.
In strict mode:
- a parameter whose value is
Noneis unresolved too; - string values of parameters are returned as is, not resolved again as names;
- string literals must be written with
Str:["Str", "plasma"]returns"plasma"without looking it up. Bare strings anywhere else (Switchcases,Inarrays,Strptimeformats, ...) are parameter names; If,MapandHasMatchingSubliststill catch aMathJSONExceptionraised by a branch or an element, as they do in the default mode.
Make sure you have pytest installed. Then cd into project directory and run:
pytest