Utilities for MathJSON evaluation
Project description
MathJSON Solver
A reliable Python library for numerically evaluating mathematical expressions in MathJSON format. Perfect for applications that need to safely execute user-provided formulas, calculate dynamic equations, or process mathematical data.
What is MathJSON? MathJSON represents mathematical expressions as JSON arrays, like ["Add", 1, 2, 3] for 1+2+3. This format is safe, structured, and easy to generate programmatically.
Table of Contents
- Installation
- Quick Start
- Supported Operations
- Error Handling
- Use Cases
- Testing
- Community
- Contributing
Installation
pip install mathjson-solver
Requirements: Python 3.7+
Optional: numpy (only required for TrapezoidalIntegrate function)
Quick Start
from mathjson_solver import create_solver, MathJSONException
# Define variables and create solver
parameters = {"x": 2, "y": 3}
solver = create_solver(parameters)
# Evaluate expressions
basic_math = solver(["Add", "x", "y", 4])
print(basic_math) # 9 (because 2+3+4=9)
# More complex expressions
result = solver(["Multiply", ["Add", "x", 1], ["Subtract", "y", 1]])
print(result) # 6 (because (2+1) * (3-1) = 6)
# Handle errors gracefully
try:
solver(["Divide", 1, 0])
except MathJSONException as e:
print(f"Math error: {e}")
# Math error: Problem in Divide. ['Divide', 1, 0]. division by zero
Think Functional: MathJSON Solver embraces functional programming principles. Instead of writing loops and modifying variables, you compose expressions that transform data. Functions like Map, Reduce, and Filter let you process arrays elegantly, while immutable operations ensure predictable, side-effect-free calculations. Don't worry if you're new to functional programming — the examples will guide you naturally into this powerful paradigm.
# Functional approach: transform data with expressions
solver(["Map", ["Array", 1, 2, 3, 4], ["Multiply"], 2]) # [2, 4, 6, 8]
solver(["Reduce", ["Array", 1, 2, 3, 4], 0, ["Add", "acc", "item"],
["Variable", "acc"], ["Variable", "item"], ["Variable", "i"]]) # 10
Supported Operations
The library supports a comprehensive set of mathematical operations:
- Arithmetic: Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round, Floor, Ceil
- Trigonometry: Sin, Cos, Tan, Arcsin, Arccos, Arctan
- Logarithms: Log, Log2, Log10, Exp
- Comparison: Equal, StrictEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual
- Logic & Sets: Any, All, Not, And, Or, In, NotIn, ContainsAnyOf, ContainsAllOf, ContainsNoneOf
- Statistics: Average, Max, Min, Median, Length
- Functional Programming: Map, Reduce, Filter
- Arrays: Array creation, GenerateRange, AtIndex, Slice, Appended, CumulativeSum, CumulativeProduct
- Control Flow: If statements, Switch-Case, Constants definition
- Type Conversion: Int, Float, Str, IsDefined
- Date/Time: Strptime, Strftime, Today, Now, TimeDelta functions (Weeks, Days, Hours, Minutes)
- Integration: TrapezoidalIntegrate (requires numpy), Interp, FindIntervalIndex, Variable references
- Advanced: HasMatchingSublist for pattern matching
- Constants: Pi
View complete documentation with examples →
Error Handling
MathJSON Solver raises MathJSONException for invalid expressions or mathematical errors:
from mathjson_solver import create_solver, MathJSONException
solver = create_solver({})
# Handle specific math errors
try:
result = solver(["Sqrt", -1]) # Invalid: square root of negative
except MathJSONException as e:
print(f"Cannot evaluate: {e}")
# Handle malformed expressions
try:
result = solver(["UnknownFunction", 1, 2])
except MathJSONException as e:
print(f"Unsupported operation: {e}")
Use Cases
- Dynamic Formulas: Let users create custom calculations in web applications
- Scientific Computing: Evaluate mathematical models with variable parameters
- Business Logic: Process complex pricing rules or scoring algorithms
- Data Processing: Apply mathematical transformations to datasets
- Health Applications: Calculate medical scores, dosages, or risk assessments
Testing
Install development dependencies and run tests:
# Install pytest if not already installed
pip install pytest
# Run tests from project directory
pytest
# Run with coverage
pytest --cov=mathjson_solver
Community
- Questions & Discussion: GitHub Issues
- Bug Reports & Feature Requests: GitHub Issues
- Documentation: Complete Function Reference
Contributing
We welcome contributions! Please feel free to:
- Report bugs or request features via GitHub Issues
- Submit pull requests with improvements
License
References
This implementation was inspired by the CortexJS Compute Engine, though designed as an independent implementation focused on our specific use cases.
Made with ❤️ by Longenesis
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mathjson_solver-1.18.0.tar.gz.
File metadata
- Download URL: mathjson_solver-1.18.0.tar.gz
- Upload date:
- Size: 28.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5ee159638e76d0cf278394eda1145c6f293fb66906e5ed30103d05273031a3a1
|
|
| MD5 |
df0e5bcf74fdad340b84acd76411d030
|
|
| BLAKE2b-256 |
0cf915d1bb4c07408e72c6dc4b9a3d2de8d54fc84b088bd967350d94858aa2a8
|
File details
Details for the file mathjson_solver-1.18.0-py3-none-any.whl.
File metadata
- Download URL: mathjson_solver-1.18.0-py3-none-any.whl
- Upload date:
- Size: 12.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0f31804509ce4bc2fbb43099d4500b1ceab6a371adbe6cb7273be3a752a4a489
|
|
| MD5 |
d4b3254d1064c2e9d0178e7edff572cf
|
|
| BLAKE2b-256 |
1287c84edd014dac9fd50d88c4fbc06c174c2d8b658bd71fe46d0382c7a23151
|