mathjs-to-func 0.1.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.
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,345 @@
1
+ Metadata-Version: 2.3
2
+ Name: mathjs-to-func
3
+ Version: 0.1.0
4
+ Summary: Compile serialized math.js expression trees into fast, reusable Python callables.
5
+ Keywords: mathjs,compiler,ast,formulas,numpy
6
+ Author: Harold Martin
7
+ Author-email: Harold Martin <harold.martin@gmail.com>
8
+ License: Apache License
9
+ Version 2.0, January 2004
10
+ https://www.apache.org/licenses/
11
+
12
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
13
+
14
+ 1. Definitions.
15
+
16
+ "License" shall mean the terms and conditions for use, reproduction,
17
+ and distribution as defined by Sections 1 through 9 of this document.
18
+
19
+ "Licensor" shall mean the copyright owner or entity authorized by
20
+ the copyright owner that is granting the License.
21
+
22
+ "Legal Entity" shall mean the union of the acting entity and all
23
+ other entities that control, are controlled by, or are under common
24
+ control with that entity. For the purposes of this definition,
25
+ "control" means (i) the power, direct or indirect, to cause the
26
+ direction or management of such entity, whether by contract or
27
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
28
+ outstanding shares, or (iii) beneficial ownership of such entity.
29
+
30
+ "You" (or "Your") shall mean an individual or Legal Entity
31
+ exercising permissions granted by this License.
32
+
33
+ "Source" form shall mean the preferred form for making modifications,
34
+ including but not limited to software source code, documentation
35
+ source, and configuration files.
36
+
37
+ "Object" form shall mean any form resulting from mechanical
38
+ transformation or translation of a Source form, including but
39
+ not limited to compiled object code, generated documentation,
40
+ and conversions to other media types.
41
+
42
+ "Work" shall mean the work of authorship, whether in Source or
43
+ Object form, made available under the License, as indicated by a
44
+ copyright notice that is included in or attached to the work
45
+ (an example is provided in the Appendix below).
46
+
47
+ "Derivative Works" shall mean any work, whether in Source or Object
48
+ form, that is based on (or derived from) the Work and for which the
49
+ editorial revisions, annotations, elaborations, or other modifications
50
+ represent, as a whole, an original work of authorship. For the purposes
51
+ of this License, Derivative Works shall not include works that remain
52
+ separable from, or merely link (or bind by name) to the interfaces of,
53
+ the Work and Derivative Works thereof.
54
+
55
+ "Contribution" shall mean any work of authorship, including
56
+ the original version of the Work and any modifications or additions
57
+ to that Work or Derivative Works thereof, that is intentionally
58
+ submitted to Licensor for inclusion in the Work by the copyright owner
59
+ or by an individual or Legal Entity authorized to submit on behalf of
60
+ the copyright owner. For the purposes of this definition, "submitted"
61
+ means any form of electronic, verbal, or written communication sent
62
+ to the Licensor or its representatives, including but not limited to
63
+ communication on electronic mailing lists, source code control systems,
64
+ and issue tracking systems that are managed by, or on behalf of, the
65
+ Licensor for the purpose of discussing and improving the Work, but
66
+ excluding communication that is conspicuously marked or otherwise
67
+ designated in writing by the copyright owner as "Not a Contribution."
68
+
69
+ "Contributor" shall mean Licensor and any individual or Legal Entity
70
+ on behalf of whom a Contribution has been received by Licensor and
71
+ subsequently incorporated within the Work.
72
+
73
+ 2. Grant of Copyright License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ copyright license to reproduce, prepare Derivative Works of,
77
+ publicly display, publicly perform, sublicense, and distribute the
78
+ Work and such Derivative Works in Source or Object form.
79
+
80
+ 3. Grant of Patent License. Subject to the terms and conditions of
81
+ this License, each Contributor hereby grants to You a perpetual,
82
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
83
+ (except as stated in this section) patent license to make, have made,
84
+ use, offer to sell, sell, import, and otherwise transfer the Work,
85
+ where such license applies only to those patent claims licensable
86
+ by such Contributor that are necessarily infringed by their
87
+ Contribution(s) alone or by combination of their Contribution(s)
88
+ with the Work to which such Contribution(s) was submitted. If You
89
+ institute patent litigation against any entity (including a
90
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
91
+ or a Contribution incorporated within the Work constitutes direct
92
+ or contributory patent infringement, then any patent licenses
93
+ granted to You under this License for that Work shall terminate
94
+ as of the date such litigation is filed.
95
+
96
+ 4. Redistribution. You may reproduce and distribute copies of the
97
+ Work or Derivative Works thereof in any medium, with or without
98
+ modifications, and in Source or Object form, provided that You
99
+ meet the following conditions:
100
+
101
+ (a) You must give any other recipients of the Work or
102
+ Derivative Works a copy of this License; and
103
+
104
+ (b) You must cause any modified files to carry prominent notices
105
+ stating that You changed the files; and
106
+
107
+ (c) You must retain, in the Source form of any Derivative Works
108
+ that You distribute, all copyright, patent, trademark, and
109
+ attribution notices from the Source form of the Work,
110
+ excluding those notices that do not pertain to any part of
111
+ the Derivative Works; and
112
+
113
+ (d) If the Work includes a "NOTICE" text file as part of its
114
+ distribution, then any Derivative Works that You distribute must
115
+ include a readable copy of the attribution notices contained
116
+ within such NOTICE file, excluding those notices that do not
117
+ pertain to any part of the Derivative Works, in at least one
118
+ of the following places: within a NOTICE text file distributed
119
+ as part of the Derivative Works; within the Source form or
120
+ documentation, if provided along with the Derivative Works; or,
121
+ within a display generated by the Derivative Works, if and
122
+ wherever such third-party notices normally appear. The contents
123
+ of the NOTICE file are for informational purposes only and
124
+ do not modify the License. You may add Your own attribution
125
+ notices within Derivative Works that You distribute, alongside
126
+ or as an addendum to the NOTICE text from the Work, provided
127
+ that such additional attribution notices cannot be construed
128
+ as modifying the License.
129
+
130
+ You may add Your own copyright statement to Your modifications and
131
+ may provide additional or different license terms and conditions
132
+ for use, reproduction, or distribution of Your modifications, or
133
+ for any such Derivative Works as a whole, provided Your use,
134
+ reproduction, and distribution of the Work otherwise complies with
135
+ the conditions stated in this License.
136
+
137
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
138
+ any Contribution intentionally submitted for inclusion in the Work
139
+ by You to the Licensor shall be under the terms and conditions of
140
+ this License, without any additional terms or conditions.
141
+ Notwithstanding the above, nothing herein shall supersede or modify
142
+ the terms of any separate license agreement you may have executed
143
+ with Licensor regarding such Contributions.
144
+
145
+ 6. Trademarks. This License does not grant permission to use the trade
146
+ names, trademarks, service marks, or product names of the Licensor,
147
+ except as required for reasonable and customary use in describing the
148
+ origin of the Work and reproducing the content of the NOTICE file.
149
+
150
+ 7. Disclaimer of Warranty. Unless required by applicable law or
151
+ agreed to in writing, Licensor provides the Work (and each
152
+ Contributor provides its Contributions) on an "AS IS" BASIS,
153
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
154
+ implied, including, without limitation, any warranties or conditions
155
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
156
+ PARTICULAR PURPOSE. You are solely responsible for determining the
157
+ appropriateness of using or redistributing the Work and assume any
158
+ risks associated with Your exercise of permissions under this License.
159
+
160
+ 8. Limitation of Liability. In no event and under no legal theory,
161
+ whether in tort (including negligence), contract, or otherwise,
162
+ unless required by applicable law (such as deliberate and grossly
163
+ negligent acts) or agreed to in writing, shall any Contributor be
164
+ liable to You for damages, including any direct, indirect, special,
165
+ incidental, or consequential damages of any character arising as a
166
+ result of this License or out of the use or inability to use the
167
+ Work (including but not limited to damages for loss of goodwill,
168
+ work stoppage, computer failure or malfunction, or any and all
169
+ other commercial damages or losses), even if such Contributor
170
+ has been advised of the possibility of such damages.
171
+
172
+ 9. Accepting Warranty or Additional Liability. While redistributing
173
+ the Work or Derivative Works thereof, You may choose to offer,
174
+ and charge a fee for, acceptance of support, warranty, indemnity,
175
+ or other liability obligations and/or rights consistent with this
176
+ License. However, in accepting such obligations, You may act only
177
+ on Your own behalf and on Your sole responsibility, not on behalf
178
+ of any other Contributor, and only if You agree to indemnify,
179
+ defend, and hold each Contributor harmless for any liability
180
+ incurred by, or claims asserted against, such Contributor by reason
181
+ of your accepting any such warranty or additional liability.
182
+
183
+ END OF TERMS AND CONDITIONS
184
+ Classifier: Development Status :: 4 - Beta
185
+ Classifier: Intended Audience :: Developers
186
+ Classifier: License :: OSI Approved :: Apache Software License
187
+ Classifier: Operating System :: OS Independent
188
+ Classifier: Programming Language :: Python
189
+ Classifier: Programming Language :: Python :: 3
190
+ Classifier: Programming Language :: Python :: 3 :: Only
191
+ Classifier: Programming Language :: Python :: 3.13
192
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
193
+ Classifier: Topic :: Software Development :: Compilers
194
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
195
+ Classifier: Typing :: Typed
196
+ Requires-Dist: numpy>=2.3.4
197
+ Requires-Python: >=3.13
198
+ Project-URL: Bug Reports, https://github.com/hbmartin/mathjs-to-func/issues
199
+ Project-URL: Homepage, https://github.com/hbmartin/mathjs-to-func
200
+ Project-URL: Source, https://github.com/hbmartin/mathjs-to-func
201
+ Description-Content-Type: text/markdown
202
+
203
+ # mathjs-to-func
204
+
205
+ [![PyPI](https://img.shields.io/pypi/v/mathjs-to-func.svg)](https://pypi.org/project/mathjs-to-func/)
206
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
207
+ [![Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black)
208
+ [![ty](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ty/main/assets/badge/v0.json)](https://github.com/astral-sh/ty)
209
+ [![CI](https://github.com/hbmartin/mathjs-to-func/actions/workflows/ci.yml/badge.svg)](https://github.com/hbmartin/mathjs-to-func/actions/workflows/ci.yml)
210
+
211
+ A tiny Python library that compiles serialized [math.js](https://mathjs.org/) expression trees into fast, reusable Python callables. The generated function respects dependency ordering, validates inputs, and mirrors a subset of math.js operators (`+`, `-`, `*`, `/`, `^`, `%`, unary plus/minus) and functions (`min`, `max`, `sum`, `ifnull`).
212
+
213
+ ## Key Features
214
+ - Execute without reparsing or repeatedly walking the JSON graph.
215
+ - Detect dependency cycles and missing identifiers early.
216
+ - Keep execution sandboxed by compiling a controlled Python AST.
217
+ - Work well with scalars or NumPy arrays for vectorised workloads.
218
+
219
+ ## Installation
220
+
221
+ The project uses [uv](https://github.com/astral-sh/uv) for dependency and virtualenv management. From the repository root:
222
+
223
+ ```bash
224
+ uv sync # create the virtual environment declared in uv.lock
225
+ ```
226
+
227
+ All examples below assume commands are wrapped with `uv run ...` to execute inside the managed environment.
228
+
229
+ ## Public API
230
+
231
+ ```python
232
+ from mathjs_to_func import build_evaluator
233
+
234
+ def main():
235
+ mathjs_payload = {
236
+ "expressions": {
237
+ # z = (x + y) / 2
238
+ "sum_xy": {
239
+ "type": "OperatorNode",
240
+ "fn": "add",
241
+ "args": [
242
+ {"type": "SymbolNode", "name": "x"},
243
+ {"type": "SymbolNode", "name": "y"},
244
+ ],
245
+ },
246
+ "mean": {
247
+ "type": "OperatorNode",
248
+ "fn": "divide",
249
+ "args": [
250
+ {"type": "SymbolNode", "name": "sum_xy"},
251
+ {"type": "ConstantNode", "value": "2", "valueType": "number"},
252
+ ],
253
+ },
254
+ },
255
+ "inputs": ["x", "y"],
256
+ "target": "mean",
257
+ }
258
+
259
+ evaluator = build_evaluator(**mathjs_payload, include_source=True)
260
+
261
+ result = evaluator({"x": 10, "y": 6})
262
+ print(result) # -> 8.0
263
+
264
+ # Introspection helpers
265
+ print(evaluator.__mathjs_required_inputs__) # ('x', 'y')
266
+ print(evaluator.__mathjs_evaluation_order__) # ('sum_xy', 'mean')
267
+ print(evaluator.__mathjs_source__) # Generated Python source
268
+ ```
269
+
270
+ ### Parameters
271
+
272
+ `build_evaluator` accepts keyword parameters (or a single `payload` mapping containing the same keys):
273
+
274
+ | Argument | Type | Description |
275
+ |---------------|------------------------------------|-------------|
276
+ | `expressions` | `Mapping[str, Mapping[str, Any]]` | math.js AST JSON keyed by expression id. Each id becomes a local variable in the compiled function. |
277
+ | `inputs` | `Iterable[str]` | Whitelisted identifiers that may be supplied when the function is invoked. |
278
+ | `target` | `str` | Name of the expression whose computed value should be returned. |
279
+ | `include_source` | `bool` (optional) | Attach the generated Python source code as `__mathjs_source__` on the returned callable. |
280
+
281
+ The returned callable always expects a single mapping argument with the provided inputs. It returns the evaluated `target` value and may be reused across invocations.
282
+
283
+ ### Supported math.js nodes
284
+
285
+ | Node | Notes |
286
+ |-------------------------|-------|
287
+ | `ConstantNode` | numeric (`number`), boolean, or `null` literals |
288
+ | `SymbolNode` | validated identifiers; must be alphanumeric/underscore, starting with a letter/underscore |
289
+ | `OperatorNode` | `add`, `subtract`, `multiply`, `divide`, `pow`, `mod`, unary `unaryPlus`, `unaryMinus` |
290
+ | `FunctionNode` | `min`, `max`, `sum`, `ifnull` |
291
+ | `ParenthesisNode` | forwards to the wrapped expression |
292
+ | `ArrayNode` | materialised to Python lists/NumPy arrays |
293
+
294
+ Unknown node types, invalid identifiers, or disallowed functions raise `InvalidNodeError` during compilation.
295
+
296
+ ### Error handling
297
+
298
+ - `ExpressionError`: base class for configuration mistakes.
299
+ - `MissingTargetError`: requested target id does not exist.
300
+ - `UnknownIdentifierError`: an expression references a symbol that is neither an input nor another expression.
301
+ - `CircularDependencyError`: dependency graph contains a cycle.
302
+ - `InvalidNodeError`: AST contains unsupported structures or invalid literals.
303
+ - `InputValidationError`: the compiled function received inputs that are missing, unexpected, or not a mapping.
304
+
305
+ All exceptions provide enough context (`expression` name, offending identifier, cycle list, etc.) to surface descriptive UI errors.
306
+
307
+ ## Implementation Notes
308
+
309
+ 1. **AST translation** – `MathJsAstBuilder` walks the math.js JSON and emits Python `ast.AST` nodes. Identifiers are validated via a strict regex to prevent sneaky names like `__import__`.
310
+ 2. **Dependency graph** – A topological sorter (`graphlib.TopologicalSorter`) runs over expression references to produce a safe evaluation order while catching cycles and missing references upfront.
311
+ 3. **Code generation** – The generated function validates the provided scope, binds required inputs to local variables, evaluates expressions in order, and returns the target. Intermediate values are stored as local variables named after their expression id.
312
+ 4. **Execution sandbox** – The compiled module is executed with a tightly scoped globals dictionary: helper math functions, NumPy, and a few safe built-ins only. There is no ambient `__builtins__` exposure.
313
+ 5. **Helper functions** – math.js functions map onto small Python helpers (`_mj_min`, `_mj_max`, `_mj_sum`, `_mj_ifnull`) that understand scalars and NumPy arrays.
314
+
315
+ ## Testing
316
+
317
+ Run the full suite (178 tests) with:
318
+
319
+ ```bash
320
+ uv run pytest
321
+ ```
322
+
323
+ The tests cover operator translation, helper semantics, dependency validation, error conditions, numpy-friendly behaviour, and public API ergonomics.
324
+
325
+ ## Project Structure
326
+
327
+ ```
328
+ src/mathjs_to_func/
329
+ ├── __init__.py # build_evaluator public API and export list
330
+ ├── ast_builder.py # math.js JSON → Python AST translation
331
+ ├── compiler.py # dependency graph, code generation, compilation
332
+ ├── errors.py # structured exception hierarchy
333
+ ├── helpers.py # runtime helpers for min/max/sum/ifnull
334
+ └── py.typed # PEP 561 marker for type-aware consumers
335
+ ```
336
+
337
+ Additional documentation lives in `docs/api_design.md`, outlining the initial design considerations.
338
+
339
+ ## Limitations & Future Work
340
+
341
+ - Only a subset of math.js functions/operators are implemented today.
342
+ - Units, user-defined functions, and incremental recomputation are intentionally out of scope for this milestone.
343
+ - Arrays are handled via NumPy; if you need bigints, complex numbers, or matrices, the helper layer will require extension.
344
+
345
+ Contributions and bug reports are welcome!
@@ -0,0 +1,143 @@
1
+ # mathjs-to-func
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/mathjs-to-func.svg)](https://pypi.org/project/mathjs-to-func/)
4
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
5
+ [![Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black)
6
+ [![ty](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ty/main/assets/badge/v0.json)](https://github.com/astral-sh/ty)
7
+ [![CI](https://github.com/hbmartin/mathjs-to-func/actions/workflows/ci.yml/badge.svg)](https://github.com/hbmartin/mathjs-to-func/actions/workflows/ci.yml)
8
+
9
+ A tiny Python library that compiles serialized [math.js](https://mathjs.org/) expression trees into fast, reusable Python callables. The generated function respects dependency ordering, validates inputs, and mirrors a subset of math.js operators (`+`, `-`, `*`, `/`, `^`, `%`, unary plus/minus) and functions (`min`, `max`, `sum`, `ifnull`).
10
+
11
+ ## Key Features
12
+ - Execute without reparsing or repeatedly walking the JSON graph.
13
+ - Detect dependency cycles and missing identifiers early.
14
+ - Keep execution sandboxed by compiling a controlled Python AST.
15
+ - Work well with scalars or NumPy arrays for vectorised workloads.
16
+
17
+ ## Installation
18
+
19
+ The project uses [uv](https://github.com/astral-sh/uv) for dependency and virtualenv management. From the repository root:
20
+
21
+ ```bash
22
+ uv sync # create the virtual environment declared in uv.lock
23
+ ```
24
+
25
+ All examples below assume commands are wrapped with `uv run ...` to execute inside the managed environment.
26
+
27
+ ## Public API
28
+
29
+ ```python
30
+ from mathjs_to_func import build_evaluator
31
+
32
+ def main():
33
+ mathjs_payload = {
34
+ "expressions": {
35
+ # z = (x + y) / 2
36
+ "sum_xy": {
37
+ "type": "OperatorNode",
38
+ "fn": "add",
39
+ "args": [
40
+ {"type": "SymbolNode", "name": "x"},
41
+ {"type": "SymbolNode", "name": "y"},
42
+ ],
43
+ },
44
+ "mean": {
45
+ "type": "OperatorNode",
46
+ "fn": "divide",
47
+ "args": [
48
+ {"type": "SymbolNode", "name": "sum_xy"},
49
+ {"type": "ConstantNode", "value": "2", "valueType": "number"},
50
+ ],
51
+ },
52
+ },
53
+ "inputs": ["x", "y"],
54
+ "target": "mean",
55
+ }
56
+
57
+ evaluator = build_evaluator(**mathjs_payload, include_source=True)
58
+
59
+ result = evaluator({"x": 10, "y": 6})
60
+ print(result) # -> 8.0
61
+
62
+ # Introspection helpers
63
+ print(evaluator.__mathjs_required_inputs__) # ('x', 'y')
64
+ print(evaluator.__mathjs_evaluation_order__) # ('sum_xy', 'mean')
65
+ print(evaluator.__mathjs_source__) # Generated Python source
66
+ ```
67
+
68
+ ### Parameters
69
+
70
+ `build_evaluator` accepts keyword parameters (or a single `payload` mapping containing the same keys):
71
+
72
+ | Argument | Type | Description |
73
+ |---------------|------------------------------------|-------------|
74
+ | `expressions` | `Mapping[str, Mapping[str, Any]]` | math.js AST JSON keyed by expression id. Each id becomes a local variable in the compiled function. |
75
+ | `inputs` | `Iterable[str]` | Whitelisted identifiers that may be supplied when the function is invoked. |
76
+ | `target` | `str` | Name of the expression whose computed value should be returned. |
77
+ | `include_source` | `bool` (optional) | Attach the generated Python source code as `__mathjs_source__` on the returned callable. |
78
+
79
+ The returned callable always expects a single mapping argument with the provided inputs. It returns the evaluated `target` value and may be reused across invocations.
80
+
81
+ ### Supported math.js nodes
82
+
83
+ | Node | Notes |
84
+ |-------------------------|-------|
85
+ | `ConstantNode` | numeric (`number`), boolean, or `null` literals |
86
+ | `SymbolNode` | validated identifiers; must be alphanumeric/underscore, starting with a letter/underscore |
87
+ | `OperatorNode` | `add`, `subtract`, `multiply`, `divide`, `pow`, `mod`, unary `unaryPlus`, `unaryMinus` |
88
+ | `FunctionNode` | `min`, `max`, `sum`, `ifnull` |
89
+ | `ParenthesisNode` | forwards to the wrapped expression |
90
+ | `ArrayNode` | materialised to Python lists/NumPy arrays |
91
+
92
+ Unknown node types, invalid identifiers, or disallowed functions raise `InvalidNodeError` during compilation.
93
+
94
+ ### Error handling
95
+
96
+ - `ExpressionError`: base class for configuration mistakes.
97
+ - `MissingTargetError`: requested target id does not exist.
98
+ - `UnknownIdentifierError`: an expression references a symbol that is neither an input nor another expression.
99
+ - `CircularDependencyError`: dependency graph contains a cycle.
100
+ - `InvalidNodeError`: AST contains unsupported structures or invalid literals.
101
+ - `InputValidationError`: the compiled function received inputs that are missing, unexpected, or not a mapping.
102
+
103
+ All exceptions provide enough context (`expression` name, offending identifier, cycle list, etc.) to surface descriptive UI errors.
104
+
105
+ ## Implementation Notes
106
+
107
+ 1. **AST translation** – `MathJsAstBuilder` walks the math.js JSON and emits Python `ast.AST` nodes. Identifiers are validated via a strict regex to prevent sneaky names like `__import__`.
108
+ 2. **Dependency graph** – A topological sorter (`graphlib.TopologicalSorter`) runs over expression references to produce a safe evaluation order while catching cycles and missing references upfront.
109
+ 3. **Code generation** – The generated function validates the provided scope, binds required inputs to local variables, evaluates expressions in order, and returns the target. Intermediate values are stored as local variables named after their expression id.
110
+ 4. **Execution sandbox** – The compiled module is executed with a tightly scoped globals dictionary: helper math functions, NumPy, and a few safe built-ins only. There is no ambient `__builtins__` exposure.
111
+ 5. **Helper functions** – math.js functions map onto small Python helpers (`_mj_min`, `_mj_max`, `_mj_sum`, `_mj_ifnull`) that understand scalars and NumPy arrays.
112
+
113
+ ## Testing
114
+
115
+ Run the full suite (178 tests) with:
116
+
117
+ ```bash
118
+ uv run pytest
119
+ ```
120
+
121
+ The tests cover operator translation, helper semantics, dependency validation, error conditions, numpy-friendly behaviour, and public API ergonomics.
122
+
123
+ ## Project Structure
124
+
125
+ ```
126
+ src/mathjs_to_func/
127
+ ├── __init__.py # build_evaluator public API and export list
128
+ ├── ast_builder.py # math.js JSON → Python AST translation
129
+ ├── compiler.py # dependency graph, code generation, compilation
130
+ ├── errors.py # structured exception hierarchy
131
+ ├── helpers.py # runtime helpers for min/max/sum/ifnull
132
+ └── py.typed # PEP 561 marker for type-aware consumers
133
+ ```
134
+
135
+ Additional documentation lives in `docs/api_design.md`, outlining the initial design considerations.
136
+
137
+ ## Limitations & Future Work
138
+
139
+ - Only a subset of math.js functions/operators are implemented today.
140
+ - Units, user-defined functions, and incremental recomputation are intentionally out of scope for this milestone.
141
+ - Arrays are handled via NumPy; if you need bigints, complex numbers, or matrices, the helper layer will require extension.
142
+
143
+ Contributions and bug reports are welcome!