mcad2py 0.2.0__tar.gz → 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {mcad2py-0.2.0/mcad2py.egg-info → mcad2py-0.3.0}/PKG-INFO +1 -1
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/cli.py +16 -1
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/convert.py +10 -3
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/emit/codegen.py +287 -142
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/emit/notebook_backend.py +35 -12
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/emit/py_backend.py +34 -5
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/ir.py +114 -5
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/loader.py +10 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/mapping.py +62 -25
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/parser/expressions.py +52 -5
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/parser/namespaces.py +5 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/parser/regions.py +251 -5
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/runtime.py +795 -43
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/shapes.py +16 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0/mcad2py.egg-info}/PKG-INFO +1 -1
- {mcad2py-0.2.0 → mcad2py-0.3.0}/pyproject.toml +1 -1
- {mcad2py-0.2.0 → mcad2py-0.3.0}/LICENSE +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/MANIFEST.in +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/README.md +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/__init__.py +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/emit/__init__.py +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/parser/__init__.py +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py/text.py +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py.egg-info/SOURCES.txt +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py.egg-info/dependency_links.txt +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py.egg-info/entry_points.txt +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py.egg-info/requires.txt +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/mcad2py.egg-info/top_level.txt +0 -0
- {mcad2py-0.2.0 → mcad2py-0.3.0}/setup.cfg +0 -0
|
@@ -4,16 +4,25 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import argparse
|
|
6
6
|
import sys
|
|
7
|
+
from importlib.metadata import version
|
|
7
8
|
from pathlib import Path
|
|
8
9
|
|
|
9
10
|
from .convert import convert_file
|
|
10
11
|
|
|
12
|
+
__version__ = version("mcad2py")
|
|
13
|
+
|
|
11
14
|
|
|
12
15
|
def main(argv: list[str] | None = None) -> int:
|
|
13
16
|
parser = argparse.ArgumentParser(
|
|
14
17
|
prog="mcad2py",
|
|
15
18
|
description="Convert PTC Mathcad Prime (.mcdx) worksheets to Python / Jupyter.",
|
|
16
19
|
)
|
|
20
|
+
parser.add_argument(
|
|
21
|
+
"-v",
|
|
22
|
+
"--version",
|
|
23
|
+
action="version",
|
|
24
|
+
version=f"%(prog)s {__version__}",
|
|
25
|
+
)
|
|
17
26
|
sub = parser.add_subparsers(dest="command", required=True)
|
|
18
27
|
|
|
19
28
|
conv = sub.add_parser("convert", help="convert a .mcdx file")
|
|
@@ -30,6 +39,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
30
39
|
choices=["notebook", "py"],
|
|
31
40
|
help="output format (default: inferred from -o suffix, else notebook).",
|
|
32
41
|
)
|
|
42
|
+
conv.add_argument(
|
|
43
|
+
"--trace-source",
|
|
44
|
+
action="store_true",
|
|
45
|
+
help="annotate each statement with its Mathcad worksheet region id "
|
|
46
|
+
"(and original name, if renamed).",
|
|
47
|
+
)
|
|
33
48
|
|
|
34
49
|
args = parser.parse_args(argv)
|
|
35
50
|
if args.command == "convert":
|
|
@@ -41,7 +56,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
41
56
|
def _run_convert(args: argparse.Namespace) -> int:
|
|
42
57
|
fmt = args.format or _infer_format(args.output)
|
|
43
58
|
try:
|
|
44
|
-
result = convert_file(args.input, fmt=fmt)
|
|
59
|
+
result = convert_file(args.input, fmt=fmt, trace_source=args.trace_source)
|
|
45
60
|
except (OSError, ValueError) as exc:
|
|
46
61
|
# The loader raises these with user-facing messages (missing file, not a
|
|
47
62
|
# zip, no worksheet.xml), so print the message rather than a traceback.
|
|
@@ -23,6 +23,8 @@ def convert_worksheet(pkg: McdxPackage) -> ir.Worksheet:
|
|
|
23
23
|
pkg.worksheet_xml,
|
|
24
24
|
text_resolver=resolve_text,
|
|
25
25
|
image_resolver=pkg.image,
|
|
26
|
+
integration_xml=pkg.integration_xml,
|
|
27
|
+
result_xml=pkg.result_xml,
|
|
26
28
|
)
|
|
27
29
|
|
|
28
30
|
|
|
@@ -30,12 +32,17 @@ def convert_file(
|
|
|
30
32
|
path: str | Path,
|
|
31
33
|
*,
|
|
32
34
|
fmt: str = "notebook",
|
|
35
|
+
trace_source: bool = False,
|
|
33
36
|
) -> str:
|
|
34
|
-
"""Convert a ``.mcdx`` file to source. ``fmt`` is ``"notebook"`` or ``"py"``.
|
|
37
|
+
"""Convert a ``.mcdx`` file to source. ``fmt`` is ``"notebook"`` or ``"py"``.
|
|
38
|
+
|
|
39
|
+
``trace_source`` annotates each generated statement with a back-reference
|
|
40
|
+
to its originating Mathcad worksheet region (see ``--trace-source``).
|
|
41
|
+
"""
|
|
35
42
|
pkg = load_mcdx(path)
|
|
36
43
|
ws = convert_worksheet(pkg)
|
|
37
44
|
if fmt == "py":
|
|
38
|
-
return to_python(ws)
|
|
45
|
+
return to_python(ws, trace_source=trace_source)
|
|
39
46
|
if fmt == "notebook":
|
|
40
|
-
return to_ipynb_string(ws)
|
|
47
|
+
return to_ipynb_string(ws, trace_source=trace_source)
|
|
41
48
|
raise ValueError(f"unknown format: {fmt!r} (expected 'notebook' or 'py')")
|
|
@@ -6,18 +6,26 @@ expression printer so we emit only the parentheses Python actually needs.
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
+
import io
|
|
10
|
+
import keyword
|
|
11
|
+
import re
|
|
12
|
+
import tokenize
|
|
13
|
+
from functools import lru_cache
|
|
14
|
+
|
|
9
15
|
from .. import ir
|
|
10
16
|
from ..mapping import (
|
|
11
17
|
BINARY_OPS,
|
|
12
18
|
CONSTANTS,
|
|
13
19
|
FUNCTIONS,
|
|
14
|
-
RUNTIME_IMPORTS,
|
|
15
20
|
UNARY_PREC,
|
|
16
21
|
unit_attr,
|
|
17
22
|
)
|
|
18
23
|
|
|
19
24
|
_ATOM = 100
|
|
20
25
|
|
|
26
|
+
# A matrix literal wider than this is emitted one row per line.
|
|
27
|
+
_WRAP_WIDTH = 88
|
|
28
|
+
|
|
21
29
|
|
|
22
30
|
def expr_to_str(node: ir.Expr) -> str:
|
|
23
31
|
"""Render an expression with no unnecessary outer parentheses."""
|
|
@@ -69,7 +77,13 @@ def _emit(node: ir.Expr) -> tuple[str, int]:
|
|
|
69
77
|
# (``mc_min``/``mc_max``). Element-wise behaviour comes from the
|
|
70
78
|
# vectorize *arrow* applying a function per element, not from min/max --
|
|
71
79
|
# so there's no ``np.minimum``/``np.maximum`` here.
|
|
72
|
-
if node.
|
|
80
|
+
if node.role == "VARIABLE":
|
|
81
|
+
# Mathcad labels a call site VARIABLE (rather than FUNCTION) when
|
|
82
|
+
# the name resolves to a user definition rather than a builtin --
|
|
83
|
+
# including a *redefined* builtin name (``exp(x) := x + 2``), which
|
|
84
|
+
# must call the user's function, not ``math.exp``.
|
|
85
|
+
func = node.func
|
|
86
|
+
elif node.func in ("min", "max"):
|
|
73
87
|
func = "mc_min" if node.func == "min" else "mc_max"
|
|
74
88
|
else:
|
|
75
89
|
func = FUNCTIONS.get(node.func, node.func)
|
|
@@ -88,10 +102,23 @@ def _emit(node: ir.Expr) -> tuple[str, int]:
|
|
|
88
102
|
return f"Eq({expr_to_str(node.lhs)}, {expr_to_str(node.rhs)})", _ATOM
|
|
89
103
|
|
|
90
104
|
if isinstance(node, ir.MatrixLiteral):
|
|
91
|
-
|
|
92
|
-
if node.
|
|
93
|
-
return f"col({
|
|
94
|
-
|
|
105
|
+
parts = [expr_to_str(e) for e in node.elements]
|
|
106
|
+
if node.cols <= 1: # vector -> 1-D array
|
|
107
|
+
return f"col({', '.join(parts)})", _ATOM
|
|
108
|
+
# ``elements`` is column-major (the XML's order); regroup into one list
|
|
109
|
+
# per row so the emitted literal reads like the Mathcad matrix does.
|
|
110
|
+
rows = [
|
|
111
|
+
"[" + ", ".join(parts[j * node.rows + i] for j in range(node.cols)) + "]"
|
|
112
|
+
for i in range(node.rows)
|
|
113
|
+
]
|
|
114
|
+
one_line = f"matrix({', '.join(rows)})"
|
|
115
|
+
# A single row has nothing to line up against, so it never wraps.
|
|
116
|
+
if len(one_line) <= _WRAP_WIDTH or node.rows == 1:
|
|
117
|
+
return one_line, _ATOM
|
|
118
|
+
# Too wide to read: one row per line. The newlines sit inside ``matrix(``'s
|
|
119
|
+
# own parentheses, so this stays a single expression wherever it is nested;
|
|
120
|
+
# ``_reindent`` gives the continuation lines the statement's indent.
|
|
121
|
+
return "matrix(\n" + "".join(f" {row},\n" for row in rows) + ")", _ATOM
|
|
95
122
|
|
|
96
123
|
if isinstance(node, ir.Index):
|
|
97
124
|
base = _wrap(node.base, _ATOM, is_left=True, right_assoc=False)
|
|
@@ -292,7 +319,27 @@ def _block_lines(block: ir.ProgramBlock, indent: int) -> list[str]:
|
|
|
292
319
|
return out
|
|
293
320
|
|
|
294
321
|
|
|
322
|
+
def _reindent(lines: list[str], pad: str) -> list[str]:
|
|
323
|
+
"""Split statements a wrapped matrix literal spread over several lines.
|
|
324
|
+
|
|
325
|
+
The continuation lines already carry their own relative indent (and sit
|
|
326
|
+
inside an open parenthesis, so Python accepts them either way) -- this adds
|
|
327
|
+
the enclosing statement's indent on top, so a wrapped literal inside a
|
|
328
|
+
``def`` lines up with the body rather than the margin.
|
|
329
|
+
"""
|
|
330
|
+
out: list[str] = []
|
|
331
|
+
for line in lines:
|
|
332
|
+
head, *rest = line.split("\n")
|
|
333
|
+
out.append(head)
|
|
334
|
+
out += [pad + cont for cont in rest]
|
|
335
|
+
return out
|
|
336
|
+
|
|
337
|
+
|
|
295
338
|
def _stmt_lines(stmt: ir.Stmt, indent: int) -> list[str]:
|
|
339
|
+
return _reindent(_stmt_lines_raw(stmt, indent), " " * indent)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _stmt_lines_raw(stmt: ir.Stmt, indent: int) -> list[str]:
|
|
296
343
|
pad = " " * indent
|
|
297
344
|
if isinstance(stmt, ir.LocalAssign):
|
|
298
345
|
target, value = stmt.target, stmt.value
|
|
@@ -392,6 +439,89 @@ def index_assign_line(region: ir.IndexAssign) -> str:
|
|
|
392
439
|
return f"{region.target.py} = index_build({idx}, lambda {idx}: {body})"
|
|
393
440
|
|
|
394
441
|
|
|
442
|
+
def recurrence_lines(region: ir.Recurrence) -> list[str]:
|
|
443
|
+
"""Emit a Mathcad difference equation (see :class:`ir.Recurrence`).
|
|
444
|
+
|
|
445
|
+
A **seed** -- every index constant -- is a straight run of ``vec_set`` calls,
|
|
446
|
+
the first write to a name passing ``None`` so the growable helper builds the
|
|
447
|
+
vector from scratch::
|
|
448
|
+
|
|
449
|
+
guess = vec_set(None, 0, 30)
|
|
450
|
+
|
|
451
|
+
A **recurrence** iterates the driving range variable, and goes inside a
|
|
452
|
+
``def`` so that loop variable is function-local: the sheet keeps using the
|
|
453
|
+
range itself further down (``i_range[i] := i``), which a bare ``for i in i:``
|
|
454
|
+
would clobber with the last scalar index. The vectors are passed in and
|
|
455
|
+
returned, so the loop reads exactly the elements written so far::
|
|
456
|
+
|
|
457
|
+
def _recur_guess(_idx, guess):
|
|
458
|
+
for i in _idx:
|
|
459
|
+
guess = vec_set(guess, i + 1, (guess[i] + X / guess[i]) * (1 / 2))
|
|
460
|
+
return guess
|
|
461
|
+
|
|
462
|
+
guess = _recur_guess(i, guess)
|
|
463
|
+
"""
|
|
464
|
+
bases: list[str] = []
|
|
465
|
+
for slot in region.targets:
|
|
466
|
+
if slot.base.py not in bases:
|
|
467
|
+
bases.append(slot.base.py)
|
|
468
|
+
|
|
469
|
+
if region.index is None:
|
|
470
|
+
return _recurrence_writes(region, set(region.create), indent=0)
|
|
471
|
+
|
|
472
|
+
helper = "_recur_" + "_".join(bases)
|
|
473
|
+
lines = [f"{n} = None" for n in region.create]
|
|
474
|
+
lines.append(f"def {helper}(_idx, {', '.join(bases)}):")
|
|
475
|
+
lines.append(f" for {region.index.py} in _idx:")
|
|
476
|
+
lines += _recurrence_writes(region, set(), indent=2)
|
|
477
|
+
lines.append(f" return {', '.join(bases)}")
|
|
478
|
+
lines.append("")
|
|
479
|
+
names = ", ".join(bases)
|
|
480
|
+
lines.append(f"{names} = {helper}({region.index.py}, {names})")
|
|
481
|
+
return lines
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _recurrence_writes(
|
|
485
|
+
region: ir.Recurrence, create: set[str], indent: int
|
|
486
|
+
) -> list[str]:
|
|
487
|
+
"""The ``vec_set`` write per target slot, for one step of the iteration.
|
|
488
|
+
|
|
489
|
+
With more than one target Mathcad updates them **simultaneously**, so the
|
|
490
|
+
step's values are computed into a ``_step`` tuple before any of them is
|
|
491
|
+
written back -- otherwise ``sus[τ+1]``'s right-hand side would read the
|
|
492
|
+
``inf[τ+1]`` this same step just wrote. A lone target needs no such staging,
|
|
493
|
+
and neither does a seed built from a matrix of constants.
|
|
494
|
+
"""
|
|
495
|
+
pad = " " * indent
|
|
496
|
+
lines: list[str] = []
|
|
497
|
+
single = len(region.targets) == 1
|
|
498
|
+
|
|
499
|
+
if single:
|
|
500
|
+
values = [expr_to_str((region.values or [region.value])[0])]
|
|
501
|
+
elif region.values is not None and region.index is None:
|
|
502
|
+
values = [expr_to_str(v) for v in region.values]
|
|
503
|
+
else:
|
|
504
|
+
step = (
|
|
505
|
+
"(" + ", ".join(expr_to_str(v) for v in region.values) + ")"
|
|
506
|
+
if region.values is not None
|
|
507
|
+
else f"tuple({expr_to_str(region.value)})"
|
|
508
|
+
)
|
|
509
|
+
lines.append(f"{pad}_step = {step}")
|
|
510
|
+
values = [f"_step[{i}]" for i in range(len(region.targets))]
|
|
511
|
+
|
|
512
|
+
for slot, value in zip(region.targets, values):
|
|
513
|
+
name = slot.base.py
|
|
514
|
+
index = (
|
|
515
|
+
f"({expr_to_str(slot.index)}, {expr_to_str(slot.col)})"
|
|
516
|
+
if slot.col is not None
|
|
517
|
+
else expr_to_str(slot.index)
|
|
518
|
+
)
|
|
519
|
+
source = "None" if name in create else name
|
|
520
|
+
create.discard(name)
|
|
521
|
+
lines.append(f"{pad}{name} = vec_set({source}, {index}, {value})")
|
|
522
|
+
return _reindent(lines, pad)
|
|
523
|
+
|
|
524
|
+
|
|
395
525
|
def _needs_elementwise(define: ir.Define) -> bool:
|
|
396
526
|
"""True for a *single-argument* scalar function that Mathcad's vectorize
|
|
397
527
|
arrow applies per element: a branching program (``σ_c``) or a *clamp* built
|
|
@@ -487,9 +617,47 @@ def echo_expr(region: ir.Region) -> str | None:
|
|
|
487
617
|
if region.display_unit is not None:
|
|
488
618
|
return _display(f"({base})", region.display_unit)
|
|
489
619
|
return _auto(base, region)
|
|
620
|
+
if isinstance(region, ir.Recurrence):
|
|
621
|
+
if not region.evaluate:
|
|
622
|
+
return None
|
|
623
|
+
# Mathcad shows the slots the equation just wrote. With the driving range
|
|
624
|
+
# variable still bound to its integer array, ``Data[i + N]`` reads them
|
|
625
|
+
# all at once -- the same sub-vector the sheet displays.
|
|
626
|
+
slot = region.targets[0]
|
|
627
|
+
base = (
|
|
628
|
+
f"matelem({slot.base.py}, {expr_to_str(slot.index)}, "
|
|
629
|
+
f"{expr_to_str(slot.col)})"
|
|
630
|
+
if slot.col is not None
|
|
631
|
+
else f"{slot.base.py}[{expr_to_str(slot.index)}]"
|
|
632
|
+
)
|
|
633
|
+
if region.display_unit is not None:
|
|
634
|
+
return _display(f"({base})", region.display_unit)
|
|
635
|
+
return _auto(base, region)
|
|
490
636
|
return None
|
|
491
637
|
|
|
492
638
|
|
|
639
|
+
def guard_cached_error(lines: list[str], region: ir.Region) -> list[str]:
|
|
640
|
+
"""Wrap a region Mathcad itself couldn't compute so the script still runs.
|
|
641
|
+
|
|
642
|
+
``result.xml`` marks these with an ``<engineError>`` -- ``mode(v)`` on data
|
|
643
|
+
with no repeated value is the canonical one, and the sheet often *means* to
|
|
644
|
+
show the error ("Since there are no repeated values, an error is returned").
|
|
645
|
+
The translation is faithful, so it raises too; catching it here keeps the
|
|
646
|
+
generated module running to the end the way the worksheet does, and prints
|
|
647
|
+
Mathcad's own wording alongside.
|
|
648
|
+
"""
|
|
649
|
+
if not region.cached_error or not lines:
|
|
650
|
+
return lines
|
|
651
|
+
body = [f" {line}" if line else line for line in lines]
|
|
652
|
+
return [
|
|
653
|
+
f"# Mathcad reports an error here: {region.cached_error}",
|
|
654
|
+
"try:",
|
|
655
|
+
*body,
|
|
656
|
+
"except Exception as _err:",
|
|
657
|
+
" print('error:', _err)",
|
|
658
|
+
]
|
|
659
|
+
|
|
660
|
+
|
|
493
661
|
def _auto(value: str, region: ir.Region) -> str:
|
|
494
662
|
"""An echo with no display override -- Mathcad's *automatic* display.
|
|
495
663
|
|
|
@@ -574,7 +742,9 @@ def plot_lines(region: ir.Plot) -> list[str]:
|
|
|
574
742
|
y = _plot_axis_call(trace.y, trace.y_unit, domain, _domain_var(region))
|
|
575
743
|
label = expr_to_str(_trace_series(trace, region))
|
|
576
744
|
color = f", color={trace.color!r}" if trace.color else ""
|
|
577
|
-
|
|
745
|
+
# ``plot_trace`` NaN-pads the pair: Mathcad lets a trace's two axes be
|
|
746
|
+
# different lengths (a seeded iteration outruns its index range).
|
|
747
|
+
lines.append(f"_ax.plot(*plot_trace({x}, {y}), label={label!r}{color})")
|
|
578
748
|
lines.append("_ax.axhline(0, color='0.6', linewidth=0.8)")
|
|
579
749
|
lines.append("_ax.axvline(0, color='0.6', linewidth=0.8)")
|
|
580
750
|
lines.append("_ax.grid(True, alpha=0.3)")
|
|
@@ -667,17 +837,35 @@ def _plot_axis_call(
|
|
|
667
837
|
expr: ir.Expr, unit: ir.Expr | None, domain: str | None, domain_var: str
|
|
668
838
|
) -> str:
|
|
669
839
|
"""``plot_axis(<data>, <unit>)`` where data is the domain array directly or
|
|
670
|
-
the expression sampled element-wise over the domain.
|
|
840
|
+
the expression sampled element-wise over the domain.
|
|
841
|
+
|
|
842
|
+
An expression that never mentions the domain variable is **not** a function
|
|
843
|
+
of it, so it isn't sampled: one plot may carry both a parametric trace (two
|
|
844
|
+
data vectors, cached ``TraceType="Vector"``) and a function trace (cached
|
|
845
|
+
``TraceType="Range"``), and the parametric one keeps its own length rather
|
|
846
|
+
than being evaluated once per domain point. ``static_axis`` settles the one
|
|
847
|
+
ambiguous case at runtime -- a *scalar* that ignores the domain is a
|
|
848
|
+
reference line and does span it.
|
|
849
|
+
"""
|
|
671
850
|
if _is_domain(expr, domain):
|
|
672
851
|
data = domain_var
|
|
673
852
|
elif domain is None:
|
|
674
853
|
data = expr_to_str(expr)
|
|
854
|
+
elif not _references(expr, domain):
|
|
855
|
+
data = f"static_axis({expr_to_str(expr)}, {domain_var})"
|
|
675
856
|
else:
|
|
676
857
|
data = f"sample(lambda {domain}: {expr_to_str(expr)}, {domain_var})"
|
|
677
858
|
unit_s = expr_to_str(unit) if unit is not None else "None"
|
|
678
859
|
return f"plot_axis({data}, {unit_s})"
|
|
679
860
|
|
|
680
861
|
|
|
862
|
+
def _references(expr: ir.Expr, name: str) -> bool:
|
|
863
|
+
"""True if ``expr`` reads the variable ``name`` anywhere inside it."""
|
|
864
|
+
return any(
|
|
865
|
+
isinstance(sub, ir.Name) and sub.py == name for sub in _walk(expr)
|
|
866
|
+
)
|
|
867
|
+
|
|
868
|
+
|
|
681
869
|
def _axis_label(region: ir.Plot, *, axis: str) -> str:
|
|
682
870
|
"""A short axis label: the domain name, or the shared unit of that axis."""
|
|
683
871
|
exprs = [(t.x, t.x_unit) for t in region.traces] if axis == "x" else [
|
|
@@ -754,13 +942,28 @@ def _solve_block_body(region: ir.SolveBlock, unknowns: list[str]) -> list[str]:
|
|
|
754
942
|
|
|
755
943
|
# ---------------------------------------------------------------------------
|
|
756
944
|
# Imports needed by a worksheet
|
|
945
|
+
#
|
|
946
|
+
# These are read off the **generated source**, not predicted from the IR. An
|
|
947
|
+
# earlier version walked the IR guessing which helpers the emitted text would
|
|
948
|
+
# name, which meant every new helper had to be registered in two places and a
|
|
949
|
+
# missed registration produced a module that raised ``NameError`` on import --
|
|
950
|
+
# invisible until somebody converted that particular sheet. The text is the
|
|
951
|
+
# ground truth: import exactly the names it references.
|
|
757
952
|
# ---------------------------------------------------------------------------
|
|
758
953
|
|
|
759
954
|
|
|
760
|
-
def header_lines(ws: ir.Worksheet) -> list[str]:
|
|
761
|
-
"""Import/setup lines for the generated module, tailored to what
|
|
955
|
+
def header_lines(ws: ir.Worksheet, source: str) -> list[str]:
|
|
956
|
+
"""Import/setup lines for the generated module, tailored to what it uses.
|
|
957
|
+
|
|
958
|
+
``source`` is the rendered body the header will sit above; the runtime and
|
|
959
|
+
NumPy imports are derived from the identifiers in it, so callers have to
|
|
960
|
+
build the body *first*. It is deliberately required rather than defaulting
|
|
961
|
+
to empty -- a header built without the body would be silently missing every
|
|
962
|
+
runtime import.
|
|
963
|
+
"""
|
|
964
|
+
names = _identifiers(source)
|
|
762
965
|
lines = ["import math"]
|
|
763
|
-
if
|
|
966
|
+
if "np" in names:
|
|
764
967
|
lines.append("import numpy as np")
|
|
765
968
|
if any(isinstance(r, (ir.Plot, ir.GridPlot)) for r in ws.regions):
|
|
766
969
|
lines.append("import matplotlib.pyplot as plt")
|
|
@@ -772,38 +975,86 @@ def header_lines(ws: ir.Worksheet) -> list[str]:
|
|
|
772
975
|
ordered += sorted(sympy_names - set(order))
|
|
773
976
|
lines.append(f"from sympy import {', '.join(ordered)}")
|
|
774
977
|
lines.append("")
|
|
775
|
-
runtime =
|
|
978
|
+
runtime = [n for n in _runtime_exports() if n in names]
|
|
776
979
|
if runtime:
|
|
777
|
-
|
|
778
|
-
*RUNTIME_IMPORTS,
|
|
779
|
-
"col", "matrix", "arange", "index_build", "index_build_2d",
|
|
780
|
-
"vectorize", "transpose", "matmul", "matcol", "total", "vec_set",
|
|
781
|
-
"unpack", "integral", "double_integral", "summation", "solve_block",
|
|
782
|
-
"sample", "plot_domain", "plot_axis", "mesh_grid", "resolve_plot_grid",
|
|
783
|
-
]
|
|
784
|
-
seen: set[str] = set()
|
|
785
|
-
names = ", ".join(
|
|
786
|
-
n for n in order if n in runtime and not (n in seen or seen.add(n))
|
|
787
|
-
)
|
|
788
|
-
lines.append(f"from mcad2py.runtime import {names}")
|
|
980
|
+
lines.append(f"from mcad2py.runtime import {', '.join(runtime)}")
|
|
789
981
|
lines.append("ureg = pint.UnitRegistry()")
|
|
790
982
|
return lines
|
|
791
983
|
|
|
792
984
|
|
|
793
|
-
|
|
794
|
-
|
|
985
|
+
@lru_cache(maxsize=1)
|
|
986
|
+
def _runtime_exports() -> tuple[str, ...]:
|
|
987
|
+
"""Every public helper *defined in* ``runtime.py``, in definition order.
|
|
795
988
|
|
|
796
|
-
|
|
797
|
-
runtime
|
|
798
|
-
|
|
799
|
-
|
|
989
|
+
The ``__module__`` test is what separates the helpers from the modules
|
|
990
|
+
``runtime`` itself imports (``np``, ``math``, ``cmath``), and ``vars()``
|
|
991
|
+
preserves definition order, so the emitted import line stays grouped by
|
|
992
|
+
family -- trig, then vector/matrix, then statistics -- for free. A new
|
|
993
|
+
runtime helper needs no registration anywhere: writing it is enough.
|
|
800
994
|
"""
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
995
|
+
from .. import runtime # local: keeps NumPy off the import path until needed
|
|
996
|
+
|
|
997
|
+
return tuple(
|
|
998
|
+
name
|
|
999
|
+
for name, value in vars(runtime).items()
|
|
1000
|
+
if not name.startswith("_")
|
|
1001
|
+
and getattr(value, "__module__", None) == "mcad2py.runtime"
|
|
1002
|
+
)
|
|
1003
|
+
|
|
1004
|
+
|
|
1005
|
+
def _identifiers(source: str) -> set[str]:
|
|
1006
|
+
"""Every identifier ``source`` names, ignoring strings and comments.
|
|
1007
|
+
|
|
1008
|
+
Tokenizing rather than pattern-matching is what keeps
|
|
1009
|
+
``# TODO unsupported: sort`` from pulling in the ``sort`` helper. A sheet
|
|
1010
|
+
that *redefines* a helper's name still counts as using it -- ``log-exp.mcdx``
|
|
1011
|
+
calls the builtin ``log`` and then shadows it with its own -- so binding is
|
|
1012
|
+
deliberately not considered. The cost is that a sheet with a variable called
|
|
1013
|
+
``total`` or ``rank`` imports a helper it then immediately shadows, which is
|
|
1014
|
+
harmless.
|
|
1015
|
+
"""
|
|
1016
|
+
try:
|
|
1017
|
+
return {
|
|
1018
|
+
token.string
|
|
1019
|
+
for token in tokenize.generate_tokens(io.StringIO(source).readline)
|
|
1020
|
+
if token.type == tokenize.NAME and not keyword.iskeyword(token.string)
|
|
1021
|
+
}
|
|
1022
|
+
except (tokenize.TokenError, IndentationError, SyntaxError):
|
|
1023
|
+
# Unparseable output is a bug elsewhere; an over-broad import list beats
|
|
1024
|
+
# failing the conversion outright (comments and strings leak in here).
|
|
1025
|
+
return set(re.findall(r"[A-Za-z_]\w*", source))
|
|
1026
|
+
|
|
1027
|
+
|
|
1028
|
+
def source_comment(region: ir.Region) -> str | None:
|
|
1029
|
+
"""``# mcdx region <id>`` back-reference, for ``--trace-source``.
|
|
1030
|
+
|
|
1031
|
+
``<id>`` is the originating ``<region>``'s ``region-id`` attribute in
|
|
1032
|
+
``worksheet.xml``. Any defined target whose sanitized Python name differs
|
|
1033
|
+
from Mathcad's original display name is listed too, since that's the name
|
|
1034
|
+
Prime's UI (or MathcadPy) actually knows the value by. If the region is
|
|
1035
|
+
tagged in ``mathcad/integration.xml`` for Application Automation
|
|
1036
|
+
(MathcadPy), the input/output alias is listed as well -- the literal key
|
|
1037
|
+
automation code sets/reads the region by, which can differ from both the
|
|
1038
|
+
Mathcad and Python names (an un-named output defaults to e.g. ``out``).
|
|
1039
|
+
"""
|
|
1040
|
+
if region.source is None:
|
|
1041
|
+
return None
|
|
1042
|
+
text = f"# mcdx region {region.source.region_id}"
|
|
1043
|
+
if region.source.io_kind:
|
|
1044
|
+
text += f', {region.source.io_kind.lower()} alias "{region.source.io_alias}"'
|
|
1045
|
+
renamed = _renamed_targets(region)
|
|
1046
|
+
if renamed:
|
|
1047
|
+
text += ", " + ", ".join(f'"{n.original}" -> {n.py}' for n in renamed)
|
|
1048
|
+
return text
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
def _renamed_targets(region: ir.Region) -> list[ir.Name]:
|
|
1052
|
+
targets: list[ir.Name] = []
|
|
1053
|
+
single = getattr(region, "target", None)
|
|
1054
|
+
if isinstance(single, ir.Name):
|
|
1055
|
+
targets.append(single)
|
|
1056
|
+
targets.extend(getattr(region, "targets", None) or [])
|
|
1057
|
+
return [n for n in targets if n.original != n.py]
|
|
807
1058
|
|
|
808
1059
|
|
|
809
1060
|
def _sympy_imports(ws: ir.Worksheet) -> set[str]:
|
|
@@ -821,112 +1072,6 @@ def _sympy_imports(ws: ir.Worksheet) -> set[str]:
|
|
|
821
1072
|
return names
|
|
822
1073
|
|
|
823
1074
|
|
|
824
|
-
def _used_runtime(ws: ir.Worksheet) -> set[str]:
|
|
825
|
-
"""Runtime-helper names the generated module imports (trig, col, vectorize)."""
|
|
826
|
-
found: set[str] = set()
|
|
827
|
-
integrals: list[ir.Integral] = []
|
|
828
|
-
for region in ws.regions:
|
|
829
|
-
du = getattr(region, "display_unit", None)
|
|
830
|
-
if du is not None and _has_unit(du):
|
|
831
|
-
found.add("disp")
|
|
832
|
-
elif du is None and echo_expr(region) is not None and _has_division(
|
|
833
|
-
getattr(region, "value", None)
|
|
834
|
-
):
|
|
835
|
-
found.add("disp") # automatic display of a possibly-unreduced ratio
|
|
836
|
-
if isinstance(region, ir.Define) and _needs_elementwise(region):
|
|
837
|
-
found.add("elementwise")
|
|
838
|
-
if isinstance(region, ir.SolveBlock):
|
|
839
|
-
found.add("solve_block")
|
|
840
|
-
if isinstance(region, ir.IndexAssign):
|
|
841
|
-
found.add("index_build_2d" if region.col_index is not None else "index_build")
|
|
842
|
-
if isinstance(region, ir.MultiAssign) and region.matrix_target:
|
|
843
|
-
found.add("unpack")
|
|
844
|
-
if isinstance(region, ir.Plot):
|
|
845
|
-
found.update(("sample", "plot_axis"))
|
|
846
|
-
if region.implicit_domain is not None:
|
|
847
|
-
found.add("plot_domain")
|
|
848
|
-
if isinstance(region, ir.GridPlot):
|
|
849
|
-
found.update(("resolve_plot_grid", "plot_axis"))
|
|
850
|
-
if region.mesh_names is not None:
|
|
851
|
-
found.add("mesh_grid")
|
|
852
|
-
for node in _region_exprs(region):
|
|
853
|
-
for sub in _walk(node):
|
|
854
|
-
if isinstance(sub, ir.Call) and sub.func in ("min", "max"):
|
|
855
|
-
found.add("mc_min" if sub.func == "min" else "mc_max")
|
|
856
|
-
for sub in _walk(node):
|
|
857
|
-
if isinstance(sub, ir.Call) and FUNCTIONS.get(sub.func, sub.func) in RUNTIME_IMPORTS:
|
|
858
|
-
found.add(FUNCTIONS.get(sub.func, sub.func))
|
|
859
|
-
elif isinstance(sub, ir.MatrixLiteral):
|
|
860
|
-
found.add("col" if sub.rows <= 1 or sub.cols <= 1 else "matrix")
|
|
861
|
-
elif isinstance(sub, ir.Range):
|
|
862
|
-
found.add("arange")
|
|
863
|
-
elif isinstance(sub, ir.Vectorize):
|
|
864
|
-
found.add("vectorize")
|
|
865
|
-
elif isinstance(sub, ir.Transpose):
|
|
866
|
-
found.add("transpose")
|
|
867
|
-
elif isinstance(sub, ir.Root):
|
|
868
|
-
found.add("nth_root")
|
|
869
|
-
elif (
|
|
870
|
-
isinstance(sub, ir.BinOp)
|
|
871
|
-
and sub.op == "pow"
|
|
872
|
-
and not _is_int_literal(sub.right)
|
|
873
|
-
):
|
|
874
|
-
found.add("power")
|
|
875
|
-
elif isinstance(sub, ir.MatCol):
|
|
876
|
-
found.add("matcol")
|
|
877
|
-
elif isinstance(sub, ir.Index2D):
|
|
878
|
-
found.add("matelem")
|
|
879
|
-
elif isinstance(sub, ir.VectorSum):
|
|
880
|
-
found.add("total")
|
|
881
|
-
elif isinstance(sub, ir.ProgramBlock):
|
|
882
|
-
if _growable_names(sub):
|
|
883
|
-
found.add("vec_set")
|
|
884
|
-
elif isinstance(sub, ir.Integral):
|
|
885
|
-
integrals.append(sub)
|
|
886
|
-
elif isinstance(sub, ir.Summation):
|
|
887
|
-
found.add("summation")
|
|
888
|
-
# A nested (rectangular double) Integral emits one double_integral() call,
|
|
889
|
-
# not two integral() calls -- so its inner Integral isn't independently used.
|
|
890
|
-
nested = {id(n): _nested_double_integral(n) for n in integrals}
|
|
891
|
-
absorbed = {id(inner) for inner in nested.values() if inner is not None}
|
|
892
|
-
for n in integrals:
|
|
893
|
-
if nested[id(n)] is not None:
|
|
894
|
-
found.add("double_integral")
|
|
895
|
-
elif id(n) not in absorbed:
|
|
896
|
-
found.add("integral")
|
|
897
|
-
return found
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
def _region_exprs(region: ir.Region) -> list[ir.Expr]:
|
|
901
|
-
if isinstance(region, ir.Define):
|
|
902
|
-
return [region.value]
|
|
903
|
-
if isinstance(region, (ir.Evaluate, ir.IndexAssign)):
|
|
904
|
-
return [region.value]
|
|
905
|
-
if isinstance(region, ir.MultiAssign):
|
|
906
|
-
return [region.value]
|
|
907
|
-
if isinstance(region, ir.StatusControl):
|
|
908
|
-
return [region.value]
|
|
909
|
-
if isinstance(region, ir.ComboBoxAssign):
|
|
910
|
-
return list(region.values)
|
|
911
|
-
if isinstance(region, ir.SymbolicEquation):
|
|
912
|
-
return [region.equation]
|
|
913
|
-
if isinstance(region, ir.SymbolicEval):
|
|
914
|
-
return [region.expr, *region.args]
|
|
915
|
-
if isinstance(region, ir.SolveBlock):
|
|
916
|
-
exprs: list[ir.Expr] = [g.value for g in region.guesses]
|
|
917
|
-
for c in region.constraints:
|
|
918
|
-
exprs += [c.lhs, c.rhs]
|
|
919
|
-
return exprs
|
|
920
|
-
if isinstance(region, ir.Plot):
|
|
921
|
-
plot_exprs: list[ir.Expr] = []
|
|
922
|
-
for t in region.traces:
|
|
923
|
-
plot_exprs += [t.x, t.y]
|
|
924
|
-
return plot_exprs
|
|
925
|
-
if isinstance(region, ir.GridPlot):
|
|
926
|
-
return [region.expr]
|
|
927
|
-
return []
|
|
928
|
-
|
|
929
|
-
|
|
930
1075
|
def _walk(node: ir.Expr) -> list[ir.Expr]:
|
|
931
1076
|
"""The node and all of its descendant expressions (pre-order)."""
|
|
932
1077
|
out = [node]
|