mcad2py 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.
- mcad2py-0.1.0/LICENSE +21 -0
- mcad2py-0.1.0/MANIFEST.in +22 -0
- mcad2py-0.1.0/PKG-INFO +153 -0
- mcad2py-0.1.0/README.md +116 -0
- mcad2py-0.1.0/mcad2py/__init__.py +16 -0
- mcad2py-0.1.0/mcad2py/cli.py +75 -0
- mcad2py-0.1.0/mcad2py/convert.py +41 -0
- mcad2py-0.1.0/mcad2py/emit/__init__.py +0 -0
- mcad2py-0.1.0/mcad2py/emit/codegen.py +927 -0
- mcad2py-0.1.0/mcad2py/emit/notebook_backend.py +174 -0
- mcad2py-0.1.0/mcad2py/emit/py_backend.py +93 -0
- mcad2py-0.1.0/mcad2py/ir.py +666 -0
- mcad2py-0.1.0/mcad2py/loader.py +130 -0
- mcad2py-0.1.0/mcad2py/mapping.py +204 -0
- mcad2py-0.1.0/mcad2py/parser/__init__.py +0 -0
- mcad2py-0.1.0/mcad2py/parser/expressions.py +436 -0
- mcad2py-0.1.0/mcad2py/parser/namespaces.py +31 -0
- mcad2py-0.1.0/mcad2py/parser/regions.py +829 -0
- mcad2py-0.1.0/mcad2py/runtime.py +1479 -0
- mcad2py-0.1.0/mcad2py/shapes.py +341 -0
- mcad2py-0.1.0/mcad2py/text.py +44 -0
- mcad2py-0.1.0/mcad2py.egg-info/PKG-INFO +153 -0
- mcad2py-0.1.0/mcad2py.egg-info/SOURCES.txt +27 -0
- mcad2py-0.1.0/mcad2py.egg-info/dependency_links.txt +1 -0
- mcad2py-0.1.0/mcad2py.egg-info/entry_points.txt +2 -0
- mcad2py-0.1.0/mcad2py.egg-info/requires.txt +12 -0
- mcad2py-0.1.0/mcad2py.egg-info/top_level.txt +1 -0
- mcad2py-0.1.0/pyproject.toml +62 -0
- mcad2py-0.1.0/setup.cfg +4 -0
mcad2py-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Christian Cruger
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# What ships in the *source* distribution.
|
|
2
|
+
#
|
|
3
|
+
# The wheel is already limited to the mcad2py package by
|
|
4
|
+
# [tool.setuptools.packages.find] in pyproject.toml. The sdist is broader by
|
|
5
|
+
# default -- setuptools sweeps in a top-level tests/ directory on its own -- so
|
|
6
|
+
# the development-only trees are pruned explicitly here.
|
|
7
|
+
#
|
|
8
|
+
# tests/ and references/ are excluded deliberately and go together: every test
|
|
9
|
+
# converts and executes a real .mcdx fixture from references/, so shipping the
|
|
10
|
+
# tests without the ~800 KB of worksheets would only ship something that cannot
|
|
11
|
+
# run. Both stay in the git repo; clone it to run the suite.
|
|
12
|
+
|
|
13
|
+
include README.md
|
|
14
|
+
include LICENSE
|
|
15
|
+
|
|
16
|
+
prune tests
|
|
17
|
+
prune references
|
|
18
|
+
prune docs
|
|
19
|
+
prune .claude
|
|
20
|
+
prune .github
|
|
21
|
+
|
|
22
|
+
global-exclude *.py[cod] __pycache__/* .DS_Store
|
mcad2py-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mcad2py
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Convert PTC Mathcad Prime (.mcdx) worksheets into runnable Jupyter notebooks / Python.
|
|
5
|
+
Author: Christian Cruger
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ChristianCruger/mcad2py
|
|
8
|
+
Project-URL: Repository, https://github.com/ChristianCruger/mcad2py
|
|
9
|
+
Project-URL: Issues, https://github.com/ChristianCruger/mcad2py/issues
|
|
10
|
+
Keywords: mathcad,mcdx,prime,jupyter,units,pint,engineering,converter
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering
|
|
20
|
+
Classifier: Topic :: Software Development :: Code Generators
|
|
21
|
+
Classifier: Topic :: Utilities
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: pint>=0.23
|
|
26
|
+
Requires-Dist: nbformat>=5.9
|
|
27
|
+
Requires-Dist: sympy>=1.12
|
|
28
|
+
Requires-Dist: Pillow>=10
|
|
29
|
+
Requires-Dist: numpy>=1.24
|
|
30
|
+
Requires-Dist: scipy>=1.10
|
|
31
|
+
Requires-Dist: matplotlib>=3.7
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
34
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
35
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
|
|
38
|
+
# mcad2py
|
|
39
|
+
|
|
40
|
+
Convert PTC **Mathcad Prime** worksheets (`.mcdx`) into runnable Python — either a
|
|
41
|
+
**Jupyter notebook** (one region per cell, results echoed inline like Mathcad's `=`) or a
|
|
42
|
+
plain `.py` script. Units are preserved with [Pint](https://pint.readthedocs.io/).
|
|
43
|
+
|
|
44
|
+
A `.mcdx` file is a zip archive of XML; the math is stored as an expression tree, so the
|
|
45
|
+
conversion walks that tree into an intermediate representation and emits Python from it.
|
|
46
|
+
|
|
47
|
+
## Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install mcad2py
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Or from a clone, for development:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
git clone https://github.com/ChristianCruger/mcad2py
|
|
57
|
+
cd mcad2py
|
|
58
|
+
pip install -e ".[dev]"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Requires Python 3.10+. Dependencies: `pint`, `nbformat`, `sympy`, `numpy`, `scipy`,
|
|
62
|
+
`matplotlib`, `Pillow`.
|
|
63
|
+
|
|
64
|
+
## Usage
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Jupyter notebook (default)
|
|
68
|
+
mcad2py convert worksheet.mcdx # -> worksheet.ipynb
|
|
69
|
+
mcad2py convert worksheet.mcdx -o out.ipynb
|
|
70
|
+
|
|
71
|
+
# Plain Python script
|
|
72
|
+
mcad2py convert worksheet.mcdx -f py # -> worksheet.py
|
|
73
|
+
mcad2py convert worksheet.mcdx -o - -f py # to stdout
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Or from Python:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from mcad2py import convert_file
|
|
80
|
+
print(convert_file("worksheet.mcdx", fmt="py"))
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Example
|
|
84
|
+
|
|
85
|
+
A Mathcad region `f_cd := 30 MPa / 1.5 =` (displayed in MPa) becomes, in a notebook cell:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
f_cd = 30 * ureg.MPa / 1.5
|
|
89
|
+
f_cd.to(ureg.MPa) # the bare last line echoes "20 megapascal", like Mathcad's "="
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Mathcad trig handles angle units automatically; generated code matches this via small
|
|
93
|
+
angle-aware helpers (`from mcad2py.runtime import sin, cos, tan, cot`), so
|
|
94
|
+
`tan(phi)` works whether `phi` is in `deg` or `rad`.
|
|
95
|
+
|
|
96
|
+
> **Converted code needs `mcad2py` installed to run.** The output isn't standalone: it
|
|
97
|
+
> imports `mcad2py.runtime` for the unit- and shape-aware helpers that give Mathcad's
|
|
98
|
+
> semantics rather than Python's (angle-aware trig, `matmul`, `index_build`, `solve_block`,
|
|
99
|
+
> …). If you send a converted `.py` or `.ipynb` to someone else, they need `pip install
|
|
100
|
+
> mcad2py` too — along with the dependencies above, since the generated code uses Pint,
|
|
101
|
+
> NumPy, SciPy and matplotlib directly.
|
|
102
|
+
|
|
103
|
+
## What's supported
|
|
104
|
+
|
|
105
|
+
- `:=` definitions and inline `=` evaluations, with display-unit overrides
|
|
106
|
+
- Arithmetic, unit scaling (`30 MPa`), roots, `%`, comparisons and boolean connectives
|
|
107
|
+
- Constants (`π`, `e`, `∞`), Greek/subscripted identifiers (`f_cd`, `β`, `ϕ` → `f_cd`, `beta`, `phi`)
|
|
108
|
+
- **Vectors and matrices** — literals, 0-based indexing (including the two-subscript form),
|
|
109
|
+
ranges, range-built vectors and matrices, and the full built-in family: `rows`/`cols`/`identity`/
|
|
110
|
+
`augment`/`submatrix`, `det`/`lsolve`/`geninv`/`rank`/`rref`, the norm and condition sets, the
|
|
111
|
+
eigen and singular-value set, `sort`/`reverse`. Mathcad's one `·` is resolved into a scalar,
|
|
112
|
+
matrix or dot product by inferring shapes across the whole sheet.
|
|
113
|
+
- **Functions** — the complete trigonometric and hyperbolic families (angle-aware), logs,
|
|
114
|
+
powers and roots, rounding, `min`/`max`, `linterp`
|
|
115
|
+
- **Programs** — inline and block `if`, plus multi-line imperative programs (loops, local `←`
|
|
116
|
+
assignments, `return`, `try`) emitted as real Python `def`s
|
|
117
|
+
- **Solve blocks** — numeric Given/Find (via `scipy.optimize`), including a block that *defines a
|
|
118
|
+
function*; symbolic `solve`/`simplify`/`factor`/`expand` via SymPy
|
|
119
|
+
- **Integrals and sums** — definite and double integrals (`scipy.integrate`), indexed Σ
|
|
120
|
+
- **Plots** — x-y (function and parametric), contour and 3D, rendered with matplotlib
|
|
121
|
+
- **Controls and tables** — ComboBox row selectors, data tables, scriptable controls (via their
|
|
122
|
+
cached value), text/comment regions → markdown cells
|
|
123
|
+
- Images embedded from picture regions
|
|
124
|
+
|
|
125
|
+
Anything not yet handled is emitted as a clearly marked `# TODO unsupported` stub rather than
|
|
126
|
+
dropped, so the output always loads. See
|
|
127
|
+
[docs/mathcad-function-coverage.md](docs/mathcad-function-coverage.md) for the full
|
|
128
|
+
category-by-category map and what's next.
|
|
129
|
+
|
|
130
|
+
## Tests
|
|
131
|
+
|
|
132
|
+
The suite lives in the git repository (it is not part of the published package, since each test
|
|
133
|
+
converts and **executes** a real `.mcdx` fixture from `references/`):
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
git clone https://github.com/ChristianCruger/mcad2py
|
|
137
|
+
cd mcad2py
|
|
138
|
+
pip install -e ".[dev]"
|
|
139
|
+
pytest
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Every test converts a reference worksheet, runs the generated code, and checks the computed
|
|
143
|
+
values against Mathcad's own cached results in that file's `result.xml`.
|
|
144
|
+
|
|
145
|
+
## Scope
|
|
146
|
+
|
|
147
|
+
Targets Mathcad **Prime** (`.mcdx`, `worksheet50`/`math50` schema). Legacy Mathcad 15
|
|
148
|
+
(`.xmcd`) is a future target — the parser is structured behind an intermediate representation
|
|
149
|
+
so a second front-end can be added without changing the code generators.
|
|
150
|
+
|
|
151
|
+
## License
|
|
152
|
+
|
|
153
|
+
MIT — see [LICENSE](LICENSE).
|
mcad2py-0.1.0/README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# mcad2py
|
|
2
|
+
|
|
3
|
+
Convert PTC **Mathcad Prime** worksheets (`.mcdx`) into runnable Python — either a
|
|
4
|
+
**Jupyter notebook** (one region per cell, results echoed inline like Mathcad's `=`) or a
|
|
5
|
+
plain `.py` script. Units are preserved with [Pint](https://pint.readthedocs.io/).
|
|
6
|
+
|
|
7
|
+
A `.mcdx` file is a zip archive of XML; the math is stored as an expression tree, so the
|
|
8
|
+
conversion walks that tree into an intermediate representation and emits Python from it.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install mcad2py
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Or from a clone, for development:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
git clone https://github.com/ChristianCruger/mcad2py
|
|
20
|
+
cd mcad2py
|
|
21
|
+
pip install -e ".[dev]"
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Requires Python 3.10+. Dependencies: `pint`, `nbformat`, `sympy`, `numpy`, `scipy`,
|
|
25
|
+
`matplotlib`, `Pillow`.
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# Jupyter notebook (default)
|
|
31
|
+
mcad2py convert worksheet.mcdx # -> worksheet.ipynb
|
|
32
|
+
mcad2py convert worksheet.mcdx -o out.ipynb
|
|
33
|
+
|
|
34
|
+
# Plain Python script
|
|
35
|
+
mcad2py convert worksheet.mcdx -f py # -> worksheet.py
|
|
36
|
+
mcad2py convert worksheet.mcdx -o - -f py # to stdout
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Or from Python:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from mcad2py import convert_file
|
|
43
|
+
print(convert_file("worksheet.mcdx", fmt="py"))
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Example
|
|
47
|
+
|
|
48
|
+
A Mathcad region `f_cd := 30 MPa / 1.5 =` (displayed in MPa) becomes, in a notebook cell:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
f_cd = 30 * ureg.MPa / 1.5
|
|
52
|
+
f_cd.to(ureg.MPa) # the bare last line echoes "20 megapascal", like Mathcad's "="
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Mathcad trig handles angle units automatically; generated code matches this via small
|
|
56
|
+
angle-aware helpers (`from mcad2py.runtime import sin, cos, tan, cot`), so
|
|
57
|
+
`tan(phi)` works whether `phi` is in `deg` or `rad`.
|
|
58
|
+
|
|
59
|
+
> **Converted code needs `mcad2py` installed to run.** The output isn't standalone: it
|
|
60
|
+
> imports `mcad2py.runtime` for the unit- and shape-aware helpers that give Mathcad's
|
|
61
|
+
> semantics rather than Python's (angle-aware trig, `matmul`, `index_build`, `solve_block`,
|
|
62
|
+
> …). If you send a converted `.py` or `.ipynb` to someone else, they need `pip install
|
|
63
|
+
> mcad2py` too — along with the dependencies above, since the generated code uses Pint,
|
|
64
|
+
> NumPy, SciPy and matplotlib directly.
|
|
65
|
+
|
|
66
|
+
## What's supported
|
|
67
|
+
|
|
68
|
+
- `:=` definitions and inline `=` evaluations, with display-unit overrides
|
|
69
|
+
- Arithmetic, unit scaling (`30 MPa`), roots, `%`, comparisons and boolean connectives
|
|
70
|
+
- Constants (`π`, `e`, `∞`), Greek/subscripted identifiers (`f_cd`, `β`, `ϕ` → `f_cd`, `beta`, `phi`)
|
|
71
|
+
- **Vectors and matrices** — literals, 0-based indexing (including the two-subscript form),
|
|
72
|
+
ranges, range-built vectors and matrices, and the full built-in family: `rows`/`cols`/`identity`/
|
|
73
|
+
`augment`/`submatrix`, `det`/`lsolve`/`geninv`/`rank`/`rref`, the norm and condition sets, the
|
|
74
|
+
eigen and singular-value set, `sort`/`reverse`. Mathcad's one `·` is resolved into a scalar,
|
|
75
|
+
matrix or dot product by inferring shapes across the whole sheet.
|
|
76
|
+
- **Functions** — the complete trigonometric and hyperbolic families (angle-aware), logs,
|
|
77
|
+
powers and roots, rounding, `min`/`max`, `linterp`
|
|
78
|
+
- **Programs** — inline and block `if`, plus multi-line imperative programs (loops, local `←`
|
|
79
|
+
assignments, `return`, `try`) emitted as real Python `def`s
|
|
80
|
+
- **Solve blocks** — numeric Given/Find (via `scipy.optimize`), including a block that *defines a
|
|
81
|
+
function*; symbolic `solve`/`simplify`/`factor`/`expand` via SymPy
|
|
82
|
+
- **Integrals and sums** — definite and double integrals (`scipy.integrate`), indexed Σ
|
|
83
|
+
- **Plots** — x-y (function and parametric), contour and 3D, rendered with matplotlib
|
|
84
|
+
- **Controls and tables** — ComboBox row selectors, data tables, scriptable controls (via their
|
|
85
|
+
cached value), text/comment regions → markdown cells
|
|
86
|
+
- Images embedded from picture regions
|
|
87
|
+
|
|
88
|
+
Anything not yet handled is emitted as a clearly marked `# TODO unsupported` stub rather than
|
|
89
|
+
dropped, so the output always loads. See
|
|
90
|
+
[docs/mathcad-function-coverage.md](docs/mathcad-function-coverage.md) for the full
|
|
91
|
+
category-by-category map and what's next.
|
|
92
|
+
|
|
93
|
+
## Tests
|
|
94
|
+
|
|
95
|
+
The suite lives in the git repository (it is not part of the published package, since each test
|
|
96
|
+
converts and **executes** a real `.mcdx` fixture from `references/`):
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
git clone https://github.com/ChristianCruger/mcad2py
|
|
100
|
+
cd mcad2py
|
|
101
|
+
pip install -e ".[dev]"
|
|
102
|
+
pytest
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Every test converts a reference worksheet, runs the generated code, and checks the computed
|
|
106
|
+
values against Mathcad's own cached results in that file's `result.xml`.
|
|
107
|
+
|
|
108
|
+
## Scope
|
|
109
|
+
|
|
110
|
+
Targets Mathcad **Prime** (`.mcdx`, `worksheet50`/`math50` schema). Legacy Mathcad 15
|
|
111
|
+
(`.xmcd`) is a future target — the parser is structured behind an intermediate representation
|
|
112
|
+
so a second front-end can be added without changing the code generators.
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Convert PTC Mathcad Prime (.mcdx) worksheets to Python / Jupyter notebooks."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version as _version
|
|
4
|
+
|
|
5
|
+
from .convert import convert_file, convert_worksheet
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
# Read the installed distribution's metadata rather than keeping a second
|
|
9
|
+
# copy of the number here: pyproject.toml stays the single source of truth,
|
|
10
|
+
# so the two can't drift (and a release that stamps the version only has to
|
|
11
|
+
# touch one file).
|
|
12
|
+
__version__ = _version("mcad2py")
|
|
13
|
+
except PackageNotFoundError: # imported from a source tree, not installed
|
|
14
|
+
__version__ = "0.0.0.dev0"
|
|
15
|
+
|
|
16
|
+
__all__ = ["convert_file", "convert_worksheet", "__version__"]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Command-line interface: ``mcad2py convert file.mcdx -o out.ipynb``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .convert import convert_file
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv: list[str] | None = None) -> int:
|
|
13
|
+
parser = argparse.ArgumentParser(
|
|
14
|
+
prog="mcad2py",
|
|
15
|
+
description="Convert PTC Mathcad Prime (.mcdx) worksheets to Python / Jupyter.",
|
|
16
|
+
)
|
|
17
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
18
|
+
|
|
19
|
+
conv = sub.add_parser("convert", help="convert a .mcdx file")
|
|
20
|
+
conv.add_argument("input", type=Path, help="path to the .mcdx file")
|
|
21
|
+
conv.add_argument(
|
|
22
|
+
"-o",
|
|
23
|
+
"--output",
|
|
24
|
+
type=Path,
|
|
25
|
+
help="output file; '-' for stdout. Default: input with .ipynb/.py suffix.",
|
|
26
|
+
)
|
|
27
|
+
conv.add_argument(
|
|
28
|
+
"-f",
|
|
29
|
+
"--format",
|
|
30
|
+
choices=["notebook", "py"],
|
|
31
|
+
help="output format (default: inferred from -o suffix, else notebook).",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
args = parser.parse_args(argv)
|
|
35
|
+
if args.command == "convert":
|
|
36
|
+
return _run_convert(args)
|
|
37
|
+
parser.error("unknown command")
|
|
38
|
+
return 2
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _run_convert(args: argparse.Namespace) -> int:
|
|
42
|
+
fmt = args.format or _infer_format(args.output)
|
|
43
|
+
try:
|
|
44
|
+
result = convert_file(args.input, fmt=fmt)
|
|
45
|
+
except (OSError, ValueError) as exc:
|
|
46
|
+
# The loader raises these with user-facing messages (missing file, not a
|
|
47
|
+
# zip, no worksheet.xml), so print the message rather than a traceback.
|
|
48
|
+
# OSError (which FileNotFoundError subclasses) also covers the read
|
|
49
|
+
# failures underneath -- a permission problem, a dead network drive --
|
|
50
|
+
# which are equally not the user's bug to debug.
|
|
51
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
52
|
+
return 1
|
|
53
|
+
|
|
54
|
+
if args.output is None:
|
|
55
|
+
suffix = ".ipynb" if fmt == "notebook" else ".py"
|
|
56
|
+
out_path = args.input.with_suffix(suffix)
|
|
57
|
+
elif str(args.output) == "-":
|
|
58
|
+
sys.stdout.write(result)
|
|
59
|
+
return 0
|
|
60
|
+
else:
|
|
61
|
+
out_path = args.output
|
|
62
|
+
|
|
63
|
+
out_path.write_text(result, encoding="utf-8")
|
|
64
|
+
print(f"wrote {out_path}")
|
|
65
|
+
return 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _infer_format(output: Path | None) -> str:
|
|
69
|
+
if output is not None and output.suffix == ".py":
|
|
70
|
+
return "py"
|
|
71
|
+
return "notebook"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""High-level conversion: ``.mcdx`` -> IR -> notebook / python."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import ir
|
|
8
|
+
from .emit.notebook_backend import to_ipynb_string
|
|
9
|
+
from .emit.py_backend import to_python
|
|
10
|
+
from .loader import McdxPackage, load_mcdx
|
|
11
|
+
from .parser.regions import parse_worksheet
|
|
12
|
+
from .text import extract_text
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def convert_worksheet(pkg: McdxPackage) -> ir.Worksheet:
|
|
16
|
+
"""Parse a loaded package into an IR worksheet (with text resolved)."""
|
|
17
|
+
|
|
18
|
+
def resolve_text(idref: str) -> str:
|
|
19
|
+
data = pkg.text_package(idref)
|
|
20
|
+
return extract_text(data) if data else ""
|
|
21
|
+
|
|
22
|
+
return parse_worksheet(
|
|
23
|
+
pkg.worksheet_xml,
|
|
24
|
+
text_resolver=resolve_text,
|
|
25
|
+
image_resolver=pkg.image,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def convert_file(
|
|
30
|
+
path: str | Path,
|
|
31
|
+
*,
|
|
32
|
+
fmt: str = "notebook",
|
|
33
|
+
) -> str:
|
|
34
|
+
"""Convert a ``.mcdx`` file to source. ``fmt`` is ``"notebook"`` or ``"py"``."""
|
|
35
|
+
pkg = load_mcdx(path)
|
|
36
|
+
ws = convert_worksheet(pkg)
|
|
37
|
+
if fmt == "py":
|
|
38
|
+
return to_python(ws)
|
|
39
|
+
if fmt == "notebook":
|
|
40
|
+
return to_ipynb_string(ws)
|
|
41
|
+
raise ValueError(f"unknown format: {fmt!r} (expected 'notebook' or 'py')")
|
|
File without changes
|