mcad2py 0.3.0__tar.gz → 0.4.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.
- {mcad2py-0.3.0/mcad2py.egg-info → mcad2py-0.4.0}/PKG-INFO +1 -1
- mcad2py-0.4.0/mcad2py/const.py +59 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/emit/codegen.py +136 -9
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/emit/notebook_backend.py +21 -1
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/emit/py_backend.py +20 -7
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/ir.py +114 -2
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/mapping.py +165 -1
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/parser/expressions.py +90 -10
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/parser/regions.py +300 -2
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/runtime.py +1686 -21
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/shapes.py +42 -1
- mcad2py-0.4.0/mcad2py/units.py +15 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0/mcad2py.egg-info}/PKG-INFO +1 -1
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py.egg-info/SOURCES.txt +2 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/pyproject.toml +1 -1
- {mcad2py-0.3.0 → mcad2py-0.4.0}/LICENSE +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/MANIFEST.in +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/README.md +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/__init__.py +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/cli.py +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/convert.py +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/emit/__init__.py +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/loader.py +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/parser/__init__.py +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/parser/namespaces.py +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py/text.py +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py.egg-info/dependency_links.txt +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py.egg-info/entry_points.txt +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py.egg-info/requires.txt +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/mcad2py.egg-info/top_level.txt +0 -0
- {mcad2py-0.3.0 → mcad2py-0.4.0}/setup.cfg +0 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Mathcad's built-in physical constants, as importable Pint quantities.
|
|
2
|
+
|
|
3
|
+
Generated code names these rather than inlining their values, so a formula reads
|
|
4
|
+
the way the worksheet does::
|
|
5
|
+
|
|
6
|
+
E = m * c**2 # not m * (299792458 * ureg.m / ureg.s)**2
|
|
7
|
+
|
|
8
|
+
They behave like Mathcad's constants do: in scope from the top of the sheet, and
|
|
9
|
+
shadowed the moment the worksheet defines a variable of the same name -- which
|
|
10
|
+
is simply Python assignment, since the import sits in the module header. (Prime
|
|
11
|
+
keeps the two apart by *label* even then; a sheet that defines its own ``c`` and
|
|
12
|
+
still refers to the constant ``c`` below it is the one case where that
|
|
13
|
+
divergence shows. No fixture does.)
|
|
14
|
+
|
|
15
|
+
Values are the CODATA/SI numbers Prime itself caches, in **base SI units** --
|
|
16
|
+
which is how ``result.xml`` states them, and what makes a scaled display
|
|
17
|
+
override (``10⁻³⁴ kg·m²/s``) divide down to exactly Mathcad's number.
|
|
18
|
+
|
|
19
|
+
The Mathcad display name for each is in :data:`mcad2py.mapping.CONSTANTS`, which
|
|
20
|
+
is what maps ``ℏ`` to ``hbar`` and ``R_∞`` to ``R_inf``.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from .units import ureg
|
|
26
|
+
|
|
27
|
+
#: Speed of light in vacuum.
|
|
28
|
+
c = 299792458 * ureg.m / ureg.s
|
|
29
|
+
#: Standard acceleration of gravity.
|
|
30
|
+
g = 9.80665 * ureg.m / ureg.s**2
|
|
31
|
+
#: Elementary charge (Mathcad spells it ``e_c``, to leave ``e`` to Euler).
|
|
32
|
+
e_c = 1.602176634e-19 * ureg.coulomb
|
|
33
|
+
#: Planck constant.
|
|
34
|
+
h = 6.62607015e-34 * ureg.kg * ureg.m**2 / ureg.s
|
|
35
|
+
#: Reduced Planck constant, Mathcad's ``ℏ``. Prime carries the rounded
|
|
36
|
+
#: 1.054571817e-34 rather than h/(2π), and the cache is held to it.
|
|
37
|
+
hbar = 1.054571817e-34 * ureg.kg * ureg.m**2 / ureg.s
|
|
38
|
+
#: Boltzmann constant.
|
|
39
|
+
k = 1.380649e-23 * ureg.kg * ureg.m**2 / (ureg.s**2 * ureg.K)
|
|
40
|
+
#: Atomic mass unit.
|
|
41
|
+
m_u = 1.66053906892e-27 * ureg.kg
|
|
42
|
+
#: Avogadro constant.
|
|
43
|
+
N_A = 6.02214076e23 / ureg.mol
|
|
44
|
+
#: Molar gas constant.
|
|
45
|
+
R = 8.314462618 * ureg.kg * ureg.m**2 / (ureg.s**2 * ureg.K * ureg.mol)
|
|
46
|
+
#: Rydberg constant, Mathcad's ``R_∞``.
|
|
47
|
+
R_inf = 10973731.56816 / ureg.m
|
|
48
|
+
#: Fine-structure constant (dimensionless).
|
|
49
|
+
alpha = 0.0072973525643
|
|
50
|
+
#: Euler-Mascheroni constant, Mathcad's ``γ`` (dimensionless).
|
|
51
|
+
gamma = 0.5772156649015329
|
|
52
|
+
#: Vacuum electric permittivity.
|
|
53
|
+
epsilon_0 = 8.8541878188e-12 * ureg.A**2 * ureg.s**4 / (ureg.kg * ureg.m**3)
|
|
54
|
+
#: Vacuum magnetic permeability.
|
|
55
|
+
mu_0 = 1.25663706127e-6 * ureg.kg * ureg.m / (ureg.s**2 * ureg.A**2)
|
|
56
|
+
#: Stefan-Boltzmann constant.
|
|
57
|
+
sigma = 5.670374419e-8 * ureg.kg / (ureg.s**3 * ureg.K**4)
|
|
58
|
+
#: Magnetic flux quantum.
|
|
59
|
+
Phi_0 = 2.067833848e-15 * ureg.weber
|
|
@@ -16,6 +16,7 @@ from .. import ir
|
|
|
16
16
|
from ..mapping import (
|
|
17
17
|
BINARY_OPS,
|
|
18
18
|
CONSTANTS,
|
|
19
|
+
CONST_MODULE_NAMES,
|
|
19
20
|
FUNCTIONS,
|
|
20
21
|
UNARY_PREC,
|
|
21
22
|
unit_attr,
|
|
@@ -27,9 +28,38 @@ _ATOM = 100
|
|
|
27
28
|
_WRAP_WIDTH = 88
|
|
28
29
|
|
|
29
30
|
|
|
31
|
+
# A ``# TODO``/``# placeholder`` note is a comment, so it swallows whatever
|
|
32
|
+
# follows it on the line. That is harmless when the note *is* the whole
|
|
33
|
+
# expression (``x = None # TODO unsupported: …``) and fatal when it sits in an
|
|
34
|
+
# argument list, where the closing parenthesis ends up inside the comment and
|
|
35
|
+
# the module stops parsing -- the one outcome the "output still loads"
|
|
36
|
+
# convention exists to prevent. So a note node renders as a bare ``None`` and
|
|
37
|
+
# pushes its text here; the outermost :func:`expr_to_str` appends the collected
|
|
38
|
+
# notes once, at the end of the line, where a comment is safe.
|
|
39
|
+
_NOTES: list[str] = []
|
|
40
|
+
_DEPTH = 0
|
|
41
|
+
|
|
42
|
+
|
|
30
43
|
def expr_to_str(node: ir.Expr) -> str:
|
|
31
44
|
"""Render an expression with no unnecessary outer parentheses."""
|
|
32
|
-
|
|
45
|
+
global _DEPTH
|
|
46
|
+
if _DEPTH == 0:
|
|
47
|
+
_NOTES.clear()
|
|
48
|
+
_DEPTH += 1
|
|
49
|
+
try:
|
|
50
|
+
text = _emit(node)[0]
|
|
51
|
+
finally:
|
|
52
|
+
_DEPTH -= 1
|
|
53
|
+
if _DEPTH == 0 and _NOTES:
|
|
54
|
+
text += " # " + "; ".join(_NOTES)
|
|
55
|
+
_NOTES.clear()
|
|
56
|
+
return text
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _note(text: str) -> str:
|
|
60
|
+
"""Record a TODO/placeholder note and render its node as a bare ``None``."""
|
|
61
|
+
_NOTES.append(text)
|
|
62
|
+
return "None"
|
|
33
63
|
|
|
34
64
|
|
|
35
65
|
def _emit(node: ir.Expr) -> tuple[str, int]:
|
|
@@ -68,6 +98,13 @@ def _emit(node: ir.Expr) -> tuple[str, int]:
|
|
|
68
98
|
return f"{left}{joiner}{right}", prec
|
|
69
99
|
|
|
70
100
|
if isinstance(node, ir.UnaryOp):
|
|
101
|
+
if node.op == "not_":
|
|
102
|
+
# Mathcad's ``¬x`` is "x is zero", which is exactly what Python's
|
|
103
|
+
# ``not`` says of a number. Its precedence sits below the
|
|
104
|
+
# comparisons, so anything that isn't an atom is parenthesised
|
|
105
|
+
# rather than given a rung in BINARY_OPS.
|
|
106
|
+
operand = _wrap(node.operand, _ATOM, is_left=True, right_assoc=False)
|
|
107
|
+
return f"not {operand}", 0
|
|
71
108
|
operand = _wrap(node.operand, UNARY_PREC, is_left=True, right_assoc=False)
|
|
72
109
|
return f"-{operand}", UNARY_PREC
|
|
73
110
|
|
|
@@ -139,11 +176,21 @@ def _emit(node: ir.Expr) -> tuple[str, int]:
|
|
|
139
176
|
if isinstance(node, ir.ProgramBlock):
|
|
140
177
|
# A ProgramBlock is only ever a Define/MultiAssign value (emitted as a
|
|
141
178
|
# ``def`` by assignment_line/multi_assign_lines), never inline.
|
|
142
|
-
return "
|
|
179
|
+
return _note("TODO: program block used inline"), _ATOM
|
|
143
180
|
|
|
144
181
|
if isinstance(node, ir.VectorSum):
|
|
145
182
|
return f"total({expr_to_str(node.operand)})", _ATOM
|
|
146
183
|
|
|
184
|
+
if isinstance(node, ir.RangeSum):
|
|
185
|
+
var = node.func.params[0]
|
|
186
|
+
# The first argument reads the range variable from the enclosing scope;
|
|
187
|
+
# the lambda's parameter shadows it for the body, which is exactly what
|
|
188
|
+
# Mathcad does with the same name.
|
|
189
|
+
return (
|
|
190
|
+
f"range_sum({var}, lambda {var}: {expr_to_str(node.func.body)})",
|
|
191
|
+
_ATOM,
|
|
192
|
+
)
|
|
193
|
+
|
|
147
194
|
if isinstance(node, ir.Vectorize):
|
|
148
195
|
return f"vectorize({expr_to_str(node.operand)})", _ATOM
|
|
149
196
|
|
|
@@ -171,6 +218,13 @@ def _emit(node: ir.Expr) -> tuple[str, int]:
|
|
|
171
218
|
_ATOM,
|
|
172
219
|
)
|
|
173
220
|
|
|
221
|
+
if isinstance(node, ir.Derivative):
|
|
222
|
+
return (
|
|
223
|
+
f"derivative({expr_to_str(node.func)}, {node.var}, "
|
|
224
|
+
f"{expr_to_str(node.degree)})",
|
|
225
|
+
_ATOM,
|
|
226
|
+
)
|
|
227
|
+
|
|
174
228
|
if isinstance(node, ir.Summation):
|
|
175
229
|
return (
|
|
176
230
|
f"summation({expr_to_str(node.func)}, "
|
|
@@ -194,12 +248,12 @@ def _emit(node: ir.Expr) -> tuple[str, int]:
|
|
|
194
248
|
return repr(node.value), _ATOM
|
|
195
249
|
|
|
196
250
|
if isinstance(node, ir.Placeholder):
|
|
197
|
-
return "
|
|
251
|
+
return _note("placeholder"), _ATOM
|
|
198
252
|
|
|
199
253
|
if isinstance(node, ir.Unsupported):
|
|
200
|
-
return f"
|
|
254
|
+
return _note(f"TODO unsupported: {node.note}"), _ATOM
|
|
201
255
|
|
|
202
|
-
return f"
|
|
256
|
+
return _note(f"TODO unknown node: {type(node).__name__}"), _ATOM
|
|
203
257
|
|
|
204
258
|
|
|
205
259
|
def _is_int_literal(node: ir.Expr) -> bool:
|
|
@@ -358,6 +412,12 @@ def _stmt_lines_raw(stmt: ir.Stmt, indent: int) -> list[str]:
|
|
|
358
412
|
f"({expr_to_str(target.row)}, {expr_to_str(target.col)}), "
|
|
359
413
|
f"{expr_to_str(value)})"
|
|
360
414
|
]
|
|
415
|
+
if isinstance(target, ir.MatCol):
|
|
416
|
+
base = expr_to_str(target.base)
|
|
417
|
+
return [
|
|
418
|
+
f"{pad}{base} = col_set({base}, {expr_to_str(target.index)}, "
|
|
419
|
+
f"{expr_to_str(value)})"
|
|
420
|
+
]
|
|
361
421
|
return [f"{pad}{expr_to_str(target)} = {expr_to_str(value)}"]
|
|
362
422
|
if isinstance(stmt, ir.ForLoop):
|
|
363
423
|
lines = [f"{pad}for {stmt.var.py} in {expr_to_str(stmt.iterable)}:"]
|
|
@@ -373,6 +433,8 @@ def _stmt_lines_raw(stmt: ir.Stmt, indent: int) -> list[str]:
|
|
|
373
433
|
inner = _block_lines(body, indent + 1)
|
|
374
434
|
lines += inner if inner else [f"{pad} pass"]
|
|
375
435
|
return lines
|
|
436
|
+
if isinstance(stmt, ir.ExprStmt):
|
|
437
|
+
return [f"{pad}{expr_to_str(stmt.value)}"]
|
|
376
438
|
if isinstance(stmt, ir.Return):
|
|
377
439
|
return [f"{pad}return {expr_to_str(stmt.value)}"]
|
|
378
440
|
if isinstance(stmt, ir.TryCatch):
|
|
@@ -394,7 +456,7 @@ def _growable_names(block: ir.ProgramBlock) -> list[str]:
|
|
|
394
456
|
def scan(b: ir.ProgramBlock) -> None:
|
|
395
457
|
for stmt in b.statements:
|
|
396
458
|
if isinstance(stmt, ir.LocalAssign) and isinstance(
|
|
397
|
-
stmt.target, (ir.Index, ir.Index2D)
|
|
459
|
+
stmt.target, (ir.Index, ir.Index2D, ir.MatCol)
|
|
398
460
|
):
|
|
399
461
|
base = stmt.target.base
|
|
400
462
|
if isinstance(base, ir.Name) and base.py not in names:
|
|
@@ -579,6 +641,22 @@ def _program_ternary(branches: list[tuple[ir.Expr | None, ir.Expr]]) -> str:
|
|
|
579
641
|
return expr
|
|
580
642
|
|
|
581
643
|
|
|
644
|
+
def print_lines(echo: str) -> list[str]:
|
|
645
|
+
"""``print(<echo>)``, with any rendered note lifted onto its own line first.
|
|
646
|
+
|
|
647
|
+
An unsupported (or placeholder) node renders as ``None # TODO unsupported:
|
|
648
|
+
…``; wrapping *that* in ``print(...)`` puts the closing parenthesis inside
|
|
649
|
+
the comment and the module stops parsing altogether -- which is exactly what
|
|
650
|
+
the "never silently drop a region, the output still loads" convention exists
|
|
651
|
+
to prevent. Splitting on the last note marker keeps the TODO visible without
|
|
652
|
+
letting it swallow the call.
|
|
653
|
+
"""
|
|
654
|
+
expr, marker, note = echo.rpartition(" # ")
|
|
655
|
+
if marker and note.startswith(("TODO", "placeholder")):
|
|
656
|
+
return [f"# {note}", f"print({expr})"]
|
|
657
|
+
return [f"print({echo})"]
|
|
658
|
+
|
|
659
|
+
|
|
582
660
|
def echo_expr(region: ir.Region) -> str | None:
|
|
583
661
|
"""The expression to display for an evaluated region, or None.
|
|
584
662
|
|
|
@@ -967,7 +1045,6 @@ def header_lines(ws: ir.Worksheet, source: str) -> list[str]:
|
|
|
967
1045
|
lines.append("import numpy as np")
|
|
968
1046
|
if any(isinstance(r, (ir.Plot, ir.GridPlot)) for r in ws.regions):
|
|
969
1047
|
lines.append("import matplotlib.pyplot as plt")
|
|
970
|
-
lines.append("import pint")
|
|
971
1048
|
sympy_names = _sympy_imports(ws)
|
|
972
1049
|
if sympy_names:
|
|
973
1050
|
order = ["Eq", "Symbol", "solve", "simplify", "factor", "expand"]
|
|
@@ -975,13 +1052,59 @@ def header_lines(ws: ir.Worksheet, source: str) -> list[str]:
|
|
|
975
1052
|
ordered += sorted(sympy_names - set(order))
|
|
976
1053
|
lines.append(f"from sympy import {', '.join(ordered)}")
|
|
977
1054
|
lines.append("")
|
|
1055
|
+
constants = _const_imports(ws)
|
|
1056
|
+
if constants:
|
|
1057
|
+
lines.append(f"from mcad2py.const import {', '.join(constants)}")
|
|
978
1058
|
runtime = [n for n in _runtime_exports() if n in names]
|
|
979
1059
|
if runtime:
|
|
980
1060
|
lines.append(f"from mcad2py.runtime import {', '.join(runtime)}")
|
|
981
|
-
|
|
1061
|
+
# The *shared* registry, not a fresh one: a constant from mcad2py.const is a
|
|
1062
|
+
# pre-built quantity, and Pint refuses to combine quantities whose
|
|
1063
|
+
# registries differ. See mcad2py/units.py.
|
|
1064
|
+
lines.append("from mcad2py.units import ureg")
|
|
982
1065
|
return lines
|
|
983
1066
|
|
|
984
1067
|
|
|
1068
|
+
def _const_imports(ws: ir.Worksheet) -> list[str]:
|
|
1069
|
+
"""The ``mcad2py.const`` names this worksheet needs, in definition order.
|
|
1070
|
+
|
|
1071
|
+
Driven by the **IR**, not by the rendered text the way the runtime imports
|
|
1072
|
+
are: these are short, everyday spellings (``c``, ``g``, ``k``, ``R``), so
|
|
1073
|
+
scanning the source for them would import a constant on the strength of a
|
|
1074
|
+
worksheet variable that merely shares a letter. A CONSTANT-labelled
|
|
1075
|
+
``ir.Name`` is unambiguous -- it is precisely what the lookup emits.
|
|
1076
|
+
"""
|
|
1077
|
+
used = {
|
|
1078
|
+
CONSTANTS[node.original]
|
|
1079
|
+
for region in ws.regions
|
|
1080
|
+
for node in _walk_expr_tree(region)
|
|
1081
|
+
if isinstance(node, ir.Name)
|
|
1082
|
+
and node.role == "CONSTANT"
|
|
1083
|
+
and node.original in CONSTANTS
|
|
1084
|
+
}
|
|
1085
|
+
return [n for n in _const_module_order() if n in used & CONST_MODULE_NAMES]
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
@lru_cache(maxsize=1)
|
|
1089
|
+
def _const_module_order() -> tuple[str, ...]:
|
|
1090
|
+
"""Every constant defined in ``const.py``, in definition order (as with the
|
|
1091
|
+
runtime helpers, so the emitted import line keeps the module's grouping)."""
|
|
1092
|
+
from .. import const
|
|
1093
|
+
|
|
1094
|
+
return tuple(name for name in vars(const) if not name.startswith("_"))
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def _walk_expr_tree(region: ir.Region) -> "list[ir.Expr]":
|
|
1098
|
+
"""Every expression in a region and its sub-expressions, pre-order."""
|
|
1099
|
+
out: list[ir.Expr] = []
|
|
1100
|
+
stack = list(ir.region_exprs(region))
|
|
1101
|
+
while stack:
|
|
1102
|
+
node = stack.pop()
|
|
1103
|
+
out.append(node)
|
|
1104
|
+
stack.extend(ir.child_exprs(node))
|
|
1105
|
+
return out
|
|
1106
|
+
|
|
1107
|
+
|
|
985
1108
|
@lru_cache(maxsize=1)
|
|
986
1109
|
def _runtime_exports() -> tuple[str, ...]:
|
|
987
1110
|
"""Every public helper *defined in* ``runtime.py``, in definition order.
|
|
@@ -1064,7 +1187,11 @@ def _sympy_imports(ws: ir.Worksheet) -> set[str]:
|
|
|
1064
1187
|
if isinstance(region, ir.SymbolDeclarations):
|
|
1065
1188
|
names.add("Symbol")
|
|
1066
1189
|
elif isinstance(region, ir.SymbolicEquation):
|
|
1067
|
-
|
|
1190
|
+
# A display-only equation is emitted as a comment, so it needs no
|
|
1191
|
+
# import -- and asking for one the body never names would break the
|
|
1192
|
+
# import round-trip test.
|
|
1193
|
+
if not region.display_only:
|
|
1194
|
+
names.add("Eq")
|
|
1068
1195
|
elif isinstance(region, ir.SymbolicEval):
|
|
1069
1196
|
names.add(region.command)
|
|
1070
1197
|
if any(isinstance(e, ir.Equation) for e in _walk(region.expr)):
|
|
@@ -109,6 +109,11 @@ def _render_region(region: ir.Region) -> nbformat.NotebookNode | None:
|
|
|
109
109
|
echo = echo_expr(region)
|
|
110
110
|
return nbformat.v4.new_code_cell(echo) if echo is not None else None
|
|
111
111
|
|
|
112
|
+
if isinstance(region, ir.Statement):
|
|
113
|
+
# Trailing ";" so Jupyter suppresses the return value: the Mathcad
|
|
114
|
+
# region shows no result either.
|
|
115
|
+
return nbformat.v4.new_code_cell(expr_to_str(region.value) + ";")
|
|
116
|
+
|
|
112
117
|
if isinstance(region, ir.StatusControl):
|
|
113
118
|
return nbformat.v4.new_code_cell(status_control_line(region))
|
|
114
119
|
|
|
@@ -117,6 +122,10 @@ def _render_region(region: ir.Region) -> nbformat.NotebookNode | None:
|
|
|
117
122
|
|
|
118
123
|
if isinstance(region, ir.SymbolicEquation):
|
|
119
124
|
# Bare Eq(...) last line -> the notebook renders the typeset equation.
|
|
125
|
+
if region.display_only:
|
|
126
|
+
return nbformat.v4.new_code_cell(
|
|
127
|
+
f"# shown, not computed: {expr_to_str(region.equation)}"
|
|
128
|
+
)
|
|
120
129
|
return nbformat.v4.new_code_cell(expr_to_str(region.equation))
|
|
121
130
|
|
|
122
131
|
if isinstance(region, ir.SymbolicEval):
|
|
@@ -132,7 +141,18 @@ def _render_region(region: ir.Region) -> nbformat.NotebookNode | None:
|
|
|
132
141
|
return nbformat.v4.new_code_cell("\n".join(grid_plot_lines(region)))
|
|
133
142
|
|
|
134
143
|
if isinstance(region, ir.UnsupportedRegion):
|
|
135
|
-
|
|
144
|
+
text = f"> **TODO** unsupported region: {region.note}"
|
|
145
|
+
# Show the Python it would have been. A downstream note reads "needs b,
|
|
146
|
+
# left undefined above", which is only actionable once you can see what
|
|
147
|
+
# ``b`` was. The label leads so a reader cannot mistake the block for a
|
|
148
|
+
# cell that is meant to run; the ``.py`` backend puts the code first,
|
|
149
|
+
# where the statement itself would have stood.
|
|
150
|
+
would_be = _render_region(region.original) if region.original else None
|
|
151
|
+
if would_be is not None and would_be.get("source"):
|
|
152
|
+
quoted = [f"> {line}"
|
|
153
|
+
for line in would_be["source"].splitlines()]
|
|
154
|
+
text = "\n".join([text, ">", *quoted])
|
|
155
|
+
return nbformat.v4.new_markdown_cell(text)
|
|
136
156
|
|
|
137
157
|
return None
|
|
138
158
|
|
|
@@ -15,6 +15,7 @@ from .codegen import (
|
|
|
15
15
|
index_assign_line,
|
|
16
16
|
multi_assign_lines,
|
|
17
17
|
plot_lines,
|
|
18
|
+
print_lines,
|
|
18
19
|
recurrence_lines,
|
|
19
20
|
solve_block_lines,
|
|
20
21
|
source_comment,
|
|
@@ -63,14 +64,14 @@ def _render_region(region: ir.Region) -> list[str]:
|
|
|
63
64
|
out = ["", assignment_line(region)]
|
|
64
65
|
echo = echo_expr(region)
|
|
65
66
|
if echo is not None:
|
|
66
|
-
out.
|
|
67
|
+
out.extend(print_lines(echo))
|
|
67
68
|
return out
|
|
68
69
|
|
|
69
70
|
if isinstance(region, ir.MultiAssign):
|
|
70
71
|
out = ["", *multi_assign_lines(region)]
|
|
71
72
|
echo = echo_expr(region)
|
|
72
73
|
if echo is not None:
|
|
73
|
-
out.
|
|
74
|
+
out.extend(print_lines(echo))
|
|
74
75
|
return out
|
|
75
76
|
|
|
76
77
|
if isinstance(region, ir.ComboBoxAssign):
|
|
@@ -80,19 +81,22 @@ def _render_region(region: ir.Region) -> list[str]:
|
|
|
80
81
|
out = ["", index_assign_line(region)]
|
|
81
82
|
echo = echo_expr(region)
|
|
82
83
|
if echo is not None:
|
|
83
|
-
out.
|
|
84
|
+
out.extend(print_lines(echo))
|
|
84
85
|
return out
|
|
85
86
|
|
|
86
87
|
if isinstance(region, ir.Recurrence):
|
|
87
88
|
out = ["", *recurrence_lines(region)]
|
|
88
89
|
echo = echo_expr(region)
|
|
89
90
|
if echo is not None:
|
|
90
|
-
out.
|
|
91
|
+
out.extend(print_lines(echo))
|
|
91
92
|
return out
|
|
92
93
|
|
|
93
94
|
if isinstance(region, ir.Evaluate):
|
|
94
95
|
echo = echo_expr(region)
|
|
95
|
-
return ["",
|
|
96
|
+
return ["", *print_lines(echo)] if echo is not None else []
|
|
97
|
+
|
|
98
|
+
if isinstance(region, ir.Statement):
|
|
99
|
+
return ["", expr_to_str(region.value)]
|
|
96
100
|
|
|
97
101
|
if isinstance(region, ir.StatusControl):
|
|
98
102
|
return ["", status_control_line(region)]
|
|
@@ -102,10 +106,12 @@ def _render_region(region: ir.Region) -> list[str]:
|
|
|
102
106
|
|
|
103
107
|
if isinstance(region, ir.SymbolicEquation):
|
|
104
108
|
# A step shown for context; assigned to nothing, like the Mathcad sheet.
|
|
109
|
+
if region.display_only:
|
|
110
|
+
return ["", f"# shown, not computed: {expr_to_str(region.equation)}"]
|
|
105
111
|
return ["", expr_to_str(region.equation)]
|
|
106
112
|
|
|
107
113
|
if isinstance(region, ir.SymbolicEval):
|
|
108
|
-
return ["",
|
|
114
|
+
return ["", *print_lines(symbolic_eval_expr(region))]
|
|
109
115
|
|
|
110
116
|
if isinstance(region, ir.SolveBlock):
|
|
111
117
|
return ["", *solve_block_lines(region)]
|
|
@@ -117,6 +123,13 @@ def _render_region(region: ir.Region) -> list[str]:
|
|
|
117
123
|
return ["", *grid_plot_lines(region)]
|
|
118
124
|
|
|
119
125
|
if isinstance(region, ir.UnsupportedRegion):
|
|
120
|
-
|
|
126
|
+
# The Python it would have been, commented out. A downstream note reads
|
|
127
|
+
# "needs b, left undefined above", which is only actionable once you can
|
|
128
|
+
# see what ``b`` was.
|
|
129
|
+
would_be = [f"# {line}" if line else "#"
|
|
130
|
+
for line in _render_region(region.original)] if region.original else []
|
|
131
|
+
while would_be and would_be[0] == "#":
|
|
132
|
+
would_be.pop(0)
|
|
133
|
+
return ["", *would_be, f"# TODO unsupported region: {region.note}"]
|
|
121
134
|
|
|
122
135
|
return []
|
|
@@ -8,7 +8,7 @@ the other half of the pipeline.
|
|
|
8
8
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
|
-
from dataclasses import dataclass, field
|
|
11
|
+
from dataclasses import dataclass, field, fields, is_dataclass
|
|
12
12
|
|
|
13
13
|
# ---------------------------------------------------------------------------
|
|
14
14
|
# Expression nodes
|
|
@@ -65,6 +65,8 @@ class BinOp(Expr):
|
|
|
65
65
|
|
|
66
66
|
@dataclass
|
|
67
67
|
class UnaryOp(Expr):
|
|
68
|
+
"""A prefix operator: ``"neg"`` (``-x``) or ``"not_"`` (Mathcad's ``¬x``)."""
|
|
69
|
+
|
|
68
70
|
op: str
|
|
69
71
|
operand: Expr
|
|
70
72
|
|
|
@@ -219,6 +221,17 @@ class Return(Stmt):
|
|
|
219
221
|
value: Expr
|
|
220
222
|
|
|
221
223
|
|
|
224
|
+
@dataclass
|
|
225
|
+
class ExprStmt(Stmt):
|
|
226
|
+
"""A bare call inside a program body, run for its effect.
|
|
227
|
+
|
|
228
|
+
Mathcad's implicit return is the *last* line of a block only; a bare
|
|
229
|
+
expression above it is just a call (``Seed(1)`` at the top of a loop).
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
value: Expr
|
|
233
|
+
|
|
234
|
+
|
|
222
235
|
@dataclass
|
|
223
236
|
class TryCatch(Stmt):
|
|
224
237
|
"""``try: … except Exception: …`` (Mathcad ``<ml:tryCatch>``)."""
|
|
@@ -279,6 +292,23 @@ class Summation(Expr):
|
|
|
279
292
|
upper: Expr
|
|
280
293
|
|
|
281
294
|
|
|
295
|
+
@dataclass
|
|
296
|
+
class Derivative(Expr):
|
|
297
|
+
"""Mathcad's numeric derivative operator ``d^n/dx^n f(x)``.
|
|
298
|
+
|
|
299
|
+
The XML is ``<ml:apply><ml:derivative /><ml:lambda>…<ml:degree>``; the
|
|
300
|
+
lambda's bound variable is the one differentiated against, and an empty
|
|
301
|
+
``<ml:degree>`` means first order. Emitted as
|
|
302
|
+
``derivative(<func>, <var>, <degree>)`` -- evaluated *at* the variable, which
|
|
303
|
+
is in scope because the operator only ever appears inside a definition of a
|
|
304
|
+
function of it.
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
func: Lambda
|
|
308
|
+
var: str
|
|
309
|
+
degree: Expr
|
|
310
|
+
|
|
311
|
+
|
|
282
312
|
@dataclass
|
|
283
313
|
class VectorSum(Expr):
|
|
284
314
|
"""Mathcad's bare ``Σ`` over a whole vector (no index bounds).
|
|
@@ -291,6 +321,23 @@ class VectorSum(Expr):
|
|
|
291
321
|
operand: Expr
|
|
292
322
|
|
|
293
323
|
|
|
324
|
+
@dataclass
|
|
325
|
+
class RangeSum(Expr):
|
|
326
|
+
"""Mathcad's ``Σ`` over a **range variable** (``<ml:summation>``, no bounds).
|
|
327
|
+
|
|
328
|
+
The XML has a ``<ml:lambda>`` with a bound variable but an empty
|
|
329
|
+
``<upperBound>`` and no ``<lowerBound>`` at all. Mathcad reads the bound
|
|
330
|
+
variable as a range already defined on the sheet and sums the body over
|
|
331
|
+
every value in it -- so the domain is the variable's own name, not a pair of
|
|
332
|
+
bounds. Emitted as ``range_sum(<var>, lambda <var>: <body>)``.
|
|
333
|
+
|
|
334
|
+
Distinct from :class:`VectorSum`, where the bound variable is *also* empty
|
|
335
|
+
and the body is already a vector.
|
|
336
|
+
"""
|
|
337
|
+
|
|
338
|
+
func: Lambda
|
|
339
|
+
|
|
340
|
+
|
|
294
341
|
@dataclass
|
|
295
342
|
class MatCol(Expr):
|
|
296
343
|
"""Mathcad column extraction ``A^<i>`` (``<ml:matcol>``).
|
|
@@ -383,6 +430,9 @@ class Define(Region):
|
|
|
383
430
|
the assignment (used to document a scriptable control's cached value).
|
|
384
431
|
``source`` is the originating region's :class:`SourceRef` (see
|
|
385
432
|
``--trace-source``), or ``None`` if the sheet wasn't tagged.
|
|
433
|
+
``global_scope`` marks Mathcad's ``≡`` (``<ml:globalDefine>``), which binds
|
|
434
|
+
across the *whole* sheet rather than from its position down -- so the parser
|
|
435
|
+
hoists it above the ordinary regions.
|
|
386
436
|
"""
|
|
387
437
|
|
|
388
438
|
target: Name
|
|
@@ -392,6 +442,7 @@ class Define(Region):
|
|
|
392
442
|
params: list[str] = field(default_factory=list)
|
|
393
443
|
comment: str | None = None
|
|
394
444
|
source: SourceRef | None = None
|
|
445
|
+
global_scope: bool = False
|
|
395
446
|
|
|
396
447
|
|
|
397
448
|
@dataclass
|
|
@@ -403,6 +454,21 @@ class Evaluate(Region):
|
|
|
403
454
|
source: SourceRef | None = None
|
|
404
455
|
|
|
405
456
|
|
|
457
|
+
@dataclass
|
|
458
|
+
class Statement(Region):
|
|
459
|
+
"""A bare call region with no ``=``: Mathcad runs it and shows no result.
|
|
460
|
+
|
|
461
|
+
Prime writes this as an ``<ml:apply>`` directly under ``<math>`` -- no
|
|
462
|
+
``<ml:define>``, no ``<ml:eval>``. ``Seed(1)`` on its own line is the case
|
|
463
|
+
that motivated it: it is called for its effect on the random stream, and
|
|
464
|
+
the sheet displays nothing. Wrapping it in ``print`` would invent output
|
|
465
|
+
the worksheet never shows.
|
|
466
|
+
"""
|
|
467
|
+
|
|
468
|
+
value: Expr
|
|
469
|
+
source: SourceRef | None = None
|
|
470
|
+
|
|
471
|
+
|
|
406
472
|
@dataclass
|
|
407
473
|
class StatusControl(Region):
|
|
408
474
|
"""A standalone scriptable status widget (``<ml:...ScriptableControl>``).
|
|
@@ -557,10 +623,18 @@ class SymbolDeclarations(Region):
|
|
|
557
623
|
|
|
558
624
|
@dataclass
|
|
559
625
|
class SymbolicEquation(Region):
|
|
560
|
-
"""A standalone symbolic equation shown as a step (assigned to nothing).
|
|
626
|
+
"""A standalone symbolic equation shown as a step (assigned to nothing).
|
|
627
|
+
|
|
628
|
+
``display_only`` marks one whose names the sheet has *already* given numeric
|
|
629
|
+
values -- a tutorial writing out the recurrence ``X[k] = c[0]·X[k-3] + …``
|
|
630
|
+
beside the data it applies to. Mathcad computes nothing for such a region,
|
|
631
|
+
and evaluating it in Python would index a real array with a real range
|
|
632
|
+
variable and raise, so it is emitted as a comment instead of as ``Eq(...)``.
|
|
633
|
+
"""
|
|
561
634
|
|
|
562
635
|
equation: Equation
|
|
563
636
|
source: SourceRef | None = None
|
|
637
|
+
display_only: bool = False
|
|
564
638
|
|
|
565
639
|
|
|
566
640
|
@dataclass
|
|
@@ -690,9 +764,20 @@ class ImageRegion(Region):
|
|
|
690
764
|
|
|
691
765
|
@dataclass
|
|
692
766
|
class UnsupportedRegion(Region):
|
|
767
|
+
"""A region the converter declines to emit, shown as a comment instead.
|
|
768
|
+
|
|
769
|
+
``original`` is the region it replaced, kept so the backends can print the
|
|
770
|
+
Python it *would* have been. Without that a reader sees "needs b, left
|
|
771
|
+
undefined above" with no way to learn what ``b`` was -- and the whole point
|
|
772
|
+
of a visible TODO is that someone can act on it. Rendering is the backends'
|
|
773
|
+
job, so the node carries the IR rather than a rendered string; a parser that
|
|
774
|
+
formatted Python here would be reaching across the IR boundary.
|
|
775
|
+
"""
|
|
776
|
+
|
|
693
777
|
note: str
|
|
694
778
|
raw: str = ""
|
|
695
779
|
source: SourceRef | None = None
|
|
780
|
+
original: Region | None = None
|
|
696
781
|
|
|
697
782
|
|
|
698
783
|
# ---------------------------------------------------------------------------
|
|
@@ -761,6 +846,33 @@ def child_exprs(node: object) -> list[Expr]:
|
|
|
761
846
|
return []
|
|
762
847
|
|
|
763
848
|
|
|
849
|
+
def region_exprs(region: object) -> list[Expr]:
|
|
850
|
+
"""Every top-level expression a region holds, found *generically*.
|
|
851
|
+
|
|
852
|
+
Walking the region's dataclass fields (and any nested dataclass, such as a
|
|
853
|
+
plot's traces) rather than listing them per region type: there is no table
|
|
854
|
+
to fall out of date when a region grows a field, and a caller that recurses
|
|
855
|
+
with :func:`child_exprs` from here sees the whole sheet.
|
|
856
|
+
"""
|
|
857
|
+
out: list[Expr] = []
|
|
858
|
+
_collect_exprs(region, out)
|
|
859
|
+
return out
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
def _collect_exprs(value: object, out: list[Expr]) -> None:
|
|
863
|
+
if isinstance(value, Expr):
|
|
864
|
+
out.append(value) # stop here: child_exprs is the caller's job
|
|
865
|
+
elif is_dataclass(value) and not isinstance(value, type):
|
|
866
|
+
for f in fields(value):
|
|
867
|
+
_collect_exprs(getattr(value, f.name, None), out)
|
|
868
|
+
elif isinstance(value, (list, tuple)):
|
|
869
|
+
for item in value:
|
|
870
|
+
_collect_exprs(item, out)
|
|
871
|
+
elif isinstance(value, dict):
|
|
872
|
+
for item in value.values():
|
|
873
|
+
_collect_exprs(item, out)
|
|
874
|
+
|
|
875
|
+
|
|
764
876
|
def _stmt_exprs(stmt: Stmt) -> list[Expr]:
|
|
765
877
|
"""The sub-expressions of a program statement (bodies are ``ProgramBlock``
|
|
766
878
|
expressions, so a generic ``child_exprs`` walk recurses into them)."""
|