mathjson-solver 2.2.0__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.3.0/CHANGELOG.md +137 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/PKG-INFO +76 -46
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/README.md +68 -44
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/SECURITY.md +3 -2
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/docs/README.md +830 -20
- mathjson_solver-2.3.0/pyproject.toml +61 -0
- 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_collections.py +156 -0
- mathjson_solver-2.3.0/tests/test_cortexjs_combinatorics.py +101 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_cortexjs_compat.py +22 -1
- mathjson_solver-2.3.0/tests/test_cortexjs_constants_relations.py +47 -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.3.0/tests/test_cortexjs_sets.py +97 -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.3.0/tests/test_cortexjs_strings.py +172 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_cortexjs_tier3.py +84 -0
- mathjson_solver-2.3.0/tests/test_scope_isolation.py +123 -0
- mathjson_solver-2.2.0/CHANGELOG.md +0 -70
- mathjson_solver-2.2.0/pyproject.toml +0 -41
- mathjson_solver-2.2.0/src/mathjson_solver/__main__.py +0 -1754
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/.gitignore +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/CODE_OF_CONDUCT.md +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/CONTRIBUTING.md +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/LICENSE +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/docs/integration-test-cases.md +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/src/mathjson_solver/__init__.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_TrapezoidalIntegratel.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_atindex.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_cumulative.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_datetime.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_equal.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_exceptions.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_extract_variables.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_findinterval.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_gail_model.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_interpolate.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_legacy_compat.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_range.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_reduce_simple.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_scalars.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_sets.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_simple_cases.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_slice.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_state_tuples_reduce.py +0 -0
- {mathjson_solver-2.2.0 → mathjson_solver-2.3.0}/tests/test_with_pytest.py +0 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
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
|
+
|
|
44
|
+
## [2.2.1] - 2026-09-14
|
|
45
|
+
|
|
46
|
+
### Fixed
|
|
47
|
+
|
|
48
|
+
- **`Which`** was aliased to `Switch` (value-equality dispatch: `["Switch", expr, default, [case, val], ...]`) instead of implementing CortexJS's actual flat condition/value chain, `["Which", cond1, val1, cond2, val2, ...]`. It now evaluates each `cond` in order and returns the `val` paired with the first truthy one, or `None` (CortexJS `Nothing`) if none match. If you were relying on the old `Switch`-shaped behavior, use `["Switch", ...]` directly.
|
|
49
|
+
- **`requires-python`** claimed `>=3.6`; the codebase has required Python 3.10 since before this release (a bare `X | Y` union type annotation with no `from __future__ import annotations`, which fails at import time on older versions), and CI has only ever tested 3.10/3.12. Corrected to `>=3.10`. The README's "Requirements: Python 3.7+" had the same problem and is corrected too.
|
|
50
|
+
- **`numpy`** is now declared as a proper optional extra (`integration = ["numpy"]` in `pyproject.toml`, `pip install mathjson-solver[integration]`) instead of an undeclared `try/except ImportError` dependency, and is installed in CI so `TrapezoidalIntegrate`'s tests run there.
|
|
51
|
+
|
|
52
|
+
### Added
|
|
53
|
+
|
|
54
|
+
- **Bare `True`/`False` boolean literals** - CortexJS's boolean symbols (native JSON `true`/`false` already worked). Reserved: a solver parameter or local variable of the same name can't shadow them.
|
|
55
|
+
- **CortexJS collection functions**, all operating on `Array` and, where they take a function/predicate argument, accepting both the call-template and `Function`-lambda conventions already used by `Map`/`Filter`/`Reduce`:
|
|
56
|
+
- Slicing: `Take`, `Drop`, `TakeWhile`, `DropWhile`
|
|
57
|
+
- Searching: `Contains`, `IndexOf`, `IndexWhere`, `Find`, `CountIf`, `Position`
|
|
58
|
+
- Reordering: `RotateLeft`, `RotateRight`, `MaxBy`, `MinBy`, `ArgMax`, `ArgMin`, `Ordering`
|
|
59
|
+
- Transforming: `FlatMap`, `Scan`, `Differences`, `Fold` (function-first `Reduce`), `Dedup` (consecutive-only, unlike `Unique`)
|
|
60
|
+
- Editing: `Append` (alias for the existing `Appended`), `Insert`, `DeleteAt`, `ReplaceAt`
|
|
61
|
+
- Grouping: `Partition` (fixed chunk size), `Chunk` (fixed group count), `GroupBy`, `ChunkBy`, `Tally`
|
|
62
|
+
- **Basic set algebra** over `Array`: `Union` and `Intersection` (variadic, deduplicated, order-preserving), `SetMinus`, `SymmetricDifference`, and `Element`/`NotElement` (CortexJS's names for the existing `In`/`Not_in`).
|
|
63
|
+
- **`Second`, `Third`**: fixed-position element access alongside `First`/`Last`.
|
|
64
|
+
- **New constants:** `MachineEpsilon`, `CatalanConstant`, `EulerGamma`.
|
|
65
|
+
- **New relations:** `IdenticallyEqual` (like `StrictEqual`, but also requires the same Python type - `1` and `1.0` are `StrictEqual` but not `IdenticallyEqual`), `Congruent` (`["Congruent", a, b, modulus]`, i.e. `a ≡ b (mod modulus)`).
|
|
66
|
+
- **`Rational`, `Numerator`, `Denominator`.** `Rational(n, d)` evaluates to `n / d` (this solver has no rational-number type carried through arithmetic). `Numerator`/`Denominator` read a `Rational` node's declared `n`/`d` exactly when passed one directly; otherwise they reconstruct an approximate fraction from the numeric value.
|
|
67
|
+
- **More statistics:** `Mode`, `PopulationVariance`, `PopulationStandardDeviation`, `Quartiles`, `InterquartileRange`, `Covariance`, `Correlation`.
|
|
68
|
+
- **String functions:** `String`, `StringJoin`, `ToUpperCase`, `ToLowerCase`, `CaseFold`, `Trim`/`TrimStart`/`TrimEnd`, `StringSplit`, `StringReplace` (literal substring, not pattern-based), `StringCompare`, `Characters`/`GraphemeClusters` (Unicode code points, not full grapheme clusters), `Utf8`/`Utf16`/`UnicodeScalars` and their inverse `StringFrom`, `IntegerString`/`DigitsFrom` (base 2-36), `NumberFrom`. `StringRepeat`/`PadStart`/`PadEnd` are capped at 100,000 characters. `Join` stays `Array`-only (unlike CortexJS's polymorphic `Join`); `StringJoin` is the dedicated string name.
|
|
69
|
+
- **Pattern matching: `RegExp`, `IsMatch`, `StringMatch`, `StringMatchAll`**, backed by [RE2](https://github.com/google/re2) rather than Python's `re`, for a hard guarantee against catastrophic backtracking (ReDoS) - at the cost of no backreferences or lookahead/lookbehind. Requires the new `regex` extra: `pip install mathjson-solver[regex]` (installs [`google-re2`](https://pypi.org/project/google-re2/)). `RegExp` compiles a pattern (optional `i`/`m`/`s` flags) into a reusable value; `IsMatch`/`StringMatch`/`StringMatchAll` accept that value or a bare pattern string. `StringMatch`/`StringMatchAll` return `["Array", matched_text, start, end, ["Array", group, ...]]` per match (1-indexed `start`, exclusive `end`, matching this solver's other index conventions).
|
|
70
|
+
|
|
71
|
+
Not included: `Delimiter`, `Spacing`, `Annotated`, `Text`, `BaseForm` (LaTeX-rendering hints, not applicable to a headless evaluator); `Set`, `Tuple`, `Dictionary`, and unbounded-iteration collections (`Cycle`, `Iterate`, arbitrary-size `Repeat`/`Linspace`/`Tabulate`); domain-membership sets (`RealNumbers`, `Integers`, etc.).
|
|
72
|
+
|
|
73
|
+
[2.2.1]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.2.0...v2.2.1
|
|
74
|
+
|
|
75
|
+
## [2.2.0] - 2026-09-08
|
|
76
|
+
|
|
77
|
+
### Added
|
|
78
|
+
|
|
79
|
+
- **Migration helper for 1.x users:** `translate_v1_mathjson(expr)` rewrites the one breaking change from 2.0.0 (`["Log", x]`, previously natural log) to its 2.x equivalent (`["Ln", x]`), leaving everything else untouched. `create_solver(parameters, legacy_v1=True)` applies this automatically, so existing 1.x expressions keep evaluating to the same results on 2.x without hand-editing, while still gaining access to functions added in 2.x.
|
|
80
|
+
|
|
81
|
+
[2.2.0]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.1.1...v2.2.0
|
|
82
|
+
|
|
83
|
+
## [2.1.1] - 2026-08-19
|
|
84
|
+
|
|
85
|
+
### Fixed
|
|
86
|
+
|
|
87
|
+
- Fixed packaging: the sdist now only includes the intended package, tests, docs, and metadata files.
|
|
88
|
+
|
|
89
|
+
[2.1.1]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.1.0...v2.1.1
|
|
90
|
+
|
|
91
|
+
## [2.1.0] - 2026-08-19
|
|
92
|
+
|
|
93
|
+
Continues the CortexJS compatibility pass: `If`, `Map`, `Filter`, and `Reduce` now also accept CortexJS calling conventions, alongside the existing Python-specific forms.
|
|
94
|
+
|
|
95
|
+
### Fixed
|
|
96
|
+
|
|
97
|
+
- **Correctness fix:** a locally-bound name (a `Constants` binding, a `Reduce` accumulator/current/index variable, or a `Function` parameter, see below) now correctly shadows a top-level solver parameter of the same name, instead of the global value silently winning. Previously `create_solver({"x": 5})` evaluating `["Constants", ["x", 100], ["Add", "x", 1]]` returned `6` instead of `101`. If you were unknowingly relying on the old (backwards) precedence, this will change your result.
|
|
98
|
+
|
|
99
|
+
### Added
|
|
100
|
+
|
|
101
|
+
- **`Function`**: now a real CortexJS-style lambda, `["Function", body, param1, param2, ...]`. With no parameter names, `body` can reference its arguments via the anonymous placeholders `"_"` (first argument only) and `"_1"`, `"_2"`, ... Meant to be passed as the function argument to `Map`, `Filter`, and `Reduce`; evaluated on its own it returns unevaluated. (Previously a non-functional stub that always returned `0`.)
|
|
102
|
+
- **`If`**: now also accepts the CortexJS flat form, `["If", cond, then]` / `["If", cond, then, else]`, including the no-else form (returns `None`/CortexJS `Nothing` when the condition is false). The existing Python pair form, `["If", [cond, val], ..., else_val]`, is unchanged and detected automatically. (Note: a Python-form condition that is a bare parameter reference, e.g. `["If", ["my_flag", "yes"], "no"]`, is still correctly disambiguated — but wrapping such conditions in `IsTrue`/`IsFalse` remains the clearer style.)
|
|
103
|
+
- **`Map` / `StrictMap` / `Filter`**: the function argument can now be a `["Function", ...]` expression (see above), in addition to the existing call-template form (e.g. `["Square"]`).
|
|
104
|
+
- **`Reduce`**: now also accepts the CortexJS form, `["Reduce", collection, fn]` / `["Reduce", collection, fn, initial]`, where `fn` is applied as `fn(accumulator, current_item)` (call-template or `Function` form). Without an initial value, the first element seeds the accumulator. The existing 6-argument Python form (with named accumulator/current/index variables) is unchanged and detected automatically via argument count.
|
|
105
|
+
- **`Product`**: `["Product", array]` multiplies together the numeric elements of `array`.
|
|
106
|
+
|
|
107
|
+
[2.1.0]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.0.0...v2.1.0
|
|
108
|
+
|
|
109
|
+
## [2.0.0] - 2026-08-19
|
|
110
|
+
|
|
111
|
+
Steers the solver back towards greater compatibility with [CortexJS MathJSON](https://cortexjs.io/compute-engine/), adding aliases and constructs that were previously CortexJS-only.
|
|
112
|
+
|
|
113
|
+
### Changed
|
|
114
|
+
|
|
115
|
+
- **BREAKING:** `Log` now matches CortexJS: `["Log", x]` is log base 10, and `["Log", x, b]` is log base `b`. Previously `Log` was natural log; use `Ln` for that.
|
|
116
|
+
- `Max` and `Min` now also accept a variadic (CortexJS) form, e.g. `["Max", 5, 2, -1]`, in addition to the existing single-array form.
|
|
117
|
+
|
|
118
|
+
### Added
|
|
119
|
+
|
|
120
|
+
- CortexJS aliases: `Lb` (`Log2`), `Lg` (`Log10`), `List` (`Array`), `Mean` (`Average`), `Count` (`Length`), `Which` (`Switch`).
|
|
121
|
+
- New math functions: `LogOnePlus`, `Chop`, `Mod`, `Clamp`, `GCD`, `LCM`, `Factorial`, `Binomial`, `IsPrime`, `Erf`, `Erfc`.
|
|
122
|
+
- New logic functions: `Xor`, `Nand`, `Nor`, `Implies`, `Equivalent`.
|
|
123
|
+
- New trigonometric functions: `Arctan2`, `Cot`, `Sec`, `Csc`, `Arccot`, `Arcsec`, `Arccsc`, `Sinh`, `Cosh`, `Tanh`, `Coth`, `Sech`, `Csch`, `Arsinh`, `Arcosh`, `Artanh`, `Arcoth`, `Arsech`, `Arcsch`, `Hypot`, `Sinc`.
|
|
124
|
+
- New constants: `Degrees`, `ExponentialE`, `GoldenRatio`.
|
|
125
|
+
- New statistics: `Variance`, `StandardDeviation`.
|
|
126
|
+
- New array/collection functions: `First`, `Last`, `Rest`, `Most`, `Reverse`, `Sort`, `IsEmpty`, `Range` (CortexJS-compatible, distinct from `GenerateRange`), `Join`, `Unique`, `Zip`, `At` (1-indexed, distinct from `AtIndex`).
|
|
127
|
+
|
|
128
|
+
[2.0.0]: https://github.com/LongenesisLtd/mathjson-solver/compare/v1.20.2...v2.0.0
|
|
129
|
+
|
|
130
|
+
## [1.20.2] - 2026-08-18
|
|
131
|
+
|
|
132
|
+
### Fixed
|
|
133
|
+
|
|
134
|
+
- Fix `extract_variables` for Constants (thanks [@nkimdwave](https://github.com/nkimdwave)!)
|
|
135
|
+
- Add missing functions to constructs in `extract_variables` (thanks [@nkimdwave](https://github.com/nkimdwave)!)
|
|
136
|
+
|
|
137
|
+
[1.20.2]: https://github.com/LongenesisLtd/mathjson-solver/compare/461bc00...v1.20.2
|
|
@@ -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
|
|
@@ -9,42 +9,66 @@ License-Expression: MIT
|
|
|
9
9
|
License-File: LICENSE
|
|
10
10
|
Classifier: Operating System :: OS Independent
|
|
11
11
|
Classifier: Programming Language :: Python :: 3
|
|
12
|
-
Requires-Python: >=3.
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Provides-Extra: integration
|
|
14
|
+
Requires-Dist: numpy; extra == 'integration'
|
|
15
|
+
Provides-Extra: regex
|
|
16
|
+
Requires-Dist: google-re2; extra == 'regex'
|
|
17
|
+
Provides-Extra: special-functions
|
|
18
|
+
Requires-Dist: scipy; extra == 'special-functions'
|
|
13
19
|
Description-Content-Type: text/markdown
|
|
14
20
|
|
|
15
21
|
# MathJSON Solver
|
|
16
22
|
|
|
17
23
|
[](https://pypi.org/project/mathjson-solver/)
|
|
18
24
|
[](https://pepy.tech/projects/mathjson-solver)
|
|
19
|
-
[) 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/)
|
|
22
26
|
|
|
23
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.
|
|
24
28
|
|
|
25
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.
|
|
26
30
|
|
|
31
|
+
Coming from 1.x? Version 2 changed `Log`'s meaning — see [Migrating from 1.x](#migrating-from-1x).
|
|
32
|
+
|
|
27
33
|
## Table of Contents
|
|
34
|
+
- [Use Cases](#use-cases)
|
|
28
35
|
- [Installation](#installation)
|
|
29
36
|
- [Quick Start](#quick-start)
|
|
30
|
-
- [Migrating from 1.x](#migrating-from-1x)
|
|
31
37
|
- [Supported Operations](#supported-operations)
|
|
38
|
+
- [Restricting Available Functions](#restricting-available-functions)
|
|
32
39
|
- [Error Handling](#error-handling)
|
|
33
|
-
- [
|
|
40
|
+
- [Migrating from 1.x](#migrating-from-1x)
|
|
34
41
|
- [Testing](#testing)
|
|
35
42
|
- [Community](#community)
|
|
36
43
|
- [Contributing](#contributing)
|
|
37
44
|
- [Related Projects](#related-projects)
|
|
38
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
|
+
|
|
39
58
|
## Installation
|
|
40
59
|
|
|
41
60
|
```bash
|
|
42
61
|
pip install mathjson-solver
|
|
43
62
|
```
|
|
44
63
|
|
|
45
|
-
**Requirements:** Python 3.
|
|
64
|
+
**Requirements:** Python 3.10+
|
|
65
|
+
|
|
66
|
+
**Optional:**
|
|
67
|
+
- `pip install mathjson-solver[integration]` (installs numpy; only required for `TrapezoidalIntegrate`)
|
|
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`)
|
|
46
70
|
|
|
47
|
-
|
|
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.
|
|
48
72
|
|
|
49
73
|
## Quick Start
|
|
50
74
|
|
|
@@ -84,48 +108,37 @@ solver(["Map", ["Array", 1, 2, 3, 4], ["Function", ["Multiply", "_", 2]]]) # [2
|
|
|
84
108
|
solver(["Reduce", ["Array", 1, 2, 3, 4], ["Add"]]) # 10
|
|
85
109
|
```
|
|
86
110
|
|
|
87
|
-
##
|
|
88
|
-
|
|
89
|
-
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
|
|
90
112
|
|
|
91
|
-
|
|
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.
|
|
92
114
|
|
|
93
115
|
```python
|
|
94
|
-
|
|
95
|
-
|
|
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)
|
|
96
121
|
```
|
|
97
122
|
|
|
98
|
-
|
|
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:
|
|
99
130
|
|
|
100
131
|
```python
|
|
101
|
-
|
|
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.
|
|
102
135
|
|
|
103
|
-
|
|
136
|
+
solver(["Add", 1, 2]) # unaffected constructs still work: 3.0
|
|
104
137
|
```
|
|
105
138
|
|
|
106
|
-
`
|
|
107
|
-
|
|
108
|
-
## 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.
|
|
109
140
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
* **Arithmetic:** Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round, Floor, Ceil
|
|
113
|
-
* **Trigonometry:** Sin, Cos, Tan, Arcsin, Arccos, Arctan, Arctan2, Cot, Sec, Csc (+ inverses), Sinh, Cosh, Tanh, Coth, Sech, Csch (+ inverses), Hypot, Sinc
|
|
114
|
-
* **Logarithms:** Log (base 10, or base b), Log2/Lb, Log10/Lg, Ln (natural log), LogOnePlus, Exp
|
|
115
|
-
* **Comparison:** Equal, StrictEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual
|
|
116
|
-
* **Logic & Sets:** Any, All, Not, And, Or, Xor, Nand, Nor, Implies, Equivalent, In, NotIn, ContainsAnyOf, ContainsAllOf, ContainsNoneOf
|
|
117
|
-
* **Statistics:** Average/Mean, Max, Min (both list and variadic forms), Median, Variance, StandardDeviation, Length/Count
|
|
118
|
-
* **Functional Programming:** Map/StrictMap, Reduce, Filter, Product (all also accept CortexJS calling conventions, including `Function` lambdas)
|
|
119
|
-
* **Arrays:** Array/List creation, GenerateRange, Range, AtIndex, At, Slice, Appended, First, Last, Rest, Most, Reverse, Sort, Unique, Join, Zip, IsEmpty, CumulativeSum, CumulativeProduct
|
|
120
|
-
* **Control Flow:** If statements (Python pair form and CortexJS flat form), Switch-Case/Which, Constants definition
|
|
121
|
-
* **Type Conversion:** Int, Float, Str, IsDefined
|
|
122
|
-
* **Date/Time:** Strptime, Strftime, Today, Now, TimeDelta functions (Weeks, Days, Hours, Minutes)
|
|
123
|
-
* **Number Theory:** Chop, Mod, Clamp, GCD, LCM, Factorial, Binomial, IsPrime, Erf, Erfc
|
|
124
|
-
* **Integration:** TrapezoidalIntegrate (requires numpy), Interp, FindIntervalIndex, Variable references
|
|
125
|
-
* **Advanced:** HasMatchingSublist for pattern matching
|
|
126
|
-
* **Constants:** Pi, Degrees, ExponentialE, GoldenRatio
|
|
127
|
-
|
|
128
|
-
[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.
|
|
129
142
|
|
|
130
143
|
## Error Handling
|
|
131
144
|
|
|
@@ -149,13 +162,28 @@ except MathJSONException as e:
|
|
|
149
162
|
print(f"Unsupported operation: {e}")
|
|
150
163
|
```
|
|
151
164
|
|
|
152
|
-
##
|
|
165
|
+
## Migrating from 1.x
|
|
153
166
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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.
|
|
159
187
|
|
|
160
188
|
## Testing
|
|
161
189
|
|
|
@@ -188,6 +216,8 @@ We welcome contributions! Please feel free to:
|
|
|
188
216
|
|
|
189
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.
|
|
190
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
|
+
|
|
191
221
|
## License
|
|
192
222
|
|
|
193
223
|
[View license information](https://github.com/LongenesisLtd/mathjson-solver/blob/main/LICENSE)
|
|
@@ -2,35 +2,53 @@
|
|
|
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
|
|
28
41
|
pip install mathjson-solver
|
|
29
42
|
```
|
|
30
43
|
|
|
31
|
-
**Requirements:** Python 3.
|
|
44
|
+
**Requirements:** Python 3.10+
|
|
45
|
+
|
|
46
|
+
**Optional:**
|
|
47
|
+
- `pip install mathjson-solver[integration]` (installs numpy; only required for `TrapezoidalIntegrate`)
|
|
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`)
|
|
32
50
|
|
|
33
|
-
|
|
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.
|
|
34
52
|
|
|
35
53
|
## Quick Start
|
|
36
54
|
|
|
@@ -70,48 +88,37 @@ solver(["Map", ["Array", 1, 2, 3, 4], ["Function", ["Multiply", "_", 2]]]) # [2
|
|
|
70
88
|
solver(["Reduce", ["Array", 1, 2, 3, 4], ["Add"]]) # 10
|
|
71
89
|
```
|
|
72
90
|
|
|
73
|
-
##
|
|
74
|
-
|
|
75
|
-
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
|
|
76
92
|
|
|
77
|
-
|
|
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.
|
|
78
94
|
|
|
79
95
|
```python
|
|
80
|
-
|
|
81
|
-
|
|
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)
|
|
82
101
|
```
|
|
83
102
|
|
|
84
|
-
|
|
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:
|
|
85
110
|
|
|
86
111
|
```python
|
|
87
|
-
|
|
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.
|
|
88
115
|
|
|
89
|
-
|
|
116
|
+
solver(["Add", 1, 2]) # unaffected constructs still work: 3.0
|
|
90
117
|
```
|
|
91
118
|
|
|
92
|
-
`
|
|
93
|
-
|
|
94
|
-
## 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.
|
|
95
120
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
* **Arithmetic:** Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round, Floor, Ceil
|
|
99
|
-
* **Trigonometry:** Sin, Cos, Tan, Arcsin, Arccos, Arctan, Arctan2, Cot, Sec, Csc (+ inverses), Sinh, Cosh, Tanh, Coth, Sech, Csch (+ inverses), Hypot, Sinc
|
|
100
|
-
* **Logarithms:** Log (base 10, or base b), Log2/Lb, Log10/Lg, Ln (natural log), LogOnePlus, Exp
|
|
101
|
-
* **Comparison:** Equal, StrictEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual
|
|
102
|
-
* **Logic & Sets:** Any, All, Not, And, Or, Xor, Nand, Nor, Implies, Equivalent, In, NotIn, ContainsAnyOf, ContainsAllOf, ContainsNoneOf
|
|
103
|
-
* **Statistics:** Average/Mean, Max, Min (both list and variadic forms), Median, Variance, StandardDeviation, Length/Count
|
|
104
|
-
* **Functional Programming:** Map/StrictMap, Reduce, Filter, Product (all also accept CortexJS calling conventions, including `Function` lambdas)
|
|
105
|
-
* **Arrays:** Array/List creation, GenerateRange, Range, AtIndex, At, Slice, Appended, First, Last, Rest, Most, Reverse, Sort, Unique, Join, Zip, IsEmpty, CumulativeSum, CumulativeProduct
|
|
106
|
-
* **Control Flow:** If statements (Python pair form and CortexJS flat form), Switch-Case/Which, Constants definition
|
|
107
|
-
* **Type Conversion:** Int, Float, Str, IsDefined
|
|
108
|
-
* **Date/Time:** Strptime, Strftime, Today, Now, TimeDelta functions (Weeks, Days, Hours, Minutes)
|
|
109
|
-
* **Number Theory:** Chop, Mod, Clamp, GCD, LCM, Factorial, Binomial, IsPrime, Erf, Erfc
|
|
110
|
-
* **Integration:** TrapezoidalIntegrate (requires numpy), Interp, FindIntervalIndex, Variable references
|
|
111
|
-
* **Advanced:** HasMatchingSublist for pattern matching
|
|
112
|
-
* **Constants:** Pi, Degrees, ExponentialE, GoldenRatio
|
|
113
|
-
|
|
114
|
-
[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.
|
|
115
122
|
|
|
116
123
|
## Error Handling
|
|
117
124
|
|
|
@@ -135,13 +142,28 @@ except MathJSONException as e:
|
|
|
135
142
|
print(f"Unsupported operation: {e}")
|
|
136
143
|
```
|
|
137
144
|
|
|
138
|
-
##
|
|
145
|
+
## Migrating from 1.x
|
|
139
146
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
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.
|
|
145
167
|
|
|
146
168
|
## Testing
|
|
147
169
|
|
|
@@ -174,6 +196,8 @@ We welcome contributions! Please feel free to:
|
|
|
174
196
|
|
|
175
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.
|
|
176
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
|
+
|
|
177
201
|
## License
|
|
178
202
|
|
|
179
203
|
[View license information](https://github.com/LongenesisLtd/mathjson-solver/blob/main/LICENSE)
|