mathjson-solver 2.2.1__tar.gz → 2.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/CHANGELOG.md +36 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/PKG-INFO +67 -45
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/README.md +64 -44
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/SECURITY.md +3 -2
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/docs/README.md +472 -12
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/pyproject.toml +9 -1
- mathjson_solver-2.3.0/src/mathjson_solver/__main__.py +1285 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_arithmetic_constructs.py +219 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_array_arithmetic_constructs.py +283 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_array_helpers.py +55 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_collection_constructs.py +819 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_combinatorics.py +31 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_combinatorics_constructs.py +87 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_common.py +136 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_comparison_constructs.py +114 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_construct_shared.py +62 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_control_flow_constructs.py +100 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_core_constructs.py +64 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_datetime_constructs.py +46 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_exceptions.py +46 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_functional_constructs.py +133 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_interpolation.py +69 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_number_theory.py +298 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_number_theory_constructs.py +257 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_special_function_constructs.py +166 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_special_functions.py +157 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_statistics_constructs.py +473 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_string_constructs.py +364 -0
- mathjson_solver-2.3.0/src/mathjson_solver/_trig_constructs.py +34 -0
- mathjson_solver-2.3.0/tests/test_blacklist.py +74 -0
- mathjson_solver-2.3.0/tests/test_cortexjs_combinatorics.py +101 -0
- mathjson_solver-2.3.0/tests/test_cortexjs_core.py +71 -0
- mathjson_solver-2.3.0/tests/test_cortexjs_distributions.py +126 -0
- mathjson_solver-2.3.0/tests/test_cortexjs_number_theory.py +167 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_cortexjs_sets.py +29 -0
- mathjson_solver-2.3.0/tests/test_cortexjs_special_functions.py +167 -0
- mathjson_solver-2.3.0/tests/test_cortexjs_statistics.py +157 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_cortexjs_tier3.py +29 -0
- mathjson_solver-2.3.0/tests/test_scope_isolation.py +123 -0
- mathjson_solver-2.2.1/src/mathjson_solver/__main__.py +0 -2869
- mathjson_solver-2.2.1/tests/test_cortexjs_statistics.py +0 -75
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/.gitignore +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/CODE_OF_CONDUCT.md +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/CONTRIBUTING.md +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/LICENSE +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/docs/integration-test-cases.md +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/src/mathjson_solver/__init__.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_TrapezoidalIntegratel.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_atindex.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_cortexjs_collections.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_cortexjs_compat.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_cortexjs_constants_relations.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_cortexjs_strings.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_cumulative.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_datetime.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_equal.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_exceptions.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_extract_variables.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_findinterval.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_gail_model.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_interpolate.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_legacy_compat.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_range.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_reduce_simple.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_scalars.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_sets.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_simple_cases.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_slice.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_state_tuples_reduce.py +0 -0
- {mathjson_solver-2.2.1 → mathjson_solver-2.3.0}/tests/test_with_pytest.py +0 -0
|
@@ -5,6 +5,42 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
7
7
|
|
|
8
|
+
## [2.3.0] - 2026-09-21
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- 2-3x faster evaluation on arithmetic- and `Reduce`-heavy expressions. No behavior change.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- **`extract_variables` treated unrecognized constructs' arguments as free variables.** `["Color", "red"]` would report `"red"` as a parameter to supply, even though it's a literal argument to a construct this solver doesn't implement - not a variable reference. `extract_variables` now mirrors `f()`'s own fallback for an unrecognized construct (return the expression unchanged, never evaluating or substituting into its arguments): it's treated as opaque data, contributing no free variables, rather than recursed into. Applies to any unimplemented construct (`Color`, `Quantity`, etc.), not just specific names. The same treatment was extended to `Head`/`Tail`/`Hold`/`IsSame`/`Same` (new in this release, see below), which likewise never evaluate their arguments.
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- **More statistics:** `Skewness`, `Kurtosis` (sample-adjusted, matching Excel's `SKEW`/`KURT` and `scipy.stats.skew`/`kurtosis` with `bias=False`), `LinearRegression` (least-squares fit, returns `["Array", slope, intercept]`), `PolynomialFit` (least-squares fit of a given degree via the normal equations, no numpy dependency, returns `["Array", c0, c1, ..., cd]` - lowest degree first, the opposite order from `numpy.polyfit`). `PolynomialFit`'s degree is capped at 50.
|
|
21
|
+
- **Probability distributions:** `NormalDistribution`, `BinomialDistribution`, `PoissonDistribution`, `UniformDistribution`, `ExponentialDistribution`, queried via `PDF`/`CDF`/`Quantile` (e.g. `["CDF", ["NormalDistribution", 0, 1], 1.5]`), matching CortexJS's calling convention. `PDF` needs no optional dependency for any of the five, including the two discrete distributions (uses a log-space reformulation - the direct formula overflows a float well within realistic `n`). `Binomial`/`PoissonDistribution`'s `CDF`/`Quantile` use the already-shipped `GammaRegularized`/`BetaRegularized` identities and so require the `special-functions` extra; the other three distributions' `CDF`/`Quantile` don't need it either.
|
|
22
|
+
- **Number theory**, ~45 new functions:
|
|
23
|
+
- stdlib-based: `PowerMod`, `ModularInverse`, `IntegerSqrt`
|
|
24
|
+
- Factorization: `FactorInteger`, `PrimeFactors`, `PrimeNu`, `PrimeOmega`, `Radical`, `IsSquareFree`
|
|
25
|
+
- Divisors: `Divisors`, `Sigma0`, `Sigma1`, `SigmaMinus1`, `DivisorSigma`, `Divides`, `Totient`, `IsPerfectPower`
|
|
26
|
+
- Prime lookups (capped - `NthPrime`'s `n`/`NextPrime`'s `k` at 10,000, `NextPrime`'s starting value and every factorization-based function above at `10**12`, `PrimePi`'s `n` at 100,000; picked from measured worst-case timing, not guessed): `NthPrime`, `NextPrime`, `PrimePi`
|
|
27
|
+
- Modular structure: `ExtendedGCD`, `ChineseRemainder`, `CarmichaelLambda`, `JacobiSymbol`, `LegendreSymbol`, `MultiplicativeOrder`, `PrimitiveRoot`
|
|
28
|
+
- Sequences: `LucasL`, `CatalanNumber`, `BernoulliB` (exact, via `fractions.Fraction`; uses the B₁ = -1/2 convention), `ContinuedFraction`, `FromContinuedFraction`
|
|
29
|
+
- Digit manipulation (array form, alongside the existing string-based `IntegerString`/`DigitsFrom`): `IntegerDigits`, `DigitCount`, `DigitSum`, `FromDigits`
|
|
30
|
+
- Figurate numbers and predicates: `IsSquare`, `IsTriangular`, `IsPentagonal`, `IsOctahedral`, `IsCenteredSquare`, `IsPerfect`, `IsAbundant`, `IsHappy`
|
|
31
|
+
|
|
32
|
+
Not included: `RandomPrime` (nondeterminism, same reasoning as `Random`/`RandomChoice`/`RandomSample`).
|
|
33
|
+
- **`Subset`, `SubsetEqual`, `Superset`, `SupersetEqual`, `NotSubset`, `NotSuperset`** - proper/non-proper subset and superset tests over `Array`, matching CortexJS's Sets page.
|
|
34
|
+
- **`Interval`/`Open`, and range membership via `Element`/`In`** - `["Element", x, ["Interval", 0, 1]]` matches CortexJS's own convention for "x is in [0, 1]" exactly (`ce.parse("x \in [0, 1]").json` produces this same shape). Either endpoint can be wrapped in `["Open", endpoint]` to exclude it (e.g. `["Interval", 0, ["Open", 1]]` for the half-open `[0, 1)`); a bare endpoint is included (closed) by default. `In`/`Element` now recognize `Interval` as a domain alongside the existing `Array`/string support.
|
|
35
|
+
- **Special functions:** `Gamma`, `GammaLn` (`math.gamma`/`math.lgamma`), `Beta`, `Factorial2`, and verified iterative algorithms `ErfInv`, `LambertW`, `AGM`, `EllipticK`, `EllipticE` (the "parameter" convention `K(m)`/`E(m)`, `m = k²`), `Hypergeometric1F1`, `Hypergeometric2F1` (defining power series; `Hypergeometric1F1` capped at `|z| <= 500` and uses Kummer's transformation for `z < 0` to avoid catastrophic cancellation, `Hypergeometric2F1` restricted to `|z| < 1`, its actual radius of convergence). Not included: `JacobiTheta`, `DedekindEta` - `scipy.special` (see below) doesn't implement these either, so they'd need a from-scratch q-series with the same "subtly wrong across the domain" risk as any other naive truncated series.
|
|
36
|
+
- **`BesselJ`/`BesselY`/`BesselI`/`BesselK`, `AiryAi`/`AiryBi`/`AiryAiPrime`/`AiryBiPrime`, `Zeta`, `GammaRegularized`, `BetaRegularized`** - thin wrappers around `scipy.special`, behind a new optional `special-functions` extra (`pip install mathjson-solver[special-functions]`), same pattern as `integration`/`regex`. `GammaRegularized(a, z)` is the *upper* regularized incomplete gamma (`scipy`'s own `gammainc` is the lower form; this uses `gammaincc`); `BetaRegularized(x, a, b)` puts `x` first, unlike `scipy.special.betainc`'s `(a, b, x)`. Without the extra installed, these raise a clear `ImportError` naming the missing package.
|
|
37
|
+
- **Combinatorics:** `Choose` (alias for `Binomial`), `Fibonacci`, `Multinomial`, `Subfactorial`, `BellNumber`, and the enumeration functions `PowerSet`, `Permutations`, `Combinations`, `CartesianProduct` - the latter four have **no built-in output-size limit** (a set of `n` elements has `2^n` subsets, etc.); see the new `blacklist` parameter below for disabling them in deployments that accept untrusted expressions.
|
|
38
|
+
- **Core (structural introspection):** `Head`/`Tail` (operator name / argument list of a compound expression, read from the raw unevaluated tree), `Hold` (returns an argument unevaluated), `Identity`, `Type` (runtime kind of an evaluated value), `IsSame`/`Same` (structural, pre-evaluation equality - distinct from `Equal`/`StrictEqual`/`IdenticallyEqual`, which all compare evaluated values). Not included: CAS functions (`Evaluate`, `Expand`, `Simplify`, `Solve`, ...), mutable-state functions (`Declare`, `Assign`, `Assume`, ...), and LaTeX serialization (`Parse`, `Latex`, `Subscript`, ...) - same reasoning as elsewhere in this solver (no CAS, no mutable state, no rendering surface). `Error`/`IsError` also not included - this solver already has an established, different error model (`MathJSONException`).
|
|
39
|
+
- **`create_solver(parameters, blacklist=[...])`**: disables the named constructs for that solver instance, raising `MathJSONException` if an expression tries to use one, rather than evaluating it or silently ignoring it. An access-policy control, not a resource limiter - it doesn't make an enabled construct safe against pathological input (in particular, it's the recommended way to disable the four uncapped enumeration functions above for untrusted expression sources). A blacklisted name that isn't an actual construct has no effect (not validated against the known-construct list).
|
|
40
|
+
- **Type hints on the public API**: `create_solver`, `MathJSONException`, `extract_variables`, `translate_v1_mathjson` now have accurate parameter/return type hints, built on one shared `MathJSONExpression` alias for a MathJSON node (`str | int | float | bool | None | list[MathJSONExpression]`). The ~300 per-construct functions inside `create_solver`'s closure remain untyped - they operate on arbitrary runtime values by design (a construct can produce a `Fraction`, a `datetime.timedelta`, a compiled regex pattern, ...), so annotating each one wouldn't add real type safety.
|
|
41
|
+
|
|
42
|
+
[2.3.0]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.2.1...v2.3.0
|
|
43
|
+
|
|
8
44
|
## [2.2.1] - 2026-09-14
|
|
9
45
|
|
|
10
46
|
### Fixed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mathjson-solver
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: Utilities for MathJSON evaluation
|
|
5
5
|
Project-URL: Homepage, https://github.com/LongenesisLtd/mathjson-solver
|
|
6
6
|
Project-URL: Bug Tracker, https://github.com/LongenesisLtd/mathjson-solver/issues
|
|
@@ -14,32 +14,47 @@ Provides-Extra: integration
|
|
|
14
14
|
Requires-Dist: numpy; extra == 'integration'
|
|
15
15
|
Provides-Extra: regex
|
|
16
16
|
Requires-Dist: google-re2; extra == 'regex'
|
|
17
|
+
Provides-Extra: special-functions
|
|
18
|
+
Requires-Dist: scipy; extra == 'special-functions'
|
|
17
19
|
Description-Content-Type: text/markdown
|
|
18
20
|
|
|
19
21
|
# MathJSON Solver
|
|
20
22
|
|
|
21
23
|
[](https://pypi.org/project/mathjson-solver/)
|
|
22
24
|
[](https://pepy.tech/projects/mathjson-solver)
|
|
23
|
-
[) as part of steering back towards greater compatibility with [CortexJS MathJSON](https://cortexjs.io/compute-engine/): `Log` is now log base 10 instead of natural log. Stuck on pre-2.0.0 expressions but want the functions added in 2.x? Pass `legacy_v1=True` to `create_solver()` (see [Migrating from 1.x](#migrating-from-1x)) instead of hand-migrating every expression. Bugfix releases for the 1.x line also continue on the [`1.x` branch](https://github.com/LongenesisLtd/mathjson-solver/tree/1.x).
|
|
25
|
+
[](https://www.python.org/downloads/)
|
|
26
26
|
|
|
27
27
|
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.
|
|
28
28
|
|
|
29
29
|
**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.
|
|
30
30
|
|
|
31
|
+
Coming from 1.x? Version 2 changed `Log`'s meaning — see [Migrating from 1.x](#migrating-from-1x).
|
|
32
|
+
|
|
31
33
|
## Table of Contents
|
|
34
|
+
- [Use Cases](#use-cases)
|
|
32
35
|
- [Installation](#installation)
|
|
33
36
|
- [Quick Start](#quick-start)
|
|
34
|
-
- [Migrating from 1.x](#migrating-from-1x)
|
|
35
37
|
- [Supported Operations](#supported-operations)
|
|
38
|
+
- [Restricting Available Functions](#restricting-available-functions)
|
|
36
39
|
- [Error Handling](#error-handling)
|
|
37
|
-
- [
|
|
40
|
+
- [Migrating from 1.x](#migrating-from-1x)
|
|
38
41
|
- [Testing](#testing)
|
|
39
42
|
- [Community](#community)
|
|
40
43
|
- [Contributing](#contributing)
|
|
41
44
|
- [Related Projects](#related-projects)
|
|
42
45
|
|
|
46
|
+
## Use Cases
|
|
47
|
+
|
|
48
|
+
**The core pattern:** if your Python backend accepts user-provided datapoints *and* user-provided math to apply to them, mathjson-solver is the engine for that — it evaluates the formula without needing to trust either the formula's author or the data's source. A survey platform is a natural fit: a survey and its "calculated answers" both come from the same untrusted party (the survey builder), the calculation runs against whatever the respondent enters, and the result has to be safe to compute no matter what either of them contains. The same shape covers pricing rules, scoring algorithms, and scientific or medical calculators wherever the formula itself isn't fixed at development time — our showcase example is a breast-cancer risk calculator implementing the [Gail model](https://github.com/LongenesisLtd/mathjson-solver/blob/main/tests/test_gail_model.py), numerical integration included, entirely in MathJSON.
|
|
49
|
+
|
|
50
|
+
* **Dynamic Formulas:** Let users create custom calculations in web applications
|
|
51
|
+
* **Scientific Computing:** Evaluate mathematical models with variable parameters
|
|
52
|
+
* **Business Logic:** Process complex pricing rules or scoring algorithms
|
|
53
|
+
* **Data Processing:** Apply mathematical transformations to datasets
|
|
54
|
+
* **Health Applications:** Calculate medical scores, dosages, or risk assessments
|
|
55
|
+
|
|
56
|
+
**What's still missing:** a ready-to-use, user-facing editor for authoring MathJSON itself — today, the expressions have to come from somewhere else (a form builder, a generated JSON structure, hand-written JSON). CortexJS ships [MathLive's mathfield](https://mathlive.io/mathfield/) for entering math, but it's built for typing LaTeX-style notation (e-learning quizzes, scientific computing, calculators) — not for assembling a formula that references named fields from a form. Worth evaluating on its own merits rather than assumed to transfer.
|
|
57
|
+
|
|
43
58
|
## Installation
|
|
44
59
|
|
|
45
60
|
```bash
|
|
@@ -51,6 +66,9 @@ pip install mathjson-solver
|
|
|
51
66
|
**Optional:**
|
|
52
67
|
- `pip install mathjson-solver[integration]` (installs numpy; only required for `TrapezoidalIntegrate`)
|
|
53
68
|
- `pip install mathjson-solver[regex]` (installs [google-re2](https://pypi.org/project/google-re2/); only required for `RegExp`/`IsMatch`/`StringMatch`/`StringMatchAll`)
|
|
69
|
+
- `pip install mathjson-solver[special-functions]` (installs [scipy](https://scipy.org/); required for `BesselJ`/`BesselY`/`BesselI`/`BesselK`, `AiryAi`/`AiryBi`/`AiryAiPrime`/`AiryBiPrime`, `Zeta`, `GammaRegularized`, `BetaRegularized`, and `CDF`/`Quantile` on `BinomialDistribution`/`PoissonDistribution`)
|
|
70
|
+
|
|
71
|
+
Combine any of these by separating them with commas in one `pip install`, e.g. `pip install mathjson-solver[integration,regex,special-functions]` for all three at once.
|
|
54
72
|
|
|
55
73
|
## Quick Start
|
|
56
74
|
|
|
@@ -90,50 +108,37 @@ solver(["Map", ["Array", 1, 2, 3, 4], ["Function", ["Multiply", "_", 2]]]) # [2
|
|
|
90
108
|
solver(["Reduce", ["Array", 1, 2, 3, 4], ["Add"]]) # 10
|
|
91
109
|
```
|
|
92
110
|
|
|
93
|
-
##
|
|
94
|
-
|
|
95
|
-
Version 2.0.0's only breaking change is `Log`: pre-2.0.0 it was always natural log, `["Log", x]` == `math.log(x)`. From 2.0.0 on it matches [CortexJS](https://cortexjs.io/compute-engine/) — `["Log", x]` is log base 10, `["Log", x, b]` is log base `b` — and natural log moved to `Ln`.
|
|
111
|
+
## Supported Operations
|
|
96
112
|
|
|
97
|
-
|
|
113
|
+
338 MathJSON constructs across arithmetic, trigonometry, logarithms, comparisons, logic and sets, statistics and probability distributions, functional programming (Map/Reduce/Filter), arrays and collections, control flow, strings and RE2-backed pattern matching, date/time, number theory, special functions (Bessel/Airy/Gamma/elliptic-integral/hypergeometric families), combinatorics, and structural introspection.
|
|
98
114
|
|
|
99
115
|
```python
|
|
100
|
-
|
|
101
|
-
|
|
116
|
+
["Add", 1, 2, ["Multiply", 3, 4]] # 15
|
|
117
|
+
["CDF", ["NormalDistribution", 0, 1], 1.96] # 0.975 (z-score to percentile)
|
|
118
|
+
["Reduce", ["Array", 1, 2, 3, 4], ["Add"]] # 10
|
|
119
|
+
["StringMatch", "patient-042", "[0-9]+"] # "042" at position 9-11
|
|
120
|
+
["FactorInteger", 360] # [[2,3], [3,2], [5,1]] (2³·3²·5)
|
|
102
121
|
```
|
|
103
122
|
|
|
104
|
-
|
|
123
|
+
Three optional extras unlock specific functions — see [Installation](#installation) above: `regex` (RE2-backed pattern matching), `integration` (`TrapezoidalIntegrate`), `special-functions` (Bessel/Airy/Zeta/regularized gamma and beta, plus `CDF`/`Quantile` on the two discrete probability distributions).
|
|
124
|
+
|
|
125
|
+
[View the complete function reference with examples →](https://github.com/LongenesisLtd/mathjson-solver/blob/main/docs/README.md)
|
|
126
|
+
|
|
127
|
+
## Restricting Available Functions
|
|
128
|
+
|
|
129
|
+
Pass `blacklist` to disable specific constructs for a solver instance — useful when evaluating expressions from a source you don't fully trust, or when your deployment simply doesn't want certain functions exposed:
|
|
105
130
|
|
|
106
131
|
```python
|
|
107
|
-
|
|
132
|
+
solver = create_solver(parameters, blacklist=["PowerSet", "Permutations", "Combinations", "CartesianProduct"])
|
|
133
|
+
solver(["PowerSet", ["Array", 1, 2, 3]])
|
|
134
|
+
# Raises: MathJSONException: Problem in PowerSet. [...]. 'PowerSet' has been disabled in this solver instance.
|
|
108
135
|
|
|
109
|
-
|
|
136
|
+
solver(["Add", 1, 2]) # unaffected constructs still work: 3.0
|
|
110
137
|
```
|
|
111
138
|
|
|
112
|
-
`
|
|
113
|
-
|
|
114
|
-
## Supported Operations
|
|
139
|
+
**This is an access-policy control, not a resource limiter.** Blacklisting a construct stops it from running at all; it doesn't make an *enabled* construct safe against pathological input. In particular, the enumeration functions (`PowerSet`, `Permutations`, `Combinations`, `CartesianProduct`) have no built-in output-size limit — `["PowerSet", ["Range", 30]]` will try to materialize over a billion subsets if you let it run. If you're evaluating expressions from an untrusted source, blacklist any construct whose worst-case cost you haven't reasoned about, rather than assuming everything implemented is safe by default for every threat model.
|
|
115
140
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
* **Arithmetic:** Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round, Floor, Ceil
|
|
119
|
-
* **Trigonometry:** Sin, Cos, Tan, Arcsin, Arccos, Arctan, Arctan2, Cot, Sec, Csc (+ inverses), Sinh, Cosh, Tanh, Coth, Sech, Csch (+ inverses), Hypot, Sinc
|
|
120
|
-
* **Logarithms:** Log (base 10, or base b), Log2/Lb, Log10/Lg, Ln (natural log), LogOnePlus, Exp
|
|
121
|
-
* **Comparison:** Equal, StrictEqual, IdenticallyEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual, Congruent
|
|
122
|
-
* **Logic & Sets:** Any, All, Not, And, Or, Xor, Nand, Nor, Implies, Equivalent, In/Element, NotIn/NotElement, ContainsAnyOf, ContainsAllOf, ContainsNoneOf, bare `True`/`False` literals, Union, Intersection, SetMinus, SymmetricDifference (over arrays - no dedicated Set type)
|
|
123
|
-
* **Statistics:** Average/Mean, Max, Min (both list and variadic forms), Median, Mode, Variance, StandardDeviation, PopulationVariance, PopulationStandardDeviation, Quartiles, InterquartileRange, Covariance, Correlation, Length/Count
|
|
124
|
-
* **Functional Programming:** Map/StrictMap, Reduce, Filter, Product (all also accept CortexJS calling conventions, including `Function` lambdas)
|
|
125
|
-
* **Arrays:** Array/List creation, GenerateRange, Range, AtIndex, At, Slice, Appended/Append, First, Second, Third, Last, Rest, Most, Reverse, Sort, Unique, Dedup, Join, Zip, IsEmpty, CumulativeSum, CumulativeProduct, Take, Drop, TakeWhile, DropWhile, Contains, IndexOf, IndexWhere, Find, CountIf, Position, RotateLeft, RotateRight, MaxBy, MinBy, ArgMax, ArgMin, Ordering, FlatMap, Scan, Differences, Fold, Insert, DeleteAt, ReplaceAt, Partition, Chunk, GroupBy, ChunkBy, Tally
|
|
126
|
-
* **Control Flow:** If statements (Python pair form and CortexJS flat form), Switch/StrictSwitch (value-equality case dispatch), Which (CortexJS flat condition/value chain), Constants definition
|
|
127
|
-
* **Type Conversion:** Int, Float, Str, IsDefined
|
|
128
|
-
* **Strings:** String, StringJoin, ToUpperCase, ToLowerCase, CaseFold, Trim, TrimStart, TrimEnd, StringSplit, StringReplace, StringCompare, StringRepeat, PadStart, PadEnd, Characters/GraphemeClusters, Utf8, Utf16, UnicodeScalars, StringFrom, IntegerString, DigitsFrom, NumberFrom
|
|
129
|
-
* **Pattern Matching (requires the optional `regex` extra, `pip install mathjson-solver[regex]`):** RegExp, IsMatch, StringMatch, StringMatchAll — backed by [RE2](https://github.com/google/re2) rather than Python's `re`, for a hard guarantee against catastrophic backtracking (no backreferences/lookaround, as a deliberate trade-off for that guarantee)
|
|
130
|
-
* **Date/Time:** Strptime, Strftime, Today, Now, TimeDelta functions (Weeks, Days, Hours, Minutes)
|
|
131
|
-
* **Number Theory:** Chop, Mod, Clamp, GCD, LCM, Factorial, Binomial, IsPrime, Erf, Erfc, Rational, Numerator, Denominator, MachineEpsilon, CatalanConstant, EulerGamma
|
|
132
|
-
* **Integration (requires the optional `integration` extra, `pip install mathjson-solver[integration]`):** TrapezoidalIntegrate. Also in this group but with no extra dependency: Interp, FindIntervalIndex, Variable references
|
|
133
|
-
* **Advanced:** HasMatchingSublist for pattern matching
|
|
134
|
-
* **Constants:** Pi, Degrees, ExponentialE, GoldenRatio
|
|
135
|
-
|
|
136
|
-
[View complete documentation with examples →](https://github.com/LongenesisLtd/mathjson-solver/blob/main/docs/README.md)
|
|
141
|
+
A blacklisted name that isn't an actual construct (a typo, for instance) is silently ignored rather than rejected — `blacklist` isn't validated against the list of implemented constructs.
|
|
137
142
|
|
|
138
143
|
## Error Handling
|
|
139
144
|
|
|
@@ -157,13 +162,28 @@ except MathJSONException as e:
|
|
|
157
162
|
print(f"Unsupported operation: {e}")
|
|
158
163
|
```
|
|
159
164
|
|
|
160
|
-
##
|
|
165
|
+
## Migrating from 1.x
|
|
161
166
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
+
> **Version 2 introduced a breaking change:** `Log` is now log base 10 instead of natural log (see [CHANGELOG.md](CHANGELOG.md)). Bugfix releases for the 1.x line continue on the [`1.x` branch](https://github.com/LongenesisLtd/mathjson-solver/tree/1.x).
|
|
168
|
+
|
|
169
|
+
Version 2.0.0's only breaking change is `Log`: pre-2.0.0 it was always natural log, `["Log", x]` == `math.log(x)`. From 2.0.0 on it matches [CortexJS](https://cortexjs.io/compute-engine/) — `["Log", x]` is log base 10, `["Log", x, b]` is log base `b` — and natural log moved to `Ln`.
|
|
170
|
+
|
|
171
|
+
If you have existing expressions built for 1.x and don't want to hand-edit every `Log` node just to pick up functions added in 2.x (`Product`, the CortexJS forms of `If`/`Map`/`Filter`/`Reduce`, the new aliases, etc.), pass `legacy_v1=True` when creating the solver. It rewrites every `["Log", x]` to `["Ln", x]` before evaluating, so old expressions keep producing the same results without modification:
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
solver = create_solver(parameters, legacy_v1=True)
|
|
175
|
+
solver(["Log", 8]) # 2.0794... (natural log, matching pre-2.0.0 behavior)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
You can also run the rewrite yourself and inspect or store the translated expression:
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
from mathjson_solver import translate_v1_mathjson
|
|
182
|
+
|
|
183
|
+
translate_v1_mathjson(["Add", ["Log", 8], 1]) # ["Add", ["Ln", 8], 1]
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`legacy_v1=True` only affects `Log`. Every other 1.x expression already evaluates identically on 2.x without any translation.
|
|
167
187
|
|
|
168
188
|
## Testing
|
|
169
189
|
|
|
@@ -196,6 +216,8 @@ We welcome contributions! Please feel free to:
|
|
|
196
216
|
|
|
197
217
|
We also created [`londec`](https://pypi.org/project/londec/) — evaluate tree-structured conditions against an ordered history of events. It uses mathjson-solver internally.
|
|
198
218
|
|
|
219
|
+
[`mathjson-tree-builder`](https://www.npmjs.com/package/mathjson-tree-builder) is a fully compatible frontend counterpart — a framework-agnostic, click-to-build editor for authoring MathJSON expressions in the browser.
|
|
220
|
+
|
|
199
221
|
## License
|
|
200
222
|
|
|
201
223
|
[View license information](https://github.com/LongenesisLtd/mathjson-solver/blob/main/LICENSE)
|
|
@@ -2,26 +2,39 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://pypi.org/project/mathjson-solver/)
|
|
4
4
|
[](https://pepy.tech/projects/mathjson-solver)
|
|
5
|
-
[) as part of steering back towards greater compatibility with [CortexJS MathJSON](https://cortexjs.io/compute-engine/): `Log` is now log base 10 instead of natural log. Stuck on pre-2.0.0 expressions but want the functions added in 2.x? Pass `legacy_v1=True` to `create_solver()` (see [Migrating from 1.x](#migrating-from-1x)) instead of hand-migrating every expression. Bugfix releases for the 1.x line also continue on the [`1.x` branch](https://github.com/LongenesisLtd/mathjson-solver/tree/1.x).
|
|
5
|
+
[](https://www.python.org/downloads/)
|
|
8
6
|
|
|
9
7
|
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.
|
|
10
8
|
|
|
11
9
|
**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.
|
|
12
10
|
|
|
11
|
+
Coming from 1.x? Version 2 changed `Log`'s meaning — see [Migrating from 1.x](#migrating-from-1x).
|
|
12
|
+
|
|
13
13
|
## Table of Contents
|
|
14
|
+
- [Use Cases](#use-cases)
|
|
14
15
|
- [Installation](#installation)
|
|
15
16
|
- [Quick Start](#quick-start)
|
|
16
|
-
- [Migrating from 1.x](#migrating-from-1x)
|
|
17
17
|
- [Supported Operations](#supported-operations)
|
|
18
|
+
- [Restricting Available Functions](#restricting-available-functions)
|
|
18
19
|
- [Error Handling](#error-handling)
|
|
19
|
-
- [
|
|
20
|
+
- [Migrating from 1.x](#migrating-from-1x)
|
|
20
21
|
- [Testing](#testing)
|
|
21
22
|
- [Community](#community)
|
|
22
23
|
- [Contributing](#contributing)
|
|
23
24
|
- [Related Projects](#related-projects)
|
|
24
25
|
|
|
26
|
+
## Use Cases
|
|
27
|
+
|
|
28
|
+
**The core pattern:** if your Python backend accepts user-provided datapoints *and* user-provided math to apply to them, mathjson-solver is the engine for that — it evaluates the formula without needing to trust either the formula's author or the data's source. A survey platform is a natural fit: a survey and its "calculated answers" both come from the same untrusted party (the survey builder), the calculation runs against whatever the respondent enters, and the result has to be safe to compute no matter what either of them contains. The same shape covers pricing rules, scoring algorithms, and scientific or medical calculators wherever the formula itself isn't fixed at development time — our showcase example is a breast-cancer risk calculator implementing the [Gail model](https://github.com/LongenesisLtd/mathjson-solver/blob/main/tests/test_gail_model.py), numerical integration included, entirely in MathJSON.
|
|
29
|
+
|
|
30
|
+
* **Dynamic Formulas:** Let users create custom calculations in web applications
|
|
31
|
+
* **Scientific Computing:** Evaluate mathematical models with variable parameters
|
|
32
|
+
* **Business Logic:** Process complex pricing rules or scoring algorithms
|
|
33
|
+
* **Data Processing:** Apply mathematical transformations to datasets
|
|
34
|
+
* **Health Applications:** Calculate medical scores, dosages, or risk assessments
|
|
35
|
+
|
|
36
|
+
**What's still missing:** a ready-to-use, user-facing editor for authoring MathJSON itself — today, the expressions have to come from somewhere else (a form builder, a generated JSON structure, hand-written JSON). CortexJS ships [MathLive's mathfield](https://mathlive.io/mathfield/) for entering math, but it's built for typing LaTeX-style notation (e-learning quizzes, scientific computing, calculators) — not for assembling a formula that references named fields from a form. Worth evaluating on its own merits rather than assumed to transfer.
|
|
37
|
+
|
|
25
38
|
## Installation
|
|
26
39
|
|
|
27
40
|
```bash
|
|
@@ -33,6 +46,9 @@ pip install mathjson-solver
|
|
|
33
46
|
**Optional:**
|
|
34
47
|
- `pip install mathjson-solver[integration]` (installs numpy; only required for `TrapezoidalIntegrate`)
|
|
35
48
|
- `pip install mathjson-solver[regex]` (installs [google-re2](https://pypi.org/project/google-re2/); only required for `RegExp`/`IsMatch`/`StringMatch`/`StringMatchAll`)
|
|
49
|
+
- `pip install mathjson-solver[special-functions]` (installs [scipy](https://scipy.org/); required for `BesselJ`/`BesselY`/`BesselI`/`BesselK`, `AiryAi`/`AiryBi`/`AiryAiPrime`/`AiryBiPrime`, `Zeta`, `GammaRegularized`, `BetaRegularized`, and `CDF`/`Quantile` on `BinomialDistribution`/`PoissonDistribution`)
|
|
50
|
+
|
|
51
|
+
Combine any of these by separating them with commas in one `pip install`, e.g. `pip install mathjson-solver[integration,regex,special-functions]` for all three at once.
|
|
36
52
|
|
|
37
53
|
## Quick Start
|
|
38
54
|
|
|
@@ -72,50 +88,37 @@ solver(["Map", ["Array", 1, 2, 3, 4], ["Function", ["Multiply", "_", 2]]]) # [2
|
|
|
72
88
|
solver(["Reduce", ["Array", 1, 2, 3, 4], ["Add"]]) # 10
|
|
73
89
|
```
|
|
74
90
|
|
|
75
|
-
##
|
|
76
|
-
|
|
77
|
-
Version 2.0.0's only breaking change is `Log`: pre-2.0.0 it was always natural log, `["Log", x]` == `math.log(x)`. From 2.0.0 on it matches [CortexJS](https://cortexjs.io/compute-engine/) — `["Log", x]` is log base 10, `["Log", x, b]` is log base `b` — and natural log moved to `Ln`.
|
|
91
|
+
## Supported Operations
|
|
78
92
|
|
|
79
|
-
|
|
93
|
+
338 MathJSON constructs across arithmetic, trigonometry, logarithms, comparisons, logic and sets, statistics and probability distributions, functional programming (Map/Reduce/Filter), arrays and collections, control flow, strings and RE2-backed pattern matching, date/time, number theory, special functions (Bessel/Airy/Gamma/elliptic-integral/hypergeometric families), combinatorics, and structural introspection.
|
|
80
94
|
|
|
81
95
|
```python
|
|
82
|
-
|
|
83
|
-
|
|
96
|
+
["Add", 1, 2, ["Multiply", 3, 4]] # 15
|
|
97
|
+
["CDF", ["NormalDistribution", 0, 1], 1.96] # 0.975 (z-score to percentile)
|
|
98
|
+
["Reduce", ["Array", 1, 2, 3, 4], ["Add"]] # 10
|
|
99
|
+
["StringMatch", "patient-042", "[0-9]+"] # "042" at position 9-11
|
|
100
|
+
["FactorInteger", 360] # [[2,3], [3,2], [5,1]] (2³·3²·5)
|
|
84
101
|
```
|
|
85
102
|
|
|
86
|
-
|
|
103
|
+
Three optional extras unlock specific functions — see [Installation](#installation) above: `regex` (RE2-backed pattern matching), `integration` (`TrapezoidalIntegrate`), `special-functions` (Bessel/Airy/Zeta/regularized gamma and beta, plus `CDF`/`Quantile` on the two discrete probability distributions).
|
|
104
|
+
|
|
105
|
+
[View the complete function reference with examples →](https://github.com/LongenesisLtd/mathjson-solver/blob/main/docs/README.md)
|
|
106
|
+
|
|
107
|
+
## Restricting Available Functions
|
|
108
|
+
|
|
109
|
+
Pass `blacklist` to disable specific constructs for a solver instance — useful when evaluating expressions from a source you don't fully trust, or when your deployment simply doesn't want certain functions exposed:
|
|
87
110
|
|
|
88
111
|
```python
|
|
89
|
-
|
|
112
|
+
solver = create_solver(parameters, blacklist=["PowerSet", "Permutations", "Combinations", "CartesianProduct"])
|
|
113
|
+
solver(["PowerSet", ["Array", 1, 2, 3]])
|
|
114
|
+
# Raises: MathJSONException: Problem in PowerSet. [...]. 'PowerSet' has been disabled in this solver instance.
|
|
90
115
|
|
|
91
|
-
|
|
116
|
+
solver(["Add", 1, 2]) # unaffected constructs still work: 3.0
|
|
92
117
|
```
|
|
93
118
|
|
|
94
|
-
`
|
|
95
|
-
|
|
96
|
-
## Supported Operations
|
|
119
|
+
**This is an access-policy control, not a resource limiter.** Blacklisting a construct stops it from running at all; it doesn't make an *enabled* construct safe against pathological input. In particular, the enumeration functions (`PowerSet`, `Permutations`, `Combinations`, `CartesianProduct`) have no built-in output-size limit — `["PowerSet", ["Range", 30]]` will try to materialize over a billion subsets if you let it run. If you're evaluating expressions from an untrusted source, blacklist any construct whose worst-case cost you haven't reasoned about, rather than assuming everything implemented is safe by default for every threat model.
|
|
97
120
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
* **Arithmetic:** Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round, Floor, Ceil
|
|
101
|
-
* **Trigonometry:** Sin, Cos, Tan, Arcsin, Arccos, Arctan, Arctan2, Cot, Sec, Csc (+ inverses), Sinh, Cosh, Tanh, Coth, Sech, Csch (+ inverses), Hypot, Sinc
|
|
102
|
-
* **Logarithms:** Log (base 10, or base b), Log2/Lb, Log10/Lg, Ln (natural log), LogOnePlus, Exp
|
|
103
|
-
* **Comparison:** Equal, StrictEqual, IdenticallyEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual, Congruent
|
|
104
|
-
* **Logic & Sets:** Any, All, Not, And, Or, Xor, Nand, Nor, Implies, Equivalent, In/Element, NotIn/NotElement, ContainsAnyOf, ContainsAllOf, ContainsNoneOf, bare `True`/`False` literals, Union, Intersection, SetMinus, SymmetricDifference (over arrays - no dedicated Set type)
|
|
105
|
-
* **Statistics:** Average/Mean, Max, Min (both list and variadic forms), Median, Mode, Variance, StandardDeviation, PopulationVariance, PopulationStandardDeviation, Quartiles, InterquartileRange, Covariance, Correlation, Length/Count
|
|
106
|
-
* **Functional Programming:** Map/StrictMap, Reduce, Filter, Product (all also accept CortexJS calling conventions, including `Function` lambdas)
|
|
107
|
-
* **Arrays:** Array/List creation, GenerateRange, Range, AtIndex, At, Slice, Appended/Append, First, Second, Third, Last, Rest, Most, Reverse, Sort, Unique, Dedup, Join, Zip, IsEmpty, CumulativeSum, CumulativeProduct, Take, Drop, TakeWhile, DropWhile, Contains, IndexOf, IndexWhere, Find, CountIf, Position, RotateLeft, RotateRight, MaxBy, MinBy, ArgMax, ArgMin, Ordering, FlatMap, Scan, Differences, Fold, Insert, DeleteAt, ReplaceAt, Partition, Chunk, GroupBy, ChunkBy, Tally
|
|
108
|
-
* **Control Flow:** If statements (Python pair form and CortexJS flat form), Switch/StrictSwitch (value-equality case dispatch), Which (CortexJS flat condition/value chain), Constants definition
|
|
109
|
-
* **Type Conversion:** Int, Float, Str, IsDefined
|
|
110
|
-
* **Strings:** String, StringJoin, ToUpperCase, ToLowerCase, CaseFold, Trim, TrimStart, TrimEnd, StringSplit, StringReplace, StringCompare, StringRepeat, PadStart, PadEnd, Characters/GraphemeClusters, Utf8, Utf16, UnicodeScalars, StringFrom, IntegerString, DigitsFrom, NumberFrom
|
|
111
|
-
* **Pattern Matching (requires the optional `regex` extra, `pip install mathjson-solver[regex]`):** RegExp, IsMatch, StringMatch, StringMatchAll — backed by [RE2](https://github.com/google/re2) rather than Python's `re`, for a hard guarantee against catastrophic backtracking (no backreferences/lookaround, as a deliberate trade-off for that guarantee)
|
|
112
|
-
* **Date/Time:** Strptime, Strftime, Today, Now, TimeDelta functions (Weeks, Days, Hours, Minutes)
|
|
113
|
-
* **Number Theory:** Chop, Mod, Clamp, GCD, LCM, Factorial, Binomial, IsPrime, Erf, Erfc, Rational, Numerator, Denominator, MachineEpsilon, CatalanConstant, EulerGamma
|
|
114
|
-
* **Integration (requires the optional `integration` extra, `pip install mathjson-solver[integration]`):** TrapezoidalIntegrate. Also in this group but with no extra dependency: Interp, FindIntervalIndex, Variable references
|
|
115
|
-
* **Advanced:** HasMatchingSublist for pattern matching
|
|
116
|
-
* **Constants:** Pi, Degrees, ExponentialE, GoldenRatio
|
|
117
|
-
|
|
118
|
-
[View complete documentation with examples →](https://github.com/LongenesisLtd/mathjson-solver/blob/main/docs/README.md)
|
|
121
|
+
A blacklisted name that isn't an actual construct (a typo, for instance) is silently ignored rather than rejected — `blacklist` isn't validated against the list of implemented constructs.
|
|
119
122
|
|
|
120
123
|
## Error Handling
|
|
121
124
|
|
|
@@ -139,13 +142,28 @@ except MathJSONException as e:
|
|
|
139
142
|
print(f"Unsupported operation: {e}")
|
|
140
143
|
```
|
|
141
144
|
|
|
142
|
-
##
|
|
145
|
+
## Migrating from 1.x
|
|
143
146
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
147
|
+
> **Version 2 introduced a breaking change:** `Log` is now log base 10 instead of natural log (see [CHANGELOG.md](CHANGELOG.md)). Bugfix releases for the 1.x line continue on the [`1.x` branch](https://github.com/LongenesisLtd/mathjson-solver/tree/1.x).
|
|
148
|
+
|
|
149
|
+
Version 2.0.0's only breaking change is `Log`: pre-2.0.0 it was always natural log, `["Log", x]` == `math.log(x)`. From 2.0.0 on it matches [CortexJS](https://cortexjs.io/compute-engine/) — `["Log", x]` is log base 10, `["Log", x, b]` is log base `b` — and natural log moved to `Ln`.
|
|
150
|
+
|
|
151
|
+
If you have existing expressions built for 1.x and don't want to hand-edit every `Log` node just to pick up functions added in 2.x (`Product`, the CortexJS forms of `If`/`Map`/`Filter`/`Reduce`, the new aliases, etc.), pass `legacy_v1=True` when creating the solver. It rewrites every `["Log", x]` to `["Ln", x]` before evaluating, so old expressions keep producing the same results without modification:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
solver = create_solver(parameters, legacy_v1=True)
|
|
155
|
+
solver(["Log", 8]) # 2.0794... (natural log, matching pre-2.0.0 behavior)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
You can also run the rewrite yourself and inspect or store the translated expression:
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
from mathjson_solver import translate_v1_mathjson
|
|
162
|
+
|
|
163
|
+
translate_v1_mathjson(["Add", ["Log", 8], 1]) # ["Add", ["Ln", 8], 1]
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`legacy_v1=True` only affects `Log`. Every other 1.x expression already evaluates identically on 2.x without any translation.
|
|
149
167
|
|
|
150
168
|
## Testing
|
|
151
169
|
|
|
@@ -178,6 +196,8 @@ We welcome contributions! Please feel free to:
|
|
|
178
196
|
|
|
179
197
|
We also created [`londec`](https://pypi.org/project/londec/) — evaluate tree-structured conditions against an ordered history of events. It uses mathjson-solver internally.
|
|
180
198
|
|
|
199
|
+
[`mathjson-tree-builder`](https://www.npmjs.com/package/mathjson-tree-builder) is a fully compatible frontend counterpart — a framework-agnostic, click-to-build editor for authoring MathJSON expressions in the browser.
|
|
200
|
+
|
|
181
201
|
## License
|
|
182
202
|
|
|
183
203
|
[View license information](https://github.com/LongenesisLtd/mathjson-solver/blob/main/LICENSE)
|