algo2code 0.2.1__py3-none-any.whl → 0.2.2__py3-none-any.whl

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.
algo2code/__init__.py CHANGED
@@ -1,6 +1,6 @@
1
1
  """algo2code — Transpile LaTeX algorithm boxes (algpseudocode) to executable code.
2
2
 
3
- Targets: Taichi (MVP), NumPy, C/PETSc.
3
+ Targets: Taichi, NumPy (C/PETSc planned).
4
4
 
5
5
  Usage:
6
6
  from algo2code import transpile
@@ -8,10 +8,11 @@ Usage:
8
8
  taichi_code = transpile(latex_source, backend='taichi')
9
9
  """
10
10
 
11
- __version__ = "0.2.1"
11
+ __version__ = "0.2.2"
12
12
 
13
13
  from .algo_parser import parse_algorithm
14
14
  from .ast_nodes import Algorithm, VarType
15
+ from .backends.numpy_codegen import generate_numpy
15
16
  from .backends.taichi_codegen import (
16
17
  RUNTIME_INLINE,
17
18
  RUNTIME_TI_RUNTIME,
@@ -33,9 +34,11 @@ def transpile(source: str, backend: str = "taichi", runtime: str = "inline") ->
33
34
  LaTeX source containing \\begin{algorithmic} ... \\end{algorithmic}
34
35
  with optional % directive comments.
35
36
  backend : str
36
- Target backend. Currently only 'taichi' is supported.
37
+ Target backend: ``"taichi"`` (default) or ``"numpy"``. The NumPy
38
+ backend emits a plain function that imports only ``numpy``, so the
39
+ result runs without Taichi installed.
37
40
  runtime : str
38
- Import mode for the Taichi backend. ``"inline"`` (default) emits
41
+ Import mode for the Taichi backend (ignored by ``"numpy"``). ``"inline"`` (default) emits
39
42
  private ``@ti.kernel`` definitions inline. ``"ti_runtime"`` emits
40
43
  ``from ti_runtime import vector_ops as _v`` and calls the shared
41
44
  primitives for dot/norm/copy. algo2code itself never imports
@@ -51,8 +54,9 @@ def transpile(source: str, backend: str = "taichi", runtime: str = "inline") ->
51
54
 
52
55
  if backend == "taichi":
53
56
  return generate_taichi(algo, runtime=runtime)
54
- else:
55
- raise ValueError(f"Unknown backend: {backend!r}. Supported: 'taichi'")
57
+ if backend == "numpy":
58
+ return generate_numpy(algo)
59
+ raise ValueError(f"Unknown backend: {backend!r}. Supported: 'taichi', 'numpy'")
56
60
 
57
61
 
58
62
  __all__ = [
@@ -63,6 +67,7 @@ __all__ = [
63
67
  "Algorithm",
64
68
  "UnsupportedConstructError",
65
69
  "VarType",
70
+ "generate_numpy",
66
71
  "generate_taichi",
67
72
  "get_pcg_algorithm_latex",
68
73
  "infer_types",
@@ -1 +1,154 @@
1
- """NumPy backend (planned)."""
1
+ """
2
+ NumPy code generator.
3
+
4
+ Takes the same typed Algorithm AST as the Taichi backend and emits a plain
5
+ Python function that depends on NumPy only. The generated module never
6
+ imports Taichi, so algorithms transpiled with this backend run on a lean
7
+ install (no ``[verify]`` extra).
8
+
9
+ The lowering mirrors :class:`~algo2code.backends.taichi_codegen.TaichiEmitter`
10
+ statement for statement, so the two backends agree on semantics:
11
+
12
+ - Scalar arithmetic and control flow are emitted exactly as in the Taichi
13
+ driver (plain Python on floats), so a scalar-only algorithm produces the
14
+ same function body under both backends and yields bit-identical results.
15
+ - Vector/matrix variables are ``numpy.ndarray`` buffers. Local working
16
+ vectors are allocated once with ``np.zeros(n)`` and every vector operation
17
+ writes *in place* (``out[...] = ...``), matching the Taichi field model:
18
+ a vector argument updated by the algorithm is updated for the caller too.
19
+ - Callables keep the in-place seam contract of the Taichi backend:
20
+ ``M_inv(r, z)`` writes into ``z``, and a matrix-free operator declared
21
+ ``% type A callable`` is applied as ``A(out, p)``.
22
+ - ``dot`` lowers to ``float(np.dot(a, b))``, ``norm`` to
23
+ ``float(np.linalg.norm(a))``, a stored-matrix product to ``A @ x``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from ..ast_nodes import Algorithm, Assign, BinOp, Expr, FuncCall, UnaryOp, Var, VarType
29
+ from ..errors import UnsupportedConstructError
30
+ from .taichi_codegen import (
31
+ RUNTIME_INLINE,
32
+ TaichiEmitter,
33
+ _collect_arg_names,
34
+ _collect_vector_vars,
35
+ _var_name,
36
+ )
37
+
38
+
39
+ class NumpyEmitter(TaichiEmitter):
40
+ """Emit a NumPy-only Python function from a typed Algorithm AST."""
41
+
42
+ BACKEND_DOC = "Backend: NumPy (CPU)"
43
+
44
+ def __init__(self, algo: Algorithm):
45
+ super().__init__(algo, runtime=RUNTIME_INLINE)
46
+
47
+ def emit(self) -> str:
48
+ """Generate the complete NumPy source."""
49
+ self._arg_names = _collect_arg_names(self.algo)
50
+ self._vector_vars = _collect_vector_vars(self.algo)
51
+ self._pre_scan_temps(self.algo.body)
52
+
53
+ parts = ["import numpy as np\n", "# ── Solver driver " + "─" * 57, self._emit_driver()]
54
+ return "\n\n".join(parts) + "\n"
55
+
56
+ # ── Allocation ───────────────────────────────────────────────────────
57
+
58
+ def _vector_field_alloc(self, vec_arg: str | None) -> str:
59
+ return "np.zeros(n)"
60
+
61
+ # ── Expressions ──────────────────────────────────────────────────────
62
+
63
+ def _emit_assign(self, stmt: Assign) -> None:
64
+ target = _var_name(stmt.target)
65
+ target_type = self.algo.type_annotations.get(stmt.target.display, stmt.target.inferred_type)
66
+ if (
67
+ target_type == VarType.VECTOR
68
+ and isinstance(stmt.value, Var)
69
+ and stmt.value.inferred_type == VarType.VECTOR
70
+ ):
71
+ self._write(f"{target}[...] = {_var_name(stmt.value)}")
72
+ return
73
+ super()._emit_assign(stmt)
74
+
75
+ def _emit_unary(self, expr: UnaryOp) -> str:
76
+ if expr.op == "norm" and expr.operand.inferred_type != VarType.SCALAR:
77
+ return f"float(np.linalg.norm({self._emit_expr_str(expr.operand)}))"
78
+ return super()._emit_unary(expr)
79
+
80
+ def _emit_dot(self, expr: BinOp) -> str:
81
+ left = expr.left
82
+ if isinstance(left, UnaryOp) and left.op == "transpose":
83
+ left = left.operand
84
+ return f"float(np.dot({self._emit_expr_str(left)}, {self._emit_expr_str(expr.right)}))"
85
+
86
+ def _emit_func_call_name(self, expr: FuncCall) -> str:
87
+ if isinstance(expr.func, Var) and _var_name(expr.func) == "sqrt":
88
+ return "np.sqrt"
89
+ return super()._emit_func_call_name(expr)
90
+
91
+ # ── Vector lowering (in-place writes into ndarray buffers) ───────────
92
+
93
+ def _lower_vector_expr(self, expr: Expr, dest: str | None) -> str:
94
+ if isinstance(expr, Var):
95
+ name = _var_name(expr)
96
+ if dest is not None and dest != name:
97
+ self._write(f"{dest}[...] = {name}")
98
+ return dest
99
+ return name
100
+
101
+ if isinstance(expr, FuncCall):
102
+ out = dest if dest is not None else self._get_temp()
103
+ func = self._emit_func_call_name(expr)
104
+ args = ", ".join(self._emit_expr_str(a) for a in expr.args)
105
+ self._write(f"{func}({args}, {out})")
106
+ return out
107
+
108
+ if isinstance(expr, UnaryOp) and expr.op == "neg":
109
+ vec = self._lower_to_field(expr.operand)
110
+ out = dest if dest is not None else self._get_temp()
111
+ self._write(f"{out}[...] = -{vec}")
112
+ return out
113
+
114
+ if isinstance(expr, BinOp):
115
+ if expr.op == "matvec":
116
+ out = dest if dest is not None else self._get_temp()
117
+ vec = self._lower_to_field(expr.right)
118
+ if expr.left.inferred_type == VarType.CALLABLE:
119
+ self._write(f"{self._emit_expr_str(expr.left)}({out}, {vec})")
120
+ return out
121
+ self._write(f"{out}[...] = {self._emit_expr_str(expr.left)} @ {vec}")
122
+ return out
123
+
124
+ if expr.op in ("scale", "*"):
125
+ scalar, vec_expr = self._split_scale(expr)
126
+ if scalar is not None and vec_expr is not None:
127
+ vec = self._lower_to_field(vec_expr)
128
+ out = dest if dest is not None else self._get_temp()
129
+ self._write(f"{out}[...] = {scalar} * {vec}")
130
+ return out
131
+
132
+ if expr.op in ("+", "-"):
133
+ left = self._lower_to_field(expr.left)
134
+ coeff, right = self._lower_addend(expr.right)
135
+ beta = self._negate(coeff) if expr.op == "-" else coeff
136
+ out = dest if dest is not None else self._get_temp()
137
+ self._write(f"{out}[...] = {left} + {beta} * {right}")
138
+ return out
139
+
140
+ raise UnsupportedConstructError(
141
+ f"cannot lower vector expression to NumPy ops: {expr!r}. "
142
+ f"Supported vector forms are copy, callable application, matvec, "
143
+ f"scalar*vector, and vector +/- vector."
144
+ )
145
+
146
+
147
+ def generate_numpy(algo: Algorithm) -> str:
148
+ """Generate NumPy source code from a typed Algorithm AST.
149
+
150
+ The emitted module imports only ``numpy`` and defines one function named
151
+ after the algorithm, with the same signature and return values as the
152
+ Taichi backend's driver.
153
+ """
154
+ return NumpyEmitter(algo).emit()
@@ -18,9 +18,9 @@ Import modes (``runtime`` parameter of :func:`generate_taichi`):
18
18
  each generated file — backward-compatible, no runtime dependency.
19
19
  - ``"ti_runtime"``: emit ``from ti_runtime import vector_ops as _v`` and call
20
20
  the shared primitives for ``dot``/``norm``/``copy``/``vec_add``; only
21
- ``_matvec`` remains inlined (the matrix-free operator seam is P2-2's
22
- concern). algo2code itself never imports ``ti_runtime`` — it only *emits*
23
- the import line.
21
+ ``_matvec`` remains inlined (the matrix-free operator is injected through
22
+ the seam by the consumer). algo2code itself never imports ``ti_runtime`` —
23
+ it only *emits* the import line.
24
24
 
25
25
  Compatibility note (``"ti_runtime"`` mode):
26
26
  ``ti_runtime.vector_ops.dot`` uses ``x[I].dot(y[I])`` which requires
@@ -29,7 +29,7 @@ Compatibility note (``"ti_runtime"`` mode):
29
29
  the consumer passes scalar fields. Callers that use vector fields (e.g.
30
30
  mechdsl FEM drivers) are unaffected. This is a known field-model mismatch;
31
31
  resolving it (either by changing the emitted field model to ``ti.Vector.field``
32
- or by adding scalar variants to ti_runtime) is out of scope for P2-1.
32
+ or by adding scalar variants to ti_runtime) is out of scope for this backend.
33
33
  """
34
34
 
35
35
  from __future__ import annotations
@@ -177,7 +177,7 @@ class KernelCollector:
177
177
  In ``"ti_runtime"`` mode the shared primitives (dot/norm/copy/vec_add)
178
178
  are called via the ``_v`` alias imported from ``ti_runtime.vector_ops``.
179
179
  Only ``_matvec`` has no ti_runtime equivalent and remains inlined
180
- (the matrix-free operator seam is P2-2's concern).
180
+ (the matrix-free operator is injected through the seam by the consumer).
181
181
  """
182
182
  lines = []
183
183
  if runtime == RUNTIME_TI_RUNTIME:
@@ -266,6 +266,9 @@ class TaichiEmitter:
266
266
  docstring for the full description of each mode.
267
267
  """
268
268
 
269
+ #: Backend line written into the generated driver's docstring.
270
+ BACKEND_DOC = "Backend: Taichi (GPU)"
271
+
269
272
  def __init__(self, algo: Algorithm, runtime: str = RUNTIME_INLINE):
270
273
  self.algo = algo
271
274
  self.runtime = runtime
@@ -341,7 +344,7 @@ class TaichiEmitter:
341
344
 
342
345
  self._write('"""')
343
346
  self._write("Auto-generated from LaTeX algorithmic environment.")
344
- self._write("Backend: Taichi (GPU)")
347
+ self._write(self.BACKEND_DOC)
345
348
  self._write('"""')
346
349
 
347
350
  vec_arg = self._first_vector_arg()
@@ -394,8 +397,8 @@ class TaichiEmitter:
394
397
  locals matching the *vector argument's* component layout (``<arg>.n``):
395
398
  the ``ti_runtime`` ``dot``/``norm2`` primitives use ``x[I].dot(y[I])``,
396
399
  which requires vector fields. This is what lets the matrix-free seam
397
- (P2-2) run end-to-end against ``ti_runtime`` (resolving the field-model
398
- mismatch P2-1 documented). With no vector argument the component count
400
+ run end-to-end against ``ti_runtime`` (resolving the field-model
401
+ mismatch documented above). With no vector argument the component count
399
402
  is unknown, so fall back to the scalar layout.
400
403
  """
401
404
  if self.runtime == RUNTIME_TI_RUNTIME and vec_arg is not None:
@@ -847,7 +850,8 @@ def generate_taichi(algo: Algorithm, runtime: str = RUNTIME_INLINE) -> str:
847
850
  ``"ti_runtime"``
848
851
  Emit ``from ti_runtime import vector_ops as _v`` and call the
849
852
  shared primitives for dot/norm/copy/vec_add. Only ``_matvec``
850
- remains inlined (the matrix-free operator seam is P2-2's concern).
853
+ remains inlined (the matrix-free operator is injected through the
854
+ seam by the consumer).
851
855
  algo2code itself never imports ti_runtime — it only emits the
852
856
  import line.
853
857
 
algo2code/expr_parser.py CHANGED
@@ -225,8 +225,7 @@ class ExprParser:
225
225
 
226
226
  Division at the term level shares precedence with multiplication
227
227
  (left-associative) so ``a + b / c`` parses as ``a + (b / c)``
228
- rather than dropping the divisor. post_recovery_plan Phase 5
229
- parser fix.
228
+ rather than dropping the divisor.
230
229
  """
231
230
  left = self.parse_signed_factor()
232
231
  while True:
@@ -6,14 +6,25 @@ small helper that returns it (and, where the parser supports it, the parsed
6
6
  here instead of re-typing or re-inventing the algorithm text — this is the
7
7
  canonical hand-off seam between ``algo2code`` and any consumer that wants a
8
8
  reference implementation of a textbook iterative solver.
9
+
10
+ The verbatim ``.tex`` sources live in ``algo2code/library/algorithms/`` and
11
+ ship as package data; :func:`algorithm_source` reads any of them by name.
9
12
  """
10
13
 
11
14
  from algo2code.library.pcg import (
12
15
  PCG_ALGORITHM_LATEX,
13
16
  get_pcg_algorithm_latex,
14
17
  )
18
+ from algo2code.library.sources import (
19
+ ALGORITHM_SOURCES,
20
+ algorithm_source,
21
+ algorithm_source_path,
22
+ )
15
23
 
16
24
  __all__ = [
25
+ "ALGORITHM_SOURCES",
17
26
  "PCG_ALGORITHM_LATEX",
27
+ "algorithm_source",
28
+ "algorithm_source_path",
18
29
  "get_pcg_algorithm_latex",
19
30
  ]
@@ -0,0 +1,51 @@
1
+ % Point-Jacobi preconditioner apply.
2
+ %
3
+ % Computes the Jacobi (diagonal) preconditioned vector:
4
+ %
5
+ % z_I = r_I / max(d_I, eps)
6
+ %
7
+ % where ``d`` is the diagonal of the system matrix (point-Jacobi: M = diag(d)),
8
+ % ``r`` is the residual vector, ``z`` is the output (M^{-1} r), and ``eps`` is a
9
+ % small positive guard against near-zero diagonal entries. All operands are
10
+ % degree-of-freedom vectors (one value per node or per component).
11
+ %
12
+ % Grammar note:
13
+ % -------------
14
+ % algo2code currently lowers vector/vector division (`z = r / d`) to the Python
15
+ % expression `z = (r / d)`, which is not runnable for `ti.Vector.field` operands
16
+ % (Taichi raises TypeError: unsupported operand type(s) for /: MatrixField /
17
+ % MatrixField). The grammar supports scalar operations and vector +/-/scale/
18
+ % callable-matvec, but has no `vec_ediv` (elementwise divide) primitive.
19
+ %
20
+ % The clean fix is a new `vec_ediv(z, r, d, eps)` primitive in ti_runtime
21
+ % vector_ops. The generated body below is therefore
22
+ % realised as a thin `@ti.data_oriented` adapter
23
+ % (`mechdsl.solver.jacobi_preconditioner.GeneratedJacobiPreconditioner`) whose
24
+ % `_apply` kernel calls `ti_runtime.vector_ops.ediv(z, r, d, eps)` — a
25
+ % generated body in the sense that the algorithm is expressed in LaTeX and
26
+ % realised via a structured adapter, not hand-coded heuristics.
27
+ %
28
+ % When algo2code gains a `vec_ediv` primitive (or scalar-field elementwise ops),
29
+ % this box can be re-transpiled to a fully auto-generated driver with no adapter
30
+ % shim.
31
+ %
32
+ % Inputs
33
+ % ------
34
+ % r : residual vector (numerator)
35
+ % d : diagonal vector (denominator)
36
+ % eps : small positive guard (scalar) -- assumed positive (SPD diagonal guard)
37
+ %
38
+ % Output
39
+ % ------
40
+ % z : preconditioned vector = M^{-1} r
41
+
42
+ % algorithm jacobi_apply
43
+ % backend taichi
44
+ % args r:vector, d:vector, eps:scalar
45
+
46
+ % type z vector
47
+
48
+ \begin{algorithmic}
49
+ \State $z_I = r_I \, / \, \max(d_I,\, \varepsilon)$ \Comment{elementwise; for all DOF indices $I$}
50
+ \Return $z$
51
+ \end{algorithmic}
@@ -0,0 +1,99 @@
1
+ % Newmark-beta implicit time integration — single step.
2
+ %
3
+ % The canonical Newmark-beta step authored for the **all-Taichi on-device
4
+ % time-integration seam path** (the temporal analogue of the matrix-free PCG in
5
+ % ``pcg.tex``): the per-step acceleration solve ``solve_a`` is a *callable*
6
+ % (matrix-free), so this box transpiles via
7
+ % ``algo2code.transpile(..., runtime='ti_runtime')`` into a body that advances a
8
+ % dynamic state ``(u, v, a)`` one step over ``ti.Vector.field`` DOF vectors
9
+ % **without NumPy in the hot path** — every update is a ``ti_runtime.vector_ops``
10
+ % AXPBY/copy call and the only non-primitive call is the injected ``solve_a``.
11
+ %
12
+ % Scheme (Hughes 2000, Box 9.1; Newmark 1959)
13
+ % -------------------------------------------
14
+ % For the semidiscrete equation of motion ``M a + C v + K u = F`` the Newmark
15
+ % family advances ``(u_n, v_n, a_n) -> (u_{n+1}, v_{n+1}, a_{n+1})`` via the
16
+ % predictor/corrector split:
17
+ %
18
+ % predictors (known from step n):
19
+ % u_pred = u_n + dt*v_n + dt^2*(1/2 - beta)*a_n
20
+ % v_pred = v_n + dt*(1 - gamma)*a_n
21
+ %
22
+ % acceleration solve (the only system solve — folded into the callable):
23
+ % a_{n+1} = solve_a(u_pred, v_pred)
24
+ % i.e. solve (M + gamma*dt*C + beta*dt^2*K) a_{n+1}
25
+ % = F_{n+1} - C*v_pred - K*u_pred
26
+ %
27
+ % correctors:
28
+ % u_{n+1} = u_pred + beta*dt^2 * a_{n+1}
29
+ % v_{n+1} = v_pred + gamma*dt * a_{n+1}
30
+ %
31
+ % gamma = 1/2 gives second-order accuracy; beta = 1/4 (with gamma = 1/2) is the
32
+ % average-acceleration / trapezoidal rule — unconditionally stable, no numerical
33
+ % damping. HHT-alpha is a one-parameter generalisation (alpha-weighted residual);
34
+ % it reuses the same predictor/corrector skeleton and is intentionally NOT
35
+ % authored here — Newmark-beta is the deliverable, HHT is optional/next.
36
+ %
37
+ % Seam contract (mirrors ti_runtime.seams.TimeIntegrationContext)
38
+ % ---------------------------------------------------------------
39
+ % solve_a(u_pred, v_pred, a_out) — acceleration solve: a_out = a_{n+1}
40
+ % (out LAST; the in-place callable convention,
41
+ % same shape as the PCG operator A(out, x)).
42
+ % The callable owns the mass / damping / stiffness / external-force data; the box
43
+ % is mass-/material-agnostic, exactly like ``pcg.tex`` is operator-agnostic.
44
+ %
45
+ % Grammar note
46
+ % ------------
47
+ % This box transpiles **directly** through algo2code in ``runtime='ti_runtime'``
48
+ % mode with no grammar gap: the predictor/corrector updates are all
49
+ % ``scalar*vector`` and ``vector +/- vector`` (fused ``_v.vec_add`` AXPBY calls),
50
+ % the scalar coefficients ``c0..c3`` are plain scalar arithmetic, and the
51
+ % acceleration solve is an in-place ``callable`` (``solve_a``) — the matrix-free
52
+ % seam form (11-ALGO2CODE §8.3). No NumPy, no dense ``_matvec``. (Verified: the
53
+ % emitted ``newmark_step`` body contains only ``_v.vec_add`` / ``_v.copy`` /
54
+ % ``solve_a(...)``.)
55
+ %
56
+ % The two predictor scalar coefficients are precomputed into named scalars
57
+ % (``c0``, ``c1``) and the corrector coefficients into (``c2``, ``c3``) so each
58
+ % vector update fuses to a single AXPBY; ``dt`` itself is the predictor velocity
59
+ % coefficient (``u + dt*v``).
60
+ %
61
+ % Inputs
62
+ % ------
63
+ % u : displacement vector at step n (carries the state; updated in place)
64
+ % v : velocity vector at step n (updated in place)
65
+ % a : acceleration vector at step n (updated in place)
66
+ % solve_a : acceleration solve (callable, in-place ``solve_a(u_pred, v_pred, a_out)``)
67
+ % dt : time step (scalar)
68
+ % beta : Newmark beta (scalar; 1/4 = average acceleration)
69
+ % gamma : Newmark gamma (scalar; 1/2 = second order, no algorithmic damping)
70
+ %
71
+ % Output
72
+ % ------
73
+ % u, v, a — the advanced state (u_{n+1}, v_{n+1}, a_{n+1})
74
+
75
+ % algorithm newmark_step
76
+ % backend taichi
77
+ % args u:vector, v:vector, a:vector, solve_a:callable, dt:scalar, beta:scalar, gamma:scalar
78
+
79
+ % type u_pred vector
80
+ % type v_pred vector
81
+ % type a_new vector
82
+ % type c_0 scalar
83
+ % type c_1 scalar
84
+ % type c_2 scalar
85
+ % type c_3 scalar
86
+
87
+ \begin{algorithmic}
88
+ \State $c_0 = dt \cdot dt \cdot (0.5 - \beta)$ % scalar
89
+ \State $c_1 = dt \cdot (1 - \gamma)$ % scalar
90
+ \State $c_2 = \beta \cdot dt \cdot dt$ % scalar
91
+ \State $c_3 = \gamma \cdot dt$ % scalar
92
+ \State $u_{\text{pred}} = u + dt \cdot v + c_0 \cdot a$ % vector
93
+ \State $v_{\text{pred}} = v + c_1 \cdot a$ % vector
94
+ \State $a_{\text{new}} = \text{solve\_a}(u_{\text{pred}}, v_{\text{pred}})$ % vector
95
+ \State $u = u_{\text{pred}} + c_2 \cdot a_{\text{new}}$ % vector
96
+ \State $v = v_{\text{pred}} + c_3 \cdot a_{\text{new}}$ % vector
97
+ \State $a = a_{\text{new}}$ % vector
98
+ \Return $u, v, a$
99
+ \end{algorithmic}
@@ -0,0 +1,103 @@
1
+ % Matrix-free Preconditioned Conjugate Gradient (PCG).
2
+ %
3
+ % The canonical PCG algorithm authored for the **all-Taichi on-device seam path**:
4
+ % the operator ``A`` and the preconditioner ``M_inv`` are both
5
+ % *callables* (matrix-free), so this box transpiles via
6
+ % ``algo2code.transpile(..., runtime='ti_runtime')`` into a body that solves
7
+ % ``A x = b`` over ``ti.Vector.field`` DOF vectors without ever forming or storing
8
+ % a matrix and without NumPy in the hot path.
9
+ %
10
+ % Provenance
11
+ % ----------
12
+ % Identical in algorithm to the canonical PCG LaTeX
13
+ % (``algo2code.library.pcg.PCG_ALGORITHM_LATEX`` / the hand twin
14
+ % ``mechdsl.solver.import_adapter.Algo2CodePCGSolver``) and to the matrix-free
15
+ % ``_CALLABLE_PCG_LATEX`` proven runnable in runtime mode. The *only* surface change vs
16
+ % the canonical box is the operator type:
17
+ %
18
+ % canonical: ``% args A:matrix, ... apply_M_inv:callable, ...``
19
+ % here: ``% args A:callable, ... M_inv:callable, ...``
20
+ %
21
+ % A matrix ``A`` lowers to a dense scalar-indexed ``_matvec`` (incompatible with
22
+ % the ``ti.Vector.field`` layout the seam uses); a callable ``A`` lowers to the
23
+ % in-place ``A(out, p)`` operator call — the ``ti_runtime`` ``apply_A(out, x)``
24
+ % seam contract. The runtime-mode guard requires exactly this: a callable
25
+ % operator + a vector argument.
26
+ %
27
+ % Seam contract (mirrors ti_runtime.seams.LinearSolveContext)
28
+ % -----------------------------------------------------------
29
+ % A(out, x) — operator: out = A @ x (out FIRST)
30
+ % M_inv(r, z) — preconditioner: z = M^{-1} r (out LAST)
31
+ %
32
+ % This box productionizes the spike's hand-written ``pcg`` body
33
+ % (``packages/mechdsl-core/tests/spike/svk_hex8_taichi.py``): the generated body
34
+ % maps line-for-line to that hand-written PCG, but is *derived from LaTeX* rather
35
+ % than hand-coded.
36
+ %
37
+ % Inputs
38
+ % ------
39
+ % A : matrix-free operator (callable, in-place ``A(out, x)``)
40
+ % b : right-hand side vector
41
+ % x : solution vector (carries the initial guess; solved in place)
42
+ % M_inv : preconditioner apply (callable, in-place ``M_inv(r, z)``)
43
+ % tol : relative convergence tolerance (scalar)
44
+ % maxiter : maximum iteration count (scalar)
45
+ %
46
+ % Output
47
+ % ------
48
+ % x, iterations, residual_norm, converged
49
+ %
50
+ % ``converged`` is a hard non-convergence flag: literal ``1`` on the two
51
+ % success returns (the ``r_0 = 0`` early-out and the in-loop tolerance hit),
52
+ % literal ``0`` on maxiter exhaustion and on the ``|pq| < 1e-300`` breakdown
53
+ % (which ``break``s out of the loop and falls through to the maxiter return).
54
+ % A caller that sees ``converged == 0`` must NOT consume ``x`` -- the inner
55
+ % solve failed and ``x`` is garbage (see seam_solve.make_seam_solver, which
56
+ % raises rather than letting a Newton step advance on it).
57
+
58
+ % algorithm pcg
59
+ % backend taichi
60
+ % args A:callable, b:vector, x:vector, M_inv:callable, tol:scalar, maxiter:scalar
61
+
62
+ % type r vector
63
+ % type z vector
64
+ % type p vector
65
+ % type q vector
66
+ % type rho scalar
67
+ % type rho_new scalar
68
+ % type alpha scalar
69
+ % type beta scalar
70
+ % type pq scalar
71
+ % type r0_norm scalar
72
+ % type r_norm scalar
73
+
74
+ \begin{algorithmic}
75
+ \State $r = b - A \cdot x$ % vector
76
+ \State $r_0 = \lVert r \rVert_2$ % scalar
77
+ \If{$r_0 = 0$}
78
+ \Return $x, 0, 0, 1$
79
+ \EndIf
80
+ \State $z = M^{-1}(r)$ % vector
81
+ \State $p = z$ % vector
82
+ \State $\rho = r^\top z$ % scalar
83
+ \For{$k = 1, 2, \ldots, \text{maxiter}$}
84
+ \State $q = A \cdot p$ % vector
85
+ \State $pq = p^\top q$ % scalar
86
+ \If{$|pq| < 10^{-300}$}
87
+ \State \textbf{break}
88
+ \EndIf
89
+ \State $\alpha = \frac{\rho}{pq}$ % scalar
90
+ \State $x = x + \alpha \, p$ % vector
91
+ \State $r = r - \alpha \, q$ % vector
92
+ \State $r_n = \lVert r \rVert_2$ % scalar
93
+ \If{$r_n < \text{tol} \cdot r_0$}
94
+ \Return $x, k, r_n, 1$
95
+ \EndIf
96
+ \State $z = M^{-1}(r)$ % vector
97
+ \State $\rho_{\text{new}} = r^\top z$ % scalar
98
+ \State $\beta = \frac{\rho_{\text{new}}}{\rho}$ % scalar
99
+ \State $p = z + \beta \, p$ % vector
100
+ \State $\rho = \rho_{\text{new}}$ % scalar
101
+ \EndFor
102
+ \Return $x, \text{maxiter}, \lVert r \rVert_2, 0$
103
+ \end{algorithmic}
@@ -0,0 +1,79 @@
1
+ % J2 radial-return algpseudocode source.
2
+ %
3
+ % Scalar Newton inner loop for J2 plasticity with power-law isotropic
4
+ % hardening. Solves for the plastic multiplier increment dl given the
5
+ % trial von Mises equivalent stress, the prior accumulated equivalent
6
+ % plastic strain, and the material parameters:
7
+ %
8
+ % sigma_y(alpha) = sigy0 + K * alpha^n
9
+ %
10
+ % The scalar loop operates on the trial-stress / hardening axes only;
11
+ % all tensor algebra (deviatoric stress, von Mises, return-mapping
12
+ % reconstruction, algorithmic tangent) is orchestrated in Python by the
13
+ % mechdsl-core wrapper at packages/mechdsl-core/src/mechdsl/lib/plasticity.py.
14
+ %
15
+ % This is the production algo2code source consumed by
16
+ % ``mechdsl.lib.plasticity.radial_return`` via ``algo2code.transpile``
17
+ % (the algo2code expr_parser bugs that previously deferred direct emission
18
+ % were fixed alongside this source). Bit-equality with the imported reference
19
+ % path is asserted by
20
+ % ``packages/mechdsl-core/tests/test_j2_radial_return_parity.py``.
21
+ %
22
+ % Inputs
23
+ % ------
24
+ % sigma_eq : von Mises equivalent of the trial deviatoric stress
25
+ % alpha : alpha_old, prior accumulated equivalent plastic strain
26
+ % mu : shear modulus (second Lame parameter)
27
+ % K : isotropic hardening modulus
28
+ % n : power-law exponent
29
+ % sigy0 : initial yield stress
30
+ % tol : Newton residual tolerance (passed through; the fixed-
31
+ % iteration loop converges quadratically and the wrapper
32
+ % applies the imported reference tolerance externally)
33
+ % max_iter : Newton max iterations
34
+ %
35
+ % Outputs
36
+ % -------
37
+ % plastic : 1 if plastic flow occurred, 0 if elastic step
38
+ % alpha_new : alpha_old + delta_lambda (when plastic)
39
+ % dl : plastic multiplier increment (delta_lambda)
40
+
41
+ % algorithm radial_return_j2
42
+ % backend taichi
43
+ % args sigma_eq:scalar, alpha:scalar, mu:scalar, K:scalar, n:scalar, sigy0:scalar, tol:scalar, max_iter:scalar
44
+
45
+ % type sy scalar
46
+ % type f scalar
47
+ % type dl scalar
48
+ % type k scalar
49
+ % type Hp scalar
50
+ % type res scalar
51
+ % type denom scalar
52
+ % type ap scalar
53
+ % type plastic scalar
54
+ % type alpha_new scalar
55
+
56
+ \begin{algorithmic}
57
+ \State $sy = sigy0 + K \cdot \alpha^{n}$
58
+ \State $f = sigma_eq - sy$
59
+ \If{$f < 0$}
60
+ \Return $0, \alpha, 0$
61
+ \EndIf
62
+ \State $dl = 0$
63
+ \For{$k = 1, 2, \ldots, max_iter$}
64
+ \State $ap = \alpha + dl$
65
+ \If{$ap < tol$}
66
+ \State $sy = sigy0$
67
+ \State $Hp = 0$
68
+ \Else
69
+ \State $sy = sigy0 + K \cdot ap^{n}$
70
+ \State $Hp = K \cdot n \cdot ap^{n - 1}$
71
+ \EndIf
72
+ \State $res = sigma_eq - 3 \cdot \mu \cdot dl - sy$
73
+ \State $denom = 3 \cdot \mu + Hp$
74
+ \State $dl = dl + res / denom$
75
+ \EndFor
76
+ \State $alpha_new = \alpha + dl$
77
+ \State $plastic = 1$
78
+ \Return $plastic, alpha_new, dl$
79
+ \end{algorithmic}
@@ -0,0 +1,82 @@
1
+ % J2 kinematic linear-hardening radial-return algpseudocode source.
2
+ %
3
+ % Scalar return-map inner solve for J2 plasticity with LINEAR KINEMATIC
4
+ % hardening (Prager). The yield surface translates (back-stress beta)
5
+ % instead of expanding: yield is measured on the RELATIVE (shifted)
6
+ % stress xi = dev(S) - beta, with a CONSTANT yield radius sigma_y0
7
+ % (no isotropic hardening — all hardening lives in beta).
8
+ %
9
+ % Yield function (von Mises of the relative stress):
10
+ %
11
+ % f = ||xi||_eq - sigma_y0, ||xi||_eq = sqrt(3/2 * xi:xi)
12
+ %
13
+ % For LINEAR kinematic hardening the discrete consistency condition is
14
+ % LINEAR in the plastic-multiplier increment, so dl has a CLOSED FORM:
15
+ %
16
+ % ||xi_trial||_eq - sigma_y0 - (3*mu + H_kin)*dl = 0
17
+ % => dl = (||xi_trial||_eq - sigma_y0) / (3*mu + H_kin)
18
+ %
19
+ % This scalar source is authored as the SAME fixed-iteration loop
20
+ % structure as the isotropic power-law variant
21
+ % (``algo2code/library/algorithms/radial_return_j2.tex``) for transpile-pattern
22
+ % consistency: the residual ``res = xi_eq - (3*mu + H_kin)*dl - sigy0``
23
+ % is linear in dl, so the Newton update (denominator ``3*mu + H_kin``)
24
+ % converges in a single step and every subsequent iteration leaves dl
25
+ % unchanged at the exact root (res = 0 => the closed form above).
26
+ % Authoring it as a loop
27
+ % keeps the isotropic, kinematic and mixed variants on one structural
28
+ % pattern that algo2code already transpiles end-to-end.
29
+ %
30
+ % Back-stress update (Prager, discrete) is performed in TENSOR space by
31
+ % the mechdsl-core wrapper:
32
+ %
33
+ % beta_new = beta_old + (2/3)*H_kin*dl*N_flow, N_flow = xi/||xi||
34
+ %
35
+ % with ||N_flow||_eq = 1, so |dbeta|_eq = (2/3)*H_kin*dl and the
36
+ % relative stress contracts at rate (3*mu + H_kin)*dl per the closed
37
+ % form above. All tensor algebra (deviatoric split, relative stress,
38
+ % von Mises of xi, stress reconstruction, plastic-strain and back-stress
39
+ % update, algorithmic tangent) is orchestrated in Python by
40
+ % ``mechdsl.lib.plasticity_kinematic``. This scalar source owns ONLY the
41
+ % plastic-multiplier solve, exactly as the isotropic variant does.
42
+ %
43
+ % Inputs
44
+ % ------
45
+ % xi_eq : von Mises equivalent of the trial RELATIVE stress xi_trial
46
+ % mu : shear modulus (second Lame parameter)
47
+ % H_kin : linear kinematic-hardening (Prager) modulus
48
+ % sigy0 : (constant) yield stress
49
+ % tol : residual tolerance (passed through; the linear solve is
50
+ % exact so the loop converges in one iteration)
51
+ % max_iter : iteration cap (>= 1 suffices; kept for pattern symmetry)
52
+ %
53
+ % Outputs
54
+ % -------
55
+ % plastic : 1 if plastic flow occurred, 0 if elastic step
56
+ % dl : plastic multiplier increment (delta_lambda)
57
+
58
+ % algorithm radial_return_j2_kinematic
59
+ % backend taichi
60
+ % args xi_eq:scalar, mu:scalar, H_kin:scalar, sigy0:scalar, tol:scalar, max_iter:scalar
61
+
62
+ % type f scalar
63
+ % type dl scalar
64
+ % type k scalar
65
+ % type res scalar
66
+ % type denom scalar
67
+ % type plastic scalar
68
+
69
+ \begin{algorithmic}
70
+ \State $f = xi_eq - sigy0$
71
+ \If{$f < 0$}
72
+ \Return $0, 0$
73
+ \EndIf
74
+ \State $dl = 0$
75
+ \State $denom = 3 \cdot \mu + H_kin$
76
+ \For{$k = 1, 2, \ldots, max_iter$}
77
+ \State $res = xi_eq - 3 \cdot \mu \cdot dl - H_kin \cdot dl - sigy0$
78
+ \State $dl = dl + res / denom$
79
+ \EndFor
80
+ \State $plastic = 1$
81
+ \Return $plastic, dl$
82
+ \end{algorithmic}
@@ -0,0 +1,114 @@
1
+ % J2 MIXED-hardening radial-return algpseudocode source.
2
+ %
3
+ % Scalar return-map inner solve for J2 plasticity with MIXED hardening:
4
+ % the yield surface BOTH translates (linear kinematic back-stress beta,
5
+ % Prager — as in the kinematic variant) AND expands (power-law isotropic
6
+ % radius growth sigma_y(alpha) = sigy0 + K*alpha^n — as in the isotropic
7
+ % variant), simultaneously. Yield
8
+ % is measured on the RELATIVE (shifted) stress xi = dev(S) - beta against
9
+ % the EXPANDING radius sigma_y(alpha):
10
+ %
11
+ % f = ||xi||_eq - sigma_y(alpha), ||xi||_eq = sqrt(3/2 * xi:xi)
12
+ % sigma_y(alpha) = sigy0 + K * alpha^n
13
+ %
14
+ % Because the isotropic part is a NONLINEAR power law in
15
+ % alpha = alpha_old + dl, the discrete consistency condition is NONLINEAR
16
+ % in the plastic-multiplier increment dl, so — unlike the pure-linear
17
+ % kinematic variant (closed form) — this needs the scalar NEWTON
18
+ % loop of the isotropic variant. The kinematic part contributes a
19
+ % LINEAR term (3*mu + H_kin)*dl exactly as in the kinematic variant; the
20
+ % isotropic part contributes the nonlinear sigma_y(alpha_old + dl) exactly
21
+ % as in the isotropic variant.
22
+ %
23
+ % Consistency residual (root in dl):
24
+ %
25
+ % r(dl) = ||xi_trial||_eq - (3*mu + H_kin)*dl - sigma_y(alpha_old + dl)
26
+ %
27
+ % Newton derivative:
28
+ %
29
+ % r'(dl) = -(3*mu + H_kin) - K*n*(alpha_old + dl)^(n-1)
30
+ %
31
+ % so the Newton update is dl <- dl + r / (3*mu + H_kin + Hp) with
32
+ % Hp = K*n*ap^(n-1) the isotropic slope d(sigma_y)/d(alpha). This reduces
33
+ % to the isotropic variant when H_kin = 0 (xi_eq == sigma_eq, beta == 0)
34
+ % and to the kinematic variant when
35
+ % K = 0 (sigma_y(alpha) == sigy0, constant radius, linear residual).
36
+ %
37
+ % The alpha->0 guard mirrors j2_power_law.py / radial_return_j2.tex: for
38
+ % hardening exponents n < 1 the slope K*n*ap^(n-1) diverges as ap -> 0+,
39
+ % so below the tolerance ap < tol the radius is held at sigy0 and the
40
+ % slope Hp at 0.
41
+ %
42
+ % This scalar source owns ONLY the plastic-multiplier solve. All tensor
43
+ % algebra (deviatoric split, relative stress xi, von Mises of xi, radial
44
+ % stress reconstruction, plastic-strain / Prager back-stress / accumulated
45
+ % plastic-strain alpha updates, algorithmic tangent) is orchestrated in
46
+ % Python by ``mechdsl.lib.plasticity_mixed`` — the same division of labour
47
+ % as the isotropic (``mechdsl.lib.plasticity``) and kinematic
48
+ % (``mechdsl.lib.plasticity_kinematic``) variants. The flow normal and
49
+ % back-stress factors are identical to the kinematic variant:
50
+ %
51
+ % nf = (3/2) * xi / ||xi||_eq (von Mises gradient)
52
+ % dEp = dl * nf (plastic strain increment)
53
+ % beta += (2/3) * H_kin * dl * nf (Prager back-stress, linear)
54
+ % alpha += dl (accumulated equivalent plastic strain)
55
+ %
56
+ % Inputs
57
+ % ------
58
+ % xi_eq : von Mises equivalent of the trial RELATIVE stress xi_trial
59
+ % alpha : alpha_old, prior accumulated equivalent plastic strain
60
+ % mu : shear modulus (second Lame parameter)
61
+ % K : isotropic hardening modulus (power-law coefficient)
62
+ % n : isotropic hardening exponent
63
+ % H_kin : linear kinematic-hardening (Prager) modulus
64
+ % sigy0 : initial yield stress
65
+ % tol : alpha->0 guard threshold / residual tolerance (passed
66
+ % through; the Newton loop converges quadratically and the
67
+ % wrapper applies the reference tolerance externally)
68
+ % max_iter : Newton max iterations
69
+ %
70
+ % Outputs
71
+ % -------
72
+ % plastic : 1 if plastic flow occurred, 0 if elastic step
73
+ % alpha_new : alpha_old + delta_lambda (when plastic)
74
+ % dl : plastic multiplier increment (delta_lambda)
75
+
76
+ % algorithm radial_return_j2_mixed
77
+ % backend taichi
78
+ % args xi_eq:scalar, alpha:scalar, mu:scalar, K:scalar, n:scalar, H_kin:scalar, sigy0:scalar, tol:scalar, max_iter:scalar
79
+
80
+ % type sy scalar
81
+ % type f scalar
82
+ % type dl scalar
83
+ % type k scalar
84
+ % type Hp scalar
85
+ % type res scalar
86
+ % type denom scalar
87
+ % type ap scalar
88
+ % type plastic scalar
89
+ % type alpha_new scalar
90
+
91
+ \begin{algorithmic}
92
+ \State $sy = sigy0 + K \cdot \alpha^{n}$
93
+ \State $f = xi_eq - sy$
94
+ \If{$f < 0$}
95
+ \Return $0, \alpha, 0$
96
+ \EndIf
97
+ \State $dl = 0$
98
+ \For{$k = 1, 2, \ldots, max_iter$}
99
+ \State $ap = \alpha + dl$
100
+ \If{$ap < tol$}
101
+ \State $sy = sigy0$
102
+ \State $Hp = 0$
103
+ \Else
104
+ \State $sy = sigy0 + K \cdot ap^{n}$
105
+ \State $Hp = K \cdot n \cdot ap^{n - 1}$
106
+ \EndIf
107
+ \State $res = xi_eq - 3 \cdot \mu \cdot dl - H_kin \cdot dl - sy$
108
+ \State $denom = 3 \cdot \mu + H_kin + Hp$
109
+ \State $dl = dl + res / denom$
110
+ \EndFor
111
+ \State $alpha_new = \alpha + dl$
112
+ \State $plastic = 1$
113
+ \Return $plastic, alpha_new, dl$
114
+ \end{algorithmic}
algo2code/library/pcg.py CHANGED
@@ -1,21 +1,18 @@
1
1
  r"""Canonical Preconditioned Conjugate Gradient (PCG) algorithm in algpseudocode.
2
2
 
3
3
  This module is the **algo2code interface hook** consumed by
4
- ``mechdsl-core``'s ``Algo2CodePCGSolver`` adapter (Plan recovery task P6-1).
4
+ ``mechdsl-core``'s ``Algo2CodePCGSolver`` adapter.
5
5
  It exposes:
6
6
 
7
7
  * :data:`PCG_ALGORITHM_LATEX` — the verbatim LaTeX source of the canonical
8
- PCG algorithm, mirrored from
9
- ``dev/tasks/recovery_plan_latex_contract/json/P6-1.json`` field
10
- ``pcg_algorithm_latex.latex``.
8
+ PCG algorithm.
11
9
  * :func:`get_pcg_algorithm_latex` — accessor returning that text.
12
10
 
13
11
  Runtime invariant
14
12
  -----------------
15
13
 
16
14
  This module imports **only stdlib**. ``algo2code`` is the runtime-free
17
- sibling package of ``mechdsl-core`` (see ``.claude/CLAUDE.md`` /
18
- ``dev/design_docs/11-ALGO2CODE.md``); nothing here imports — directly or
15
+ sibling package of ``mechdsl-core``; nothing here imports — directly or
19
16
  transitively — ``mechdsl``. Consumers that want a runnable implementation
20
17
  own the translation step.
21
18
 
@@ -1,13 +1,12 @@
1
1
  r"""Canonical J2 radial-return algorithm (algo2code interface hook).
2
2
 
3
- post_recovery_plan Phase 5 (P5-1, P5-3). Mirrors the
4
- ``algo2code.library.pcg`` pattern but goes one step further:
3
+ Mirrors the ``algo2code.library.pcg`` pattern but goes one step further:
5
4
 
6
5
  - :data:`RADIAL_RETURN_J2_LATEX` exposes the verbatim algpseudocode.
7
6
  - :func:`get_radial_return_j2_latex` returns it (accessor symmetry
8
7
  with PCG).
9
8
  - :func:`transpile_radial_return_j2` runs ``algo2code.transpile`` on
10
- the source and returns the emitted Python module text. Phase 5's
9
+ the source and returns the emitted Python module text. The
11
10
  parser fixes (multi-letter scratch identifiers; binary ``/`` in
12
11
  assignment LHS) and codegen fix (``n = b.shape[0]`` regression for
13
12
  scalar-only algorithms) make this work end-to-end.
@@ -25,28 +24,11 @@ runtime-free contract holds.
25
24
 
26
25
  from __future__ import annotations
27
26
 
28
- from pathlib import Path
27
+ from algo2code.library.sources import algorithm_source
29
28
 
30
-
31
- def _load_canonical_source() -> str:
32
- """Read the canonical algpseudocode source from
33
- ``dev/algorithms/radial_return_j2.tex``.
34
-
35
- Walks up from this module to the repo root, then reads the
36
- file. Single source of truth — the LaTeX file is authoritative.
37
- """
38
- here = Path(__file__).resolve()
39
- for parent in here.parents:
40
- candidate = parent / "dev" / "algorithms" / "radial_return_j2.tex"
41
- if candidate.is_file():
42
- return candidate.read_text(encoding="utf-8")
43
- raise FileNotFoundError(
44
- "post_recovery_plan Phase 5 (P5-1): canonical algorithm source "
45
- "not found. Expected at <repo>/dev/algorithms/radial_return_j2.tex."
46
- )
47
-
48
-
49
- RADIAL_RETURN_J2_LATEX: str = _load_canonical_source()
29
+ # Single source of truth: the bundled ``algorithms/radial_return_j2.tex``
30
+ # (package data shipped in the wheel) is authoritative.
31
+ RADIAL_RETURN_J2_LATEX: str = algorithm_source("radial_return_j2.tex")
50
32
 
51
33
 
52
34
  def get_radial_return_j2_latex() -> str:
@@ -58,8 +40,8 @@ def transpile_radial_return_j2(backend: str = "taichi") -> str:
58
40
  """Transpile the canonical algpseudocode to ``backend`` and return
59
41
  the emitted Python module source.
60
42
 
61
- post_recovery_plan Phase 5 lifted the deferral that previously
62
- blocked this round-trip: the algo2code expr_parser now handles
43
+ The deferral that previously blocked this round-trip has been
44
+ lifted: the algo2code expr_parser handles
63
45
  multi-letter scratch identifiers (``sy``, ``Hp``, ``ap``) and
64
46
  binary ``/`` in assignment LHS contexts, and the Taichi codegen
65
47
  no longer emits ``n = b.shape[0]`` for scalar-only algorithms.
@@ -67,8 +49,8 @@ def transpile_radial_return_j2(backend: str = "taichi") -> str:
67
49
  Parameters
68
50
  ----------
69
51
  backend:
70
- Target backend name. ``"taichi"`` is the only one consumed by
71
- ``mechdsl-core`` today.
52
+ Target backend name: ``"taichi"`` or ``"numpy"``. ``mechdsl-core``
53
+ consumes ``"numpy"`` so J2 runs without Taichi installed.
72
54
 
73
55
  Returns
74
56
  -------
@@ -1,6 +1,6 @@
1
1
  r"""J2 kinematic linear-hardening radial-return (algo2code interface hook).
2
2
 
3
- constitutive_latex Phase 6 (P6-2). Mirrors
3
+ Mirrors
4
4
  :mod:`algo2code.library.radial_return_j2` (the isotropic power-law
5
5
  variant) for the linear-kinematic (Prager) hardening model:
6
6
 
@@ -29,29 +29,11 @@ runtime-free contract holds.
29
29
 
30
30
  from __future__ import annotations
31
31
 
32
- from pathlib import Path
32
+ from algo2code.library.sources import algorithm_source
33
33
 
34
-
35
- def _load_canonical_source() -> str:
36
- """Read the canonical algpseudocode source from
37
- ``dev/algorithms/radial_return_j2_kinematic.tex``.
38
-
39
- Walks up from this module to the repo root, then reads the file.
40
- Single source of truth — the LaTeX file is authoritative.
41
- """
42
- here = Path(__file__).resolve()
43
- for parent in here.parents:
44
- candidate = parent / "dev" / "algorithms" / "radial_return_j2_kinematic.tex"
45
- if candidate.is_file():
46
- return candidate.read_text(encoding="utf-8")
47
- raise FileNotFoundError(
48
- "constitutive_latex Phase 6 (P6-2): canonical kinematic algorithm "
49
- "source not found. Expected at "
50
- "<repo>/dev/algorithms/radial_return_j2_kinematic.tex."
51
- )
52
-
53
-
54
- RADIAL_RETURN_J2_KINEMATIC_LATEX: str = _load_canonical_source()
34
+ # Single source of truth: the bundled ``algorithms/radial_return_j2_kinematic.tex``
35
+ # (package data shipped in the wheel) is authoritative.
36
+ RADIAL_RETURN_J2_KINEMATIC_LATEX: str = algorithm_source("radial_return_j2_kinematic.tex")
55
37
 
56
38
 
57
39
  def get_radial_return_j2_kinematic_latex() -> str:
@@ -66,8 +48,8 @@ def transpile_radial_return_j2_kinematic(backend: str = "taichi") -> str:
66
48
  Parameters
67
49
  ----------
68
50
  backend:
69
- Target backend name. ``"taichi"`` is the only one consumed by
70
- ``mechdsl-core`` today.
51
+ Target backend name: ``"taichi"`` or ``"numpy"``. ``mechdsl-core``
52
+ consumes ``"numpy"`` so J2 runs without Taichi installed.
71
53
 
72
54
  Returns
73
55
  -------
@@ -1,6 +1,6 @@
1
1
  r"""J2 mixed-hardening radial-return (algo2code interface hook).
2
2
 
3
- constitutive_latex Phase 6 (P6-3). Mirrors
3
+ Mirrors
4
4
  :mod:`algo2code.library.radial_return_j2` (isotropic power-law) and
5
5
  :mod:`algo2code.library.radial_return_j2_kinematic` (linear kinematic)
6
6
  for the MIXED-hardening model — the yield surface BOTH translates
@@ -31,29 +31,11 @@ runtime-free contract holds.
31
31
 
32
32
  from __future__ import annotations
33
33
 
34
- from pathlib import Path
34
+ from algo2code.library.sources import algorithm_source
35
35
 
36
-
37
- def _load_canonical_source() -> str:
38
- """Read the canonical algpseudocode source from
39
- ``dev/algorithms/radial_return_j2_mixed.tex``.
40
-
41
- Walks up from this module to the repo root, then reads the file.
42
- Single source of truth — the LaTeX file is authoritative.
43
- """
44
- here = Path(__file__).resolve()
45
- for parent in here.parents:
46
- candidate = parent / "dev" / "algorithms" / "radial_return_j2_mixed.tex"
47
- if candidate.is_file():
48
- return candidate.read_text(encoding="utf-8")
49
- raise FileNotFoundError(
50
- "constitutive_latex Phase 6 (P6-3): canonical mixed algorithm "
51
- "source not found. Expected at "
52
- "<repo>/dev/algorithms/radial_return_j2_mixed.tex."
53
- )
54
-
55
-
56
- RADIAL_RETURN_J2_MIXED_LATEX: str = _load_canonical_source()
36
+ # Single source of truth: the bundled ``algorithms/radial_return_j2_mixed.tex``
37
+ # (package data shipped in the wheel) is authoritative.
38
+ RADIAL_RETURN_J2_MIXED_LATEX: str = algorithm_source("radial_return_j2_mixed.tex")
57
39
 
58
40
 
59
41
  def get_radial_return_j2_mixed_latex() -> str:
@@ -68,8 +50,8 @@ def transpile_radial_return_j2_mixed(backend: str = "taichi") -> str:
68
50
  Parameters
69
51
  ----------
70
52
  backend:
71
- Target backend name. ``"taichi"`` is the only one consumed by
72
- ``mechdsl-core`` today.
53
+ Target backend name: ``"taichi"`` or ``"numpy"``. ``mechdsl-core``
54
+ consumes ``"numpy"`` so J2 runs without Taichi installed.
73
55
 
74
56
  Returns
75
57
  -------
@@ -0,0 +1,90 @@
1
+ """Access to the canonical algorithm sources bundled with ``algo2code``.
2
+
3
+ The ``.tex`` files under ``algo2code/library/algorithms/`` are the single
4
+ source of truth for every algorithm the library exposes (and for the solver
5
+ seams in ``mechdsl-core`` that transpile them at runtime). They ship as
6
+ package data inside the wheel, so an installed ``algo2code`` can read them
7
+ without a source checkout — nothing here depends on the repository layout.
8
+
9
+ Runtime invariant
10
+ -----------------
11
+
12
+ This module imports **only stdlib**.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from importlib import resources
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING
20
+
21
+ if TYPE_CHECKING:
22
+ from importlib.resources.abc import Traversable
23
+
24
+ #: Names of every bundled algorithm source, as accepted by :func:`algorithm_source`.
25
+ ALGORITHM_SOURCES: tuple[str, ...] = (
26
+ "jacobi.tex",
27
+ "newmark.tex",
28
+ "pcg.tex",
29
+ "radial_return_j2.tex",
30
+ "radial_return_j2_kinematic.tex",
31
+ "radial_return_j2_mixed.tex",
32
+ )
33
+
34
+
35
+ def _algorithms_dir() -> Traversable:
36
+ return resources.files("algo2code.library").joinpath("algorithms")
37
+
38
+
39
+ def _resource(name: str) -> Traversable:
40
+ resource = _algorithms_dir().joinpath(name)
41
+ if not resource.is_file():
42
+ try:
43
+ available = sorted(
44
+ p.name for p in _algorithms_dir().iterdir() if p.name.endswith(".tex")
45
+ )
46
+ except (FileNotFoundError, NotADirectoryError):
47
+ available = []
48
+ raise FileNotFoundError(
49
+ f"algo2code has no bundled algorithm source named {name!r} "
50
+ f"(expected it under algo2code/library/algorithms/). "
51
+ f"Available sources: {', '.join(available) or 'none'}. "
52
+ "If this is an installed package, the installation is missing its "
53
+ "package data — reinstall algo2code."
54
+ )
55
+ return resource
56
+
57
+
58
+ def algorithm_source(name: str) -> str:
59
+ """Return the verbatim LaTeX text of the bundled algorithm source ``name``.
60
+
61
+ Parameters
62
+ ----------
63
+ name:
64
+ File name of the source, e.g. ``"pcg.tex"``. See
65
+ :data:`ALGORITHM_SOURCES` for the full list.
66
+
67
+ Raises
68
+ ------
69
+ FileNotFoundError
70
+ If no bundled source of that name exists.
71
+ """
72
+ return _resource(name).read_text(encoding="utf-8")
73
+
74
+
75
+ def algorithm_source_path(name: str) -> Path:
76
+ """Return the on-disk path of the bundled algorithm source ``name``.
77
+
78
+ Installed wheels are unpacked, so the resource is a regular file and the
79
+ returned path can be read directly. Prefer :func:`algorithm_source` when
80
+ only the text is needed; this accessor exists for callers that want to
81
+ show *where* the canonical source lives.
82
+ """
83
+ return Path(str(_resource(name)))
84
+
85
+
86
+ __all__ = [
87
+ "ALGORITHM_SOURCES",
88
+ "algorithm_source",
89
+ "algorithm_source_path",
90
+ ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: algo2code
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Transpile LaTeX algorithm boxes (algpseudocode) to executable Taichi/NumPy/C code
5
5
  Project-URL: Repository, https://github.com/CEmM2/MechDSL
6
6
  Author: Shmuel Osovski
@@ -17,7 +17,14 @@ Description-Content-Type: text/markdown
17
17
 
18
18
  # algo2code
19
19
 
20
- Transpile LaTeX algorithm boxes (`algpseudocode`) to executable code targeting Taichi, NumPy, or C/PETSc.
20
+ Transpile LaTeX algorithm boxes (`algpseudocode`) to executable code targeting Taichi or NumPy (C/PETSc planned).
21
+
22
+ ```python
23
+ from algo2code import transpile
24
+
25
+ transpile(source, backend="taichi") # Taichi kernels + Python driver
26
+ transpile(source, backend="numpy") # plain function that imports only NumPy
27
+ ```
21
28
 
22
29
  Parses `\begin{algorithmic}...\end{algorithmic}` environments with type-directed code generation.
23
30
  Zero runtime dependencies — standard library only.
@@ -0,0 +1,27 @@
1
+ algo2code/__init__.py,sha256=53EERdBlCpGlOQBigJ8u7zmBUc8RsYt3p8937ti0DLU,2352
2
+ algo2code/algo_parser.py,sha256=eC0Dl2X7vPojmViTk-3XCXBpySevBeptgI24vVS7KI4,15880
3
+ algo2code/ast_nodes.py,sha256=p7n-ZPoR7SizrcbgIMUWigWrk8kfifBLYfSchlrlQxo,4561
4
+ algo2code/errors.py,sha256=506gr0O_ufY1eqceHicuP8RcGzwNT1TuCGoquJHoA1Q,1098
5
+ algo2code/expr_parser.py,sha256=HJ7lYawKB3vUu24tFC_ihvjFYtBypXi_-pGYdKTGdWE,21517
6
+ algo2code/type_inference.py,sha256=Pa3bK-QV_IlMx32jh1xx39lj_-dC4DOC-eO9aU1keF4,7596
7
+ algo2code/backends/__init__.py,sha256=hNwHmY9S56cZsMNlP95kFYMz8qojJKqXl7s1aFcXg84,32
8
+ algo2code/backends/c_petsc_codegen.py,sha256=YlRVHC8vwugD1ZGz0UVGMKzMzhZBlAzLBwkbO90FpXM,33
9
+ algo2code/backends/numpy_codegen.py,sha256=7qG0Zyg5OgQ8Sp5t_OsPI67JEfcZx_f44LCPszEscM0,6733
10
+ algo2code/backends/taichi_codegen.py,sha256=vEQHYjH46l3WK9LOcK0AxGMZotWvbrLsBC-nRbAcNd0,36125
11
+ algo2code/library/.gitkeep,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ algo2code/library/__init__.py,sha256=rjMAE0SQPG0xLWmvFuX19S9adKTSbDlwN0FK13WNgrM,1029
13
+ algo2code/library/pcg.py,sha256=sVN_klQYT7UQoKxnK_IfLT3jr676ru8eRc3FgyfnMIY,5434
14
+ algo2code/library/radial_return_j2.py,sha256=eBbZuvL6VGFVPYmtZUq7C5ZpziB0AK7HjsxFlm473Mc,2586
15
+ algo2code/library/radial_return_j2_kinematic.py,sha256=wU-Fz5wkNzLnPrSm9MMLqGXIba3wjGBY3vifiVcJiZs,2553
16
+ algo2code/library/radial_return_j2_mixed.py,sha256=5s5Xr4fP1ZMhYGMCTuZgiyBDH1DBlt4JmHneESCXq-U,2759
17
+ algo2code/library/sources.py,sha256=j3BGBO9ZVBGwVaAgfjHFcy5_Ck5uynr_oXff7z7J8CY,2840
18
+ algo2code/library/algorithms/jacobi.tex,sha256=dvXn1F8TUf3z2Gqq_a-OL6U88Vk3qFRJXIJE4DRHoUQ,1992
19
+ algo2code/library/algorithms/newmark.tex,sha256=YKxN9Oowc9duJgGa_TzBwGuR8VvL6h_xZrSbcxbhbLw,4972
20
+ algo2code/library/algorithms/pcg.tex,sha256=YKVl8-k5rBNvTO1ocIZrIx5-IQMRnWIpmDiS4kO7HFQ,4688
21
+ algo2code/library/algorithms/radial_return_j2.tex,sha256=8JfLU_ZImM526IUFPllX6tzZEFT3SY2GnqMZSV37XJs,2760
22
+ algo2code/library/algorithms/radial_return_j2_kinematic.tex,sha256=Laxph0YV1QuK7rBoUhif1RlsX8FITdLIQOc7g_yMxM0,3269
23
+ algo2code/library/algorithms/radial_return_j2_mixed.tex,sha256=7Ki2m73s05X0zWRi3b4EtHxt7W1yT6z0I4nC9U-1fpQ,4640
24
+ algo2code-0.2.2.dist-info/METADATA,sha256=IubpunNQJEqCvJP-U2Bj5ayWagmsV5_dViRDtMYKaRI,1419
25
+ algo2code-0.2.2.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
26
+ algo2code-0.2.2.dist-info/licenses/LICENSE,sha256=09AX3cq_TtJwbbZ00zsqmmGL_p_FINJ4l8asH_rhVhk,1071
27
+ algo2code-0.2.2.dist-info/RECORD,,
@@ -1,20 +0,0 @@
1
- algo2code/__init__.py,sha256=FWaPHkz13pKOXfuA0ahh_uKXGRe80UGCz_1nUs_hpIc,2061
2
- algo2code/algo_parser.py,sha256=eC0Dl2X7vPojmViTk-3XCXBpySevBeptgI24vVS7KI4,15880
3
- algo2code/ast_nodes.py,sha256=p7n-ZPoR7SizrcbgIMUWigWrk8kfifBLYfSchlrlQxo,4561
4
- algo2code/errors.py,sha256=506gr0O_ufY1eqceHicuP8RcGzwNT1TuCGoquJHoA1Q,1098
5
- algo2code/expr_parser.py,sha256=R5PQ3ey3DQYTTl-xOJ4KvqKSpUbEvhrs82htSae6W0A,21564
6
- algo2code/type_inference.py,sha256=Pa3bK-QV_IlMx32jh1xx39lj_-dC4DOC-eO9aU1keF4,7596
7
- algo2code/backends/__init__.py,sha256=hNwHmY9S56cZsMNlP95kFYMz8qojJKqXl7s1aFcXg84,32
8
- algo2code/backends/c_petsc_codegen.py,sha256=YlRVHC8vwugD1ZGz0UVGMKzMzhZBlAzLBwkbO90FpXM,33
9
- algo2code/backends/numpy_codegen.py,sha256=WpOm7GkpD51L_kYkoZiVnv-lwn_5ZwtcveU9porEdWY,31
10
- algo2code/backends/taichi_codegen.py,sha256=ME7BGQDX8nOOYiQFe7Mw0hDYezGU-KVQ9f0bv-nKKYw,35942
11
- algo2code/library/.gitkeep,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
- algo2code/library/__init__.py,sha256=HZf5doUkzAjS2D1It3Jc-9fUIRp04BH4wYteaOVPGqc,686
13
- algo2code/library/pcg.py,sha256=uFQnr3U5a0L3hz_d_S3g9D4pUu8vFthiN55bOy-FBeA,5639
14
- algo2code/library/radial_return_j2.py,sha256=qW-3avbzW9WQQytX2fZwg7zwQaWhDMYcJCx_B6m9aXM,3136
15
- algo2code/library/radial_return_j2_kinematic.py,sha256=MaP0IPmrZSafjzH8KuzdBtC2XbKw8tYK7uaLW3M7LQc,3100
16
- algo2code/library/radial_return_j2_mixed.py,sha256=q9AKkf6Z7uRtMcKTCFWXFI74xHJi0qiMje8hzGWdPl8,3298
17
- algo2code-0.2.1.dist-info/METADATA,sha256=EOl2z0f4pzkiX-les0_93qdcL-fZ_fHznqmLfGD9uUI,1215
18
- algo2code-0.2.1.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
19
- algo2code-0.2.1.dist-info/licenses/LICENSE,sha256=09AX3cq_TtJwbbZ00zsqmmGL_p_FINJ4l8asH_rhVhk,1071
20
- algo2code-0.2.1.dist-info/RECORD,,