origami-engine-mjx 0.1.0__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.
@@ -0,0 +1,73 @@
1
+ """origami-engine-mjx: MJX-based origami folding simulator.
2
+
3
+ Dual-backend MuJoCo MJX engine supporting both MJX-JAX (CPU/GPU/TPU,
4
+ differentiable) and MJX-Warp (NVIDIA CUDA GPU, high-throughput batched).
5
+
6
+ Quick start
7
+ -----------
8
+ >>> from origami_engine_mjx import OrigamiEngine, load_default_creases
9
+ >>> engine = OrigamiEngine(backend="jax")
10
+ >>> creases = load_default_creases()
11
+ >>> score = engine.evaluate(creases, duration=1.0)
12
+ """
13
+
14
+ from .constants import (
15
+ MAX_FOLD,
16
+ PAPER_MASS,
17
+ THICK,
18
+ VIB_AMP_X,
19
+ VIB_AMP_Z,
20
+ VIB_FREQ,
21
+ Z0,
22
+ M,
23
+ S,
24
+ V,
25
+ )
26
+ from .engine import OrigamiEngine, compute_forward_displacement
27
+ from .evaluation import evaluate_individual, evaluate_population
28
+ from .geometry import build_pattern
29
+ from .model import generate_xml
30
+ from .patterns import (
31
+ DEFAULT_PATTERN_JSON,
32
+ load_default_creases,
33
+ reference_miura_legacy_creases,
34
+ reference_miura_render_creases,
35
+ )
36
+ from .plotting import plot_pattern
37
+ from .serialization import CREASE_SCHEMA, load_creases_from_json, normalize_creases, save_creases_to_json
38
+ from .types import BackendName, Crease, Pattern, PopulationResult, SimulationResult
39
+
40
+ __version__ = "0.1.0"
41
+
42
+ __all__ = [
43
+ "CREASE_SCHEMA",
44
+ "DEFAULT_PATTERN_JSON",
45
+ "MAX_FOLD",
46
+ "PAPER_MASS",
47
+ "THICK",
48
+ "VIB_AMP_X",
49
+ "VIB_AMP_Z",
50
+ "VIB_FREQ",
51
+ "Z0",
52
+ "BackendName",
53
+ "Crease",
54
+ "M",
55
+ "OrigamiEngine",
56
+ "Pattern",
57
+ "PopulationResult",
58
+ "S",
59
+ "SimulationResult",
60
+ "V",
61
+ "build_pattern",
62
+ "compute_forward_displacement",
63
+ "evaluate_individual",
64
+ "evaluate_population",
65
+ "generate_xml",
66
+ "load_creases_from_json",
67
+ "load_default_creases",
68
+ "normalize_creases",
69
+ "plot_pattern",
70
+ "reference_miura_legacy_creases",
71
+ "reference_miura_render_creases",
72
+ "save_creases_to_json",
73
+ ]
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ """Backend import guards.
4
+
5
+ Keeping optional imports in one place lets geometry and I/O modules be
6
+ imported (and unit-tested) without JAX or Warp installed.
7
+ """
8
+
9
+ # --- classic MuJoCo (used for XML compilation + rendering) ---
10
+ MUJOCO_IMPORT_ERROR: BaseException | None = None
11
+ try:
12
+ import mujoco
13
+ except Exception as exc: # noqa: BLE001
14
+ mujoco = None
15
+ MUJOCO_IMPORT_ERROR = exc
16
+
17
+
18
+ def require_mujoco(message: str = "MuJoCo is required for this operation."):
19
+ """Return the imported ``mujoco`` module or raise a helpful RuntimeError."""
20
+ if mujoco is None:
21
+ raise RuntimeError(message) from MUJOCO_IMPORT_ERROR
22
+ return mujoco
23
+
24
+
25
+ # --- MJX-JAX ---
26
+ MJX_JAX_IMPORT_ERROR: BaseException | None = None
27
+ try:
28
+ import jax # noqa: F401
29
+ import jax.numpy as jnp # noqa: F401
30
+ from mujoco import mjx as mjx_jax
31
+ except Exception as exc: # noqa: BLE001
32
+ mjx_jax = None
33
+ MJX_JAX_IMPORT_ERROR = exc
34
+
35
+
36
+ def require_mjx_jax(message: str = "MJX-JAX backend requires 'mujoco-mjx' and 'jax'."):
37
+ if mjx_jax is None:
38
+ raise RuntimeError(message + " Install with: pip install 'origami-engine-mjx[jax]'") from MJX_JAX_IMPORT_ERROR
39
+ return mjx_jax
40
+
41
+
42
+ # --- MJX-Warp ---
43
+ MJX_WARP_IMPORT_ERROR: BaseException | None = None
44
+ try:
45
+ import mujoco.warp as mjx_warp
46
+ except Exception as exc: # noqa: BLE001
47
+ mjx_warp = None
48
+ MJX_WARP_IMPORT_ERROR = exc
49
+
50
+
51
+ def require_mjx_warp(message: str = "MJX-Warp backend requires 'mujoco-warp' and an NVIDIA GPU."):
52
+ if mjx_warp is None:
53
+ raise RuntimeError(
54
+ message + " Install with: pip install 'origami-engine-mjx[warp]'"
55
+ ) from MJX_WARP_IMPORT_ERROR
56
+ return mjx_warp
57
+
58
+
59
+ __all__ = [
60
+ "MJX_JAX_IMPORT_ERROR",
61
+ "MJX_WARP_IMPORT_ERROR",
62
+ "MUJOCO_IMPORT_ERROR",
63
+ "mjx_jax",
64
+ "mjx_warp",
65
+ "mujoco",
66
+ "require_mjx_jax",
67
+ "require_mjx_warp",
68
+ "require_mujoco",
69
+ ]
@@ -0,0 +1,73 @@
1
+ from __future__ import annotations
2
+
3
+ """Backend factory and registry.
4
+
5
+ Resolves a backend name (``"jax"`` or ``"warp"``) to a concrete
6
+ :class:`~origami_engine_mjx.backends.base.SimulationBackend` instance.
7
+ Missing optional dependencies produce clear, actionable errors.
8
+ """
9
+
10
+ from .base import SimulationBackend
11
+
12
+ _REGISTRY: dict[str, type[SimulationBackend]] = {}
13
+
14
+
15
+ def register_backend(name: str, cls: type[SimulationBackend]) -> None:
16
+ _REGISTRY[name] = cls
17
+
18
+
19
+ def available_backends() -> list[str]:
20
+ """Return names of backends whose dependencies are installed."""
21
+ result = []
22
+ for name, cls in _REGISTRY.items():
23
+ try:
24
+ if cls().is_available():
25
+ result.append(name)
26
+ except Exception: # noqa: BLE001, S110 - availability probe must never raise
27
+ pass
28
+ return result
29
+
30
+
31
+ def get_backend(name: str) -> SimulationBackend:
32
+ """Instantiate the named backend.
33
+
34
+ Parameters
35
+ ----------
36
+ name : {"jax", "warp"}
37
+ Backend identifier. ``"jax"`` selects MJX-JAX (CPU/GPU/TPU via JAX).
38
+ ``"warp"`` selects MJX-Warp (NVIDIA CUDA GPU).
39
+
40
+ Raises
41
+ ------
42
+ ValueError
43
+ If the name is unknown.
44
+ RuntimeError
45
+ If the backend's optional dependencies are not installed.
46
+ """
47
+ if name not in _REGISTRY:
48
+ raise ValueError(f"unknown backend {name!r}; expected one of {sorted(_REGISTRY)}")
49
+ cls = _REGISTRY[name]
50
+ instance = cls()
51
+ if not instance.is_available():
52
+ raise RuntimeError(
53
+ f"backend {name!r} is not available. "
54
+ f"Install its optional dependencies, e.g. pip install 'origami-engine-mjx[{name}]'"
55
+ )
56
+ return instance
57
+
58
+
59
+ # Register built-in backends. Imports are deferred so that importing this
60
+ # module never initialises JAX or Warp unless the corresponding backend is
61
+ # actually requested.
62
+ def _register_builtin() -> None:
63
+ from .jax_backend import JaxBackend
64
+ from .warp_backend import WarpBackend
65
+
66
+ register_backend("jax", JaxBackend)
67
+ register_backend("warp", WarpBackend)
68
+
69
+
70
+ _register_builtin()
71
+
72
+
73
+ __all__ = ["available_backends", "get_backend", "register_backend"]
@@ -0,0 +1,73 @@
1
+ from __future__ import annotations
2
+
3
+ """Abstract simulation backend interface.
4
+
5
+ Each backend (MJX-JAX, MJX-Warp) implements this interface so that the public
6
+ :class:`~origami_engine_mjx.engine.OrigamiEngine` API can be backend-agnostic.
7
+ """
8
+
9
+ from abc import ABC, abstractmethod
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+
14
+ from ..types import SimulationResult
15
+
16
+
17
+ class SimulationBackend(ABC):
18
+ """Common interface for MJX simulation backends."""
19
+
20
+ name: str = "abstract"
21
+
22
+ @abstractmethod
23
+ def build_model(self, xml: str, info: dict[str, Any]) -> Any:
24
+ """Convert MJCF XML into a backend-native model object.
25
+
26
+ Returns a backend-specific model handle (not necessarily a PyTree).
27
+ """
28
+
29
+ @abstractmethod
30
+ def make_state(self, model: Any) -> Any:
31
+ """Create an initial simulation state for the given model."""
32
+
33
+ @abstractmethod
34
+ def run(
35
+ self,
36
+ creases,
37
+ duration: float = 8.0,
38
+ fold_duration: float = 3.0,
39
+ vibrate: bool = True,
40
+ amp_x: float = 0.0,
41
+ amp_z: float = 0.0013,
42
+ freq_hz: float = 75.0,
43
+ coll_thick: float | None = None,
44
+ ) -> SimulationResult:
45
+ """Run a single simulation and return the result."""
46
+
47
+ @abstractmethod
48
+ def run_batch(
49
+ self,
50
+ population: list,
51
+ duration: float = 8.0,
52
+ fold_duration: float = 3.0,
53
+ vibrate: bool = True,
54
+ amp_x: float = 0.0,
55
+ amp_z: float = 0.0013,
56
+ freq_hz: float = 75.0,
57
+ batch_size: int | None = None,
58
+ ) -> np.ndarray:
59
+ """Run a batch of crease patterns in parallel and return fitness scores.
60
+
61
+ Returns an array of forward-displacement scores, one per individual.
62
+ """
63
+
64
+ @abstractmethod
65
+ def is_available(self) -> bool:
66
+ """Return True if this backend's dependencies are installed and usable."""
67
+
68
+ @abstractmethod
69
+ def device_info(self) -> str:
70
+ """Return a human-readable description of the compute device in use."""
71
+
72
+
73
+ __all__ = ["SimulationBackend"]
@@ -0,0 +1,217 @@
1
+ from __future__ import annotations
2
+
3
+ """MJX-JAX simulation backend.
4
+
5
+ Uses ``mujoco.mjx`` (the JAX implementation of MuJoCo) for differentiable,
6
+ JIT-compiled simulation. Runs on CPU locally and on GPU/TPU through JAX
7
+ backends. Supports ``jax.jit``, ``jax.vmap``, and ``jax.lax.scan``.
8
+ """
9
+
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+
14
+ from ..constants import VIB_AMP_X, VIB_AMP_Z, VIB_FREQ
15
+ from ..geometry import build_pattern
16
+ from ..model import generate_xml
17
+ from ..serialization import normalize_creases
18
+ from ..types import SimulationResult
19
+ from .base import SimulationBackend
20
+
21
+ # Lazy imports — JAX/MJX are optional dependencies.
22
+ jax = None
23
+ jnp = None
24
+ mjx = None
25
+ MjModel = None
26
+ _IMPORT_ERROR: BaseException | None = None
27
+
28
+ try:
29
+ import jax
30
+ import jax.numpy as jnp
31
+ from mujoco import MjModel, mjx
32
+ except Exception as exc: # noqa: BLE001
33
+ _IMPORT_ERROR = exc
34
+
35
+
36
+ class JaxBackend(SimulationBackend):
37
+ """MJX-JAX backend: differentiable, JIT-compiled, vmap-able."""
38
+
39
+ name = "jax"
40
+
41
+ def is_available(self) -> bool:
42
+ return jax is not None and mjx is not None
43
+
44
+ def device_info(self) -> str:
45
+ if jax is None:
46
+ return "jax not installed"
47
+ devices = jax.devices()
48
+ backend = jax.default_backend()
49
+ return f"jax backend={backend}, devices={[str(d) for d in devices]}"
50
+
51
+ # ------------------------------------------------------------------
52
+ # Model / state construction
53
+ # ------------------------------------------------------------------
54
+
55
+ def build_model(self, xml: str, info: dict[str, Any]) -> Any:
56
+ """Compile MJCF XML into an MJX model plus metadata.
57
+
58
+ Returns a dict with keys ``mjx_model``, ``classic_model`` (for name
59
+ lookups), ``info``.
60
+ """
61
+ if mjx is None:
62
+ raise RuntimeError(
63
+ "MJX-JAX backend requires 'mujoco-mjx' and 'jax'. Install with: pip install 'origami-engine-mjx[jax]'"
64
+ ) from _IMPORT_ERROR
65
+ classic = MjModel.from_xml_string(xml)
66
+ mjx_model = mjx.put_model(classic)
67
+ return {"mjx_model": mjx_model, "classic_model": classic, "info": info}
68
+
69
+ def make_state(self, model_bundle: dict[str, Any]) -> Any:
70
+ """Create initial MJX Data from a model bundle."""
71
+ return mjx.make_data(model_bundle["mjx_model"])
72
+
73
+ # ------------------------------------------------------------------
74
+ # Single simulation
75
+ # ------------------------------------------------------------------
76
+
77
+ def run(
78
+ self,
79
+ creases,
80
+ duration: float = 8.0,
81
+ fold_duration: float = 3.0,
82
+ vibrate: bool = True,
83
+ amp_x: float = VIB_AMP_X,
84
+ amp_z: float = VIB_AMP_Z,
85
+ freq_hz: float = VIB_FREQ,
86
+ coll_thick: float | None = None,
87
+ jit: bool = False,
88
+ ) -> SimulationResult:
89
+ if duration <= 0:
90
+ raise ValueError("duration must be positive.")
91
+
92
+ normalized = normalize_creases(creases)
93
+ pat = build_pattern(normalized)
94
+ if not pat.valid:
95
+ raise ValueError(f"invalid crease pattern: {pat.reason}")
96
+
97
+ xml, info = generate_xml(pat, normalized, coll_thick=coll_thick)
98
+ bundle = self.build_model(xml, info)
99
+ mjx_model = bundle["mjx_model"]
100
+ classic = bundle["classic_model"]
101
+
102
+ data = self.make_state(bundle)
103
+
104
+ # Resolve joint addresses from the classic model for bookkeeping.
105
+ hinge_adr = np.array([classic.joint(h["name"]).qposadr[0] for h in info["hinges"]], dtype=int)
106
+ table_x_qadr = int(classic.joint("table_x").qposadr[0])
107
+ table_x_dadr = int(classic.joint("table_x").dofadr[0])
108
+ table_z_qadr = int(classic.joint("table_z").qposadr[0])
109
+ table_z_dadr = int(classic.joint("table_z").dofadr[0])
110
+
111
+ targets = jnp.asarray(info["targets"], dtype=jnp.float32)
112
+
113
+ # Zero hinge qpos initially.
114
+ if len(hinge_adr):
115
+ data = data.replace(qpos=data.qpos.at[hinge_adr].set(0.0))
116
+
117
+ # Compute initial centroid from geom_xpos (exclude table body).
118
+ table_id = int(classic.body("table").id)
119
+ geom_bodyid = np.asarray(mjx_model.geom_bodyid)
120
+ paper_mask = geom_bodyid != table_id
121
+ initial_centroid = self._centroid_from_data(data, paper_mask)
122
+
123
+ # Run the simulation loop. By default we use a plain Python loop with
124
+ # eager mjx.step (JIT compilation of mjx.step on mesh-contact models is
125
+ # prohibitively slow). Set jit=True to JIT-compile the step function
126
+ # (useful for long steady-state runs after warm-up, or on GPU).
127
+ timestep = float(classic.opt.timestep)
128
+ n_steps = round(duration / timestep)
129
+
130
+ def step_fn(d, t_scalar):
131
+ frac = jnp.minimum(t_scalar / fold_duration, 1.0)
132
+ s = frac * frac * (3.0 - 2.0 * frac)
133
+ d = d.replace(ctrl=s * targets)
134
+ if vibrate:
135
+ w = 2.0 * jnp.pi * freq_hz
136
+ qpos = d.qpos.at[table_x_qadr].set(amp_x * jnp.sin(w * t_scalar))
137
+ qvel = d.qvel.at[table_x_dadr].set(amp_x * w * jnp.cos(w * t_scalar))
138
+ qpos = qpos.at[table_z_qadr].set(amp_z * jnp.sin(w * t_scalar))
139
+ qvel = qvel.at[table_z_dadr].set(amp_z * w * jnp.cos(w * t_scalar))
140
+ d = d.replace(qpos=qpos, qvel=qvel)
141
+ return mjx.step(mjx_model, d)
142
+
143
+ step = jax.jit(step_fn) if jit else step_fn
144
+ final_data = data
145
+ for i in range(n_steps):
146
+ t_scalar = jnp.asarray(i * timestep, dtype=jnp.float32)
147
+ final_data = step(final_data, t_scalar)
148
+
149
+ final_qpos = np.asarray(final_data.qpos)
150
+ if not np.isfinite(final_qpos).all():
151
+ raise FloatingPointError("unstable simulation: non-finite joint coordinates produced.")
152
+
153
+ final_centroid = self._centroid_from_data(final_data, paper_mask)
154
+
155
+ return SimulationResult(
156
+ model=bundle,
157
+ data=final_data,
158
+ pattern=pat,
159
+ info=info,
160
+ initial_centroid=initial_centroid,
161
+ final_centroid=final_centroid,
162
+ backend="jax",
163
+ )
164
+
165
+ # ------------------------------------------------------------------
166
+ # Batch population evaluation (jax.vmap over individuals)
167
+ # ------------------------------------------------------------------
168
+
169
+ def run_batch(
170
+ self,
171
+ population: list,
172
+ duration: float = 8.0,
173
+ fold_duration: float = 3.0,
174
+ vibrate: bool = True,
175
+ amp_x: float = VIB_AMP_X,
176
+ amp_z: float = VIB_AMP_Z,
177
+ freq_hz: float = 75.0,
178
+ batch_size: int | None = None,
179
+ ) -> np.ndarray:
180
+ """Evaluate a population of crease patterns.
181
+
182
+ For MJX-JAX, each individual gets its own model (different topology),
183
+ so we loop over individuals but JIT-compile each simulation. True
184
+ ``jax.vmap`` batching applies when individuals share the same model
185
+ topology (same number of faces/hinges) — handled by ``run_batch_vmap``.
186
+ """
187
+ scores = []
188
+ for i, creases in enumerate(population):
189
+ try:
190
+ result = self.run(
191
+ creases,
192
+ duration=duration,
193
+ fold_duration=fold_duration,
194
+ vibrate=vibrate,
195
+ amp_x=amp_x,
196
+ amp_z=amp_z,
197
+ freq_hz=freq_hz,
198
+ )
199
+ delta = result.final_centroid - result.initial_centroid
200
+ scores.append(float(delta[0])) # forward along +x
201
+ except Exception: # noqa: BLE001 - one bad individual must not kill the batch
202
+ scores.append(float("nan"))
203
+ return np.asarray(scores, dtype=float)
204
+
205
+ # ------------------------------------------------------------------
206
+ # Helpers
207
+ # ------------------------------------------------------------------
208
+
209
+ @staticmethod
210
+ def _centroid_from_data(data, paper_mask: np.ndarray) -> np.ndarray:
211
+ """Mean XY of paper geoms (those whose body is not the table)."""
212
+ xpos = np.asarray(data.geom_xpos)
213
+ pts = xpos[paper_mask, :2]
214
+ return pts.mean(axis=0)
215
+
216
+
217
+ __all__ = ["JaxBackend"]