mathjson-solver 2.1.1__tar.gz → 2.2.1__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/CHANGELOG.md +101 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/PKG-INFO +49 -13
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/README.md +43 -11
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/docs/README.md +362 -12
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/pyproject.toml +14 -2
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/src/mathjson_solver/__init__.py +1 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/src/mathjson_solver/__main__.py +1148 -4
- mathjson_solver-2.2.1/tests/test_cortexjs_collections.py +156 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_cortexjs_compat.py +22 -1
- mathjson_solver-2.2.1/tests/test_cortexjs_constants_relations.py +47 -0
- mathjson_solver-2.2.1/tests/test_cortexjs_sets.py +68 -0
- mathjson_solver-2.2.1/tests/test_cortexjs_statistics.py +75 -0
- mathjson_solver-2.2.1/tests/test_cortexjs_strings.py +172 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_cortexjs_tier3.py +55 -0
- mathjson_solver-2.2.1/tests/test_legacy_compat.py +73 -0
- mathjson_solver-2.1.1/CHANGELOG.md +0 -62
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/.gitignore +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/CODE_OF_CONDUCT.md +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/CONTRIBUTING.md +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/LICENSE +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/SECURITY.md +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/docs/integration-test-cases.md +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_TrapezoidalIntegratel.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_atindex.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_cumulative.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_datetime.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_equal.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_exceptions.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_extract_variables.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_findinterval.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_gail_model.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_interpolate.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_range.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_reduce_simple.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_scalars.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_sets.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_simple_cases.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_slice.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_state_tuples_reduce.py +0 -0
- {mathjson_solver-2.1.1 → mathjson_solver-2.2.1}/tests/test_with_pytest.py +0 -0
|
@@ -0,0 +1,101 @@
|
|
|
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.2.1] - 2026-09-14
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- **`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.
|
|
13
|
+
- **`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.
|
|
14
|
+
- **`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.
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- **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.
|
|
19
|
+
- **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`:
|
|
20
|
+
- Slicing: `Take`, `Drop`, `TakeWhile`, `DropWhile`
|
|
21
|
+
- Searching: `Contains`, `IndexOf`, `IndexWhere`, `Find`, `CountIf`, `Position`
|
|
22
|
+
- Reordering: `RotateLeft`, `RotateRight`, `MaxBy`, `MinBy`, `ArgMax`, `ArgMin`, `Ordering`
|
|
23
|
+
- Transforming: `FlatMap`, `Scan`, `Differences`, `Fold` (function-first `Reduce`), `Dedup` (consecutive-only, unlike `Unique`)
|
|
24
|
+
- Editing: `Append` (alias for the existing `Appended`), `Insert`, `DeleteAt`, `ReplaceAt`
|
|
25
|
+
- Grouping: `Partition` (fixed chunk size), `Chunk` (fixed group count), `GroupBy`, `ChunkBy`, `Tally`
|
|
26
|
+
- **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`).
|
|
27
|
+
- **`Second`, `Third`**: fixed-position element access alongside `First`/`Last`.
|
|
28
|
+
- **New constants:** `MachineEpsilon`, `CatalanConstant`, `EulerGamma`.
|
|
29
|
+
- **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)`).
|
|
30
|
+
- **`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.
|
|
31
|
+
- **More statistics:** `Mode`, `PopulationVariance`, `PopulationStandardDeviation`, `Quartiles`, `InterquartileRange`, `Covariance`, `Correlation`.
|
|
32
|
+
- **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.
|
|
33
|
+
- **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).
|
|
34
|
+
|
|
35
|
+
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.).
|
|
36
|
+
|
|
37
|
+
[2.2.1]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.2.0...v2.2.1
|
|
38
|
+
|
|
39
|
+
## [2.2.0] - 2026-09-08
|
|
40
|
+
|
|
41
|
+
### Added
|
|
42
|
+
|
|
43
|
+
- **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.
|
|
44
|
+
|
|
45
|
+
[2.2.0]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.1.1...v2.2.0
|
|
46
|
+
|
|
47
|
+
## [2.1.1] - 2026-08-19
|
|
48
|
+
|
|
49
|
+
### Fixed
|
|
50
|
+
|
|
51
|
+
- Fixed packaging: the sdist now only includes the intended package, tests, docs, and metadata files.
|
|
52
|
+
|
|
53
|
+
[2.1.1]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.1.0...v2.1.1
|
|
54
|
+
|
|
55
|
+
## [2.1.0] - 2026-08-19
|
|
56
|
+
|
|
57
|
+
Continues the CortexJS compatibility pass: `If`, `Map`, `Filter`, and `Reduce` now also accept CortexJS calling conventions, alongside the existing Python-specific forms.
|
|
58
|
+
|
|
59
|
+
### Fixed
|
|
60
|
+
|
|
61
|
+
- **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.
|
|
62
|
+
|
|
63
|
+
### Added
|
|
64
|
+
|
|
65
|
+
- **`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`.)
|
|
66
|
+
- **`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.)
|
|
67
|
+
- **`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"]`).
|
|
68
|
+
- **`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.
|
|
69
|
+
- **`Product`**: `["Product", array]` multiplies together the numeric elements of `array`.
|
|
70
|
+
|
|
71
|
+
[2.1.0]: https://github.com/LongenesisLtd/mathjson-solver/compare/v2.0.0...v2.1.0
|
|
72
|
+
|
|
73
|
+
## [2.0.0] - 2026-08-19
|
|
74
|
+
|
|
75
|
+
Steers the solver back towards greater compatibility with [CortexJS MathJSON](https://cortexjs.io/compute-engine/), adding aliases and constructs that were previously CortexJS-only.
|
|
76
|
+
|
|
77
|
+
### Changed
|
|
78
|
+
|
|
79
|
+
- **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.
|
|
80
|
+
- `Max` and `Min` now also accept a variadic (CortexJS) form, e.g. `["Max", 5, 2, -1]`, in addition to the existing single-array form.
|
|
81
|
+
|
|
82
|
+
### Added
|
|
83
|
+
|
|
84
|
+
- CortexJS aliases: `Lb` (`Log2`), `Lg` (`Log10`), `List` (`Array`), `Mean` (`Average`), `Count` (`Length`), `Which` (`Switch`).
|
|
85
|
+
- New math functions: `LogOnePlus`, `Chop`, `Mod`, `Clamp`, `GCD`, `LCM`, `Factorial`, `Binomial`, `IsPrime`, `Erf`, `Erfc`.
|
|
86
|
+
- New logic functions: `Xor`, `Nand`, `Nor`, `Implies`, `Equivalent`.
|
|
87
|
+
- New trigonometric functions: `Arctan2`, `Cot`, `Sec`, `Csc`, `Arccot`, `Arcsec`, `Arccsc`, `Sinh`, `Cosh`, `Tanh`, `Coth`, `Sech`, `Csch`, `Arsinh`, `Arcosh`, `Artanh`, `Arcoth`, `Arsech`, `Arcsch`, `Hypot`, `Sinc`.
|
|
88
|
+
- New constants: `Degrees`, `ExponentialE`, `GoldenRatio`.
|
|
89
|
+
- New statistics: `Variance`, `StandardDeviation`.
|
|
90
|
+
- 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`).
|
|
91
|
+
|
|
92
|
+
[2.0.0]: https://github.com/LongenesisLtd/mathjson-solver/compare/v1.20.2...v2.0.0
|
|
93
|
+
|
|
94
|
+
## [1.20.2] - 2026-08-18
|
|
95
|
+
|
|
96
|
+
### Fixed
|
|
97
|
+
|
|
98
|
+
- Fix `extract_variables` for Constants (thanks [@nkimdwave](https://github.com/nkimdwave)!)
|
|
99
|
+
- Add missing functions to constructs in `extract_variables` (thanks [@nkimdwave](https://github.com/nkimdwave)!)
|
|
100
|
+
|
|
101
|
+
[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.2.1
|
|
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,7 +9,11 @@ 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'
|
|
13
17
|
Description-Content-Type: text/markdown
|
|
14
18
|
|
|
15
19
|
# MathJSON Solver
|
|
@@ -18,7 +22,7 @@ Description-Content-Type: text/markdown
|
|
|
18
22
|
[](https://pepy.tech/projects/mathjson-solver)
|
|
19
23
|
[](https://www.python.org/downloads/)
|
|
20
24
|
|
|
21
|
-
> **Heads up:** Version 2 introduces a
|
|
25
|
+
> **Heads up:** Version 2 introduces a breaking change (see [CHANGELOG.md](CHANGELOG.md)) 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).
|
|
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
|
|
|
@@ -27,12 +31,14 @@ A reliable Python library for numerically evaluating mathematical expressions in
|
|
|
27
31
|
## Table of Contents
|
|
28
32
|
- [Installation](#installation)
|
|
29
33
|
- [Quick Start](#quick-start)
|
|
34
|
+
- [Migrating from 1.x](#migrating-from-1x)
|
|
30
35
|
- [Supported Operations](#supported-operations)
|
|
31
36
|
- [Error Handling](#error-handling)
|
|
32
37
|
- [Use Cases](#use-cases)
|
|
33
38
|
- [Testing](#testing)
|
|
34
39
|
- [Community](#community)
|
|
35
40
|
- [Contributing](#contributing)
|
|
41
|
+
- [Related Projects](#related-projects)
|
|
36
42
|
|
|
37
43
|
## Installation
|
|
38
44
|
|
|
@@ -40,9 +46,11 @@ A reliable Python library for numerically evaluating mathematical expressions in
|
|
|
40
46
|
pip install mathjson-solver
|
|
41
47
|
```
|
|
42
48
|
|
|
43
|
-
**Requirements:** Python 3.
|
|
49
|
+
**Requirements:** Python 3.10+
|
|
44
50
|
|
|
45
|
-
**Optional:**
|
|
51
|
+
**Optional:**
|
|
52
|
+
- `pip install mathjson-solver[integration]` (installs numpy; only required for `TrapezoidalIntegrate`)
|
|
53
|
+
- `pip install mathjson-solver[regex]` (installs [google-re2](https://pypi.org/project/google-re2/); only required for `RegExp`/`IsMatch`/`StringMatch`/`StringMatchAll`)
|
|
46
54
|
|
|
47
55
|
## Quick Start
|
|
48
56
|
|
|
@@ -82,6 +90,27 @@ solver(["Map", ["Array", 1, 2, 3, 4], ["Function", ["Multiply", "_", 2]]]) # [2
|
|
|
82
90
|
solver(["Reduce", ["Array", 1, 2, 3, 4], ["Add"]]) # 10
|
|
83
91
|
```
|
|
84
92
|
|
|
93
|
+
## Migrating from 1.x
|
|
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`.
|
|
96
|
+
|
|
97
|
+
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:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
solver = create_solver(parameters, legacy_v1=True)
|
|
101
|
+
solver(["Log", 8]) # 2.0794... (natural log, matching pre-2.0.0 behavior)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
You can also run the rewrite yourself and inspect or store the translated expression:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from mathjson_solver import translate_v1_mathjson
|
|
108
|
+
|
|
109
|
+
translate_v1_mathjson(["Add", ["Log", 8], 1]) # ["Add", ["Ln", 8], 1]
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`legacy_v1=True` only affects `Log`. Every other 1.x expression already evaluates identically on 2.x without any translation.
|
|
113
|
+
|
|
85
114
|
## Supported Operations
|
|
86
115
|
|
|
87
116
|
The library supports a comprehensive set of mathematical operations:
|
|
@@ -89,16 +118,18 @@ The library supports a comprehensive set of mathematical operations:
|
|
|
89
118
|
* **Arithmetic:** Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round, Floor, Ceil
|
|
90
119
|
* **Trigonometry:** Sin, Cos, Tan, Arcsin, Arccos, Arctan, Arctan2, Cot, Sec, Csc (+ inverses), Sinh, Cosh, Tanh, Coth, Sech, Csch (+ inverses), Hypot, Sinc
|
|
91
120
|
* **Logarithms:** Log (base 10, or base b), Log2/Lb, Log10/Lg, Ln (natural log), LogOnePlus, Exp
|
|
92
|
-
* **Comparison:** Equal, StrictEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual
|
|
93
|
-
* **Logic & Sets:** Any, All, Not, And, Or, Xor, Nand, Nor, Implies, Equivalent, In, NotIn, ContainsAnyOf, ContainsAllOf, ContainsNoneOf
|
|
94
|
-
* **Statistics:** Average/Mean, Max, Min (both list and variadic forms), Median, Variance, StandardDeviation, Length/Count
|
|
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
|
|
95
124
|
* **Functional Programming:** Map/StrictMap, Reduce, Filter, Product (all also accept CortexJS calling conventions, including `Function` lambdas)
|
|
96
|
-
* **Arrays:** Array/List creation, GenerateRange, Range, AtIndex, At, Slice, Appended, First, Last, Rest, Most, Reverse, Sort, Unique, Join, Zip, IsEmpty, CumulativeSum, CumulativeProduct
|
|
97
|
-
* **Control Flow:** If statements (Python pair form and CortexJS flat form), Switch-
|
|
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
|
|
98
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)
|
|
99
130
|
* **Date/Time:** Strptime, Strftime, Today, Now, TimeDelta functions (Weeks, Days, Hours, Minutes)
|
|
100
|
-
* **Number Theory:** Chop, Mod, Clamp, GCD, LCM, Factorial, Binomial, IsPrime, Erf, Erfc
|
|
101
|
-
* **Integration
|
|
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
|
|
102
133
|
* **Advanced:** HasMatchingSublist for pattern matching
|
|
103
134
|
* **Constants:** Pi, Degrees, ExponentialE, GoldenRatio
|
|
104
135
|
|
|
@@ -161,6 +192,9 @@ We welcome contributions! Please feel free to:
|
|
|
161
192
|
- Report bugs or request features via [GitHub Issues](https://github.com/LongenesisLtd/mathjson-solver/issues)
|
|
162
193
|
- Submit pull requests with improvements
|
|
163
194
|
|
|
195
|
+
## Related Projects
|
|
196
|
+
|
|
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.
|
|
164
198
|
|
|
165
199
|
## License
|
|
166
200
|
|
|
@@ -168,7 +202,9 @@ We welcome contributions! Please feel free to:
|
|
|
168
202
|
|
|
169
203
|
## References
|
|
170
204
|
|
|
171
|
-
This
|
|
205
|
+
This library implements the [MathJSON](https://cortexjs.io/mathjson/) format as defined by the [CortexJS Compute Engine](https://cortexjs.io/compute-engine/). Since 2.0.0, mathjson-solver has been steering towards greater compatibility with CortexJS's calling conventions and function set — while remaining an independent Python implementation, not a port or dependency of CortexJS.
|
|
206
|
+
|
|
207
|
+
**Scope:** mathjson-solver targets compatibility with CortexJS's array-form calling conventions and standard function names — not the full [Compute Engine](https://cortexjs.io/compute-engine/), which is a symbolic CAS.
|
|
172
208
|
|
|
173
209
|
---
|
|
174
210
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://pepy.tech/projects/mathjson-solver)
|
|
5
5
|
[](https://www.python.org/downloads/)
|
|
6
6
|
|
|
7
|
-
> **Heads up:** Version 2 introduces a
|
|
7
|
+
> **Heads up:** Version 2 introduces a breaking change (see [CHANGELOG.md](CHANGELOG.md)) 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).
|
|
8
8
|
|
|
9
9
|
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
10
|
|
|
@@ -13,12 +13,14 @@ A reliable Python library for numerically evaluating mathematical expressions in
|
|
|
13
13
|
## Table of Contents
|
|
14
14
|
- [Installation](#installation)
|
|
15
15
|
- [Quick Start](#quick-start)
|
|
16
|
+
- [Migrating from 1.x](#migrating-from-1x)
|
|
16
17
|
- [Supported Operations](#supported-operations)
|
|
17
18
|
- [Error Handling](#error-handling)
|
|
18
19
|
- [Use Cases](#use-cases)
|
|
19
20
|
- [Testing](#testing)
|
|
20
21
|
- [Community](#community)
|
|
21
22
|
- [Contributing](#contributing)
|
|
23
|
+
- [Related Projects](#related-projects)
|
|
22
24
|
|
|
23
25
|
## Installation
|
|
24
26
|
|
|
@@ -26,9 +28,11 @@ A reliable Python library for numerically evaluating mathematical expressions in
|
|
|
26
28
|
pip install mathjson-solver
|
|
27
29
|
```
|
|
28
30
|
|
|
29
|
-
**Requirements:** Python 3.
|
|
31
|
+
**Requirements:** Python 3.10+
|
|
30
32
|
|
|
31
|
-
**Optional:**
|
|
33
|
+
**Optional:**
|
|
34
|
+
- `pip install mathjson-solver[integration]` (installs numpy; only required for `TrapezoidalIntegrate`)
|
|
35
|
+
- `pip install mathjson-solver[regex]` (installs [google-re2](https://pypi.org/project/google-re2/); only required for `RegExp`/`IsMatch`/`StringMatch`/`StringMatchAll`)
|
|
32
36
|
|
|
33
37
|
## Quick Start
|
|
34
38
|
|
|
@@ -68,6 +72,27 @@ solver(["Map", ["Array", 1, 2, 3, 4], ["Function", ["Multiply", "_", 2]]]) # [2
|
|
|
68
72
|
solver(["Reduce", ["Array", 1, 2, 3, 4], ["Add"]]) # 10
|
|
69
73
|
```
|
|
70
74
|
|
|
75
|
+
## Migrating from 1.x
|
|
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`.
|
|
78
|
+
|
|
79
|
+
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:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
solver = create_solver(parameters, legacy_v1=True)
|
|
83
|
+
solver(["Log", 8]) # 2.0794... (natural log, matching pre-2.0.0 behavior)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
You can also run the rewrite yourself and inspect or store the translated expression:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from mathjson_solver import translate_v1_mathjson
|
|
90
|
+
|
|
91
|
+
translate_v1_mathjson(["Add", ["Log", 8], 1]) # ["Add", ["Ln", 8], 1]
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`legacy_v1=True` only affects `Log`. Every other 1.x expression already evaluates identically on 2.x without any translation.
|
|
95
|
+
|
|
71
96
|
## Supported Operations
|
|
72
97
|
|
|
73
98
|
The library supports a comprehensive set of mathematical operations:
|
|
@@ -75,16 +100,18 @@ The library supports a comprehensive set of mathematical operations:
|
|
|
75
100
|
* **Arithmetic:** Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round, Floor, Ceil
|
|
76
101
|
* **Trigonometry:** Sin, Cos, Tan, Arcsin, Arccos, Arctan, Arctan2, Cot, Sec, Csc (+ inverses), Sinh, Cosh, Tanh, Coth, Sech, Csch (+ inverses), Hypot, Sinc
|
|
77
102
|
* **Logarithms:** Log (base 10, or base b), Log2/Lb, Log10/Lg, Ln (natural log), LogOnePlus, Exp
|
|
78
|
-
* **Comparison:** Equal, StrictEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual
|
|
79
|
-
* **Logic & Sets:** Any, All, Not, And, Or, Xor, Nand, Nor, Implies, Equivalent, In, NotIn, ContainsAnyOf, ContainsAllOf, ContainsNoneOf
|
|
80
|
-
* **Statistics:** Average/Mean, Max, Min (both list and variadic forms), Median, Variance, StandardDeviation, Length/Count
|
|
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
|
|
81
106
|
* **Functional Programming:** Map/StrictMap, Reduce, Filter, Product (all also accept CortexJS calling conventions, including `Function` lambdas)
|
|
82
|
-
* **Arrays:** Array/List creation, GenerateRange, Range, AtIndex, At, Slice, Appended, First, Last, Rest, Most, Reverse, Sort, Unique, Join, Zip, IsEmpty, CumulativeSum, CumulativeProduct
|
|
83
|
-
* **Control Flow:** If statements (Python pair form and CortexJS flat form), Switch-
|
|
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
|
|
84
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)
|
|
85
112
|
* **Date/Time:** Strptime, Strftime, Today, Now, TimeDelta functions (Weeks, Days, Hours, Minutes)
|
|
86
|
-
* **Number Theory:** Chop, Mod, Clamp, GCD, LCM, Factorial, Binomial, IsPrime, Erf, Erfc
|
|
87
|
-
* **Integration
|
|
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
|
|
88
115
|
* **Advanced:** HasMatchingSublist for pattern matching
|
|
89
116
|
* **Constants:** Pi, Degrees, ExponentialE, GoldenRatio
|
|
90
117
|
|
|
@@ -147,6 +174,9 @@ We welcome contributions! Please feel free to:
|
|
|
147
174
|
- Report bugs or request features via [GitHub Issues](https://github.com/LongenesisLtd/mathjson-solver/issues)
|
|
148
175
|
- Submit pull requests with improvements
|
|
149
176
|
|
|
177
|
+
## Related Projects
|
|
178
|
+
|
|
179
|
+
We also created [`londec`](https://pypi.org/project/londec/) — evaluate tree-structured conditions against an ordered history of events. It uses mathjson-solver internally.
|
|
150
180
|
|
|
151
181
|
## License
|
|
152
182
|
|
|
@@ -154,7 +184,9 @@ We welcome contributions! Please feel free to:
|
|
|
154
184
|
|
|
155
185
|
## References
|
|
156
186
|
|
|
157
|
-
This
|
|
187
|
+
This library implements the [MathJSON](https://cortexjs.io/mathjson/) format as defined by the [CortexJS Compute Engine](https://cortexjs.io/compute-engine/). Since 2.0.0, mathjson-solver has been steering towards greater compatibility with CortexJS's calling conventions and function set — while remaining an independent Python implementation, not a port or dependency of CortexJS.
|
|
188
|
+
|
|
189
|
+
**Scope:** mathjson-solver targets compatibility with CortexJS's array-form calling conventions and standard function names — not the full [Compute Engine](https://cortexjs.io/compute-engine/), which is a symbolic CAS.
|
|
158
190
|
|
|
159
191
|
---
|
|
160
192
|
|