Build a custom Newton solver

Build a custom Newton solver#

This tutorial implements a spring-slider solver with DexSim’s Newton extension interface. All of its code lives in scripts/tutorials/sim/simple_newton_solver/; the provider is an example, not an EmbodiChain solver or package entry point. The scene contains two independent prismatic sliders, one in each environment.

Run the example#

Use a DexSim build that provides ProviderNewtonSolverCfg, FunctionalDynamics and Scene.dynamics_capabilities(). From the repository root, run against an installed EmbodiChain environment or expose this checkout:

export PYTHONPATH="$PWD:$PWD/extensions${PYTHONPATH:+:$PYTHONPATH}"
python scripts/tutorials/sim/simple_newton_solver/demo.py --device cpu \
    --preview-path simple_newton_solver_preview.png

Use --device cuda:0 to run the same numerical example on CUDA. The script runs headlessly. It checks native/functional parity and state isolation before printing JSON. A successful CPU run reports approximately:

{
  "native_functional_parity": true,
  "published_position": [0.020873, 0.031310],
  "partial_reset_position": [0.0, 0.031310],
  "force_gradient": [0.00012048, 0.00050749],
  "force_scale_gradient": 0.00352685
}

The optional PNG plots the two slider trajectories. Its dashed final segment shows that resetting arena_0 returns only the first slider to zero.

For an image rendered by EmbodiChain’s native offscreen camera, run:

python scripts/tutorials/sim/simple_newton_solver/demo.py --device cpu \
    --render-path simple_newton_offscreen.png

The resulting PNG has environment 0 and 1 in the left and right columns, with initial and after-30-step views in the top and bottom rows. The script reserves FastRT before constructing the World, creates a CameraCfg in each arena, renders through SimulationManager.render_camera_group(), and reads the RGB frames from Camera.get_data(). This needs a working native GPU renderer even when the solver runs on the CPU.

To record the same offscreen cameras as a video, run:

python scripts/tutorials/sim/simple_newton_solver/demo.py --device cpu \
    --video-path simple_newton_offscreen.mp4

The H.264 MP4 places the two environments side by side and records all 30 native simulation steps at 10 fps, with short holds on the initial and final poses. It requires ffmpeg with libx264 on PATH. Combine --render-path and --video-path to save both outputs in one run.

To inspect the actual EmbodiChain scene in Viser, run:

python scripts/tutorials/sim/simple_newton_solver/demo.py --device cpu \
    --viser --viser-seconds 60

Open http://127.0.0.1:8080 while the script runs. Viser receives both URDF slider meshes, then shows 30 native simulation steps. The scene remains open for the requested number of seconds after replay. Use --viser-port PORT if 8080 is in use. The base link has no visual geometry, so the visible objects are the two cubes. This browser view uses EmbodiChain’s SimulationManager.capture_visualization() and does not require a native render window.

Follow the data flow#

  1. demo.py passes the local SimpleSolverProvider class to NewtonPhysicsCfg through DexSim’s ProviderNewtonSolverCfg. The direct factory path does not require package entry-point registration.

  2. SimulationManager.prepare() finalizes the scene and asks DexSim to create a fresh provider for the model. The provider validates the slider model and declares effort-only controls, reset support and no CUDA Graph support.

  3. _SliderDynamics.step() applies effort, spring force and damping, then updates velocity and position with semi-implicit Euler. Its Torch operations preserve gradients in the functional path.

  4. The native SolverBase adapter calls that same transition under torch.no_grad() and writes the resulting state to the next Newton state. demo.py checks that one native step matches one functional step.

  5. Functional stepping with publish=False leaves the live scene untouched. publish=True publishes a detached physical state and advances the Scene clock once. The returned functional tensors retain their gradient graph. Reset selects arenas independently.

For a slider coordinate q, velocity v, effort u, trainable scale g and effective mass m, the unconstrained transition is:

force = clamp(g * u, -effort_limit, effort_limit)
acceleration = (force - stiffness * q - damping * v) / m
v_next = clamp(v + dt * acceleration, -velocity_limit, velocity_limit)
q_next = clamp(q + dt * v_next, lower_limit, upper_limit)

The implementation also includes joint damping in damping and stops the slider when a position limit is reached. Gradients at clamp boundaries are piecewise-defined; the example stays away from those boundaries.

Complete provider (solver.py)
  1# ----------------------------------------------------------------------------
  2# Copyright (c) 2021-2026 DexForce Technology Co., Ltd.
  3#
  4# Licensed under the Apache License, Version 2.0 (the "License");
  5# you may not use this file except in compliance with the License.
  6# You may obtain a copy of the License at
  7#
  8#     http://www.apache.org/licenses/LICENSE-2.0
  9#
 10# Unless required by applicable law or agreed to in writing, software
 11# distributed under the License is distributed on an "AS IS" BASIS,
 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13# See the License for the specific language governing permissions and
 14# limitations under the License.
 15# ----------------------------------------------------------------------------
 16"""Tutorial spring-slider solver demonstrating the DexSim extension contract."""
 17
 18from __future__ import annotations
 19
 20import math
 21from collections.abc import Mapping
 22from contextlib import nullcontext
 23from typing import Any
 24
 25import newton
 26import numpy as np
 27import torch
 28import warp as wp
 29from newton.solvers import SolverBase
 30from dexsim.engine import newton_physics as _sdk
 31
 32from embodichain.utils.math import quat_apply
 33
 34__all__ = ["SimpleSolverProvider"]
 35
 36# Catalogues and autodoc may inspect the provider with the released SDK.
 37# Resolve annotations when available; instance creation enforces the runtime API.
 38try:
 39    from dexsim.engine.newton_physics import (
 40        FunctionalSolverState,
 41        NewtonSolverCapabilities,
 42        NewtonSolverContext,
 43        NewtonSolverExtension,
 44    )
 45except ImportError:
 46    FunctionalSolverState = Any
 47    NewtonSolverCapabilities = Any
 48    NewtonSolverContext = Any
 49    NewtonSolverExtension = Any
 50
 51
 52def _torch_scope(device: wp.context.Device) -> Any:
 53    return (
 54        torch.cuda.stream(wp.stream_to_torch(wp.get_stream(device)))
 55        if device.is_cuda
 56        else nullcontext()
 57    )
 58
 59
 60def _tensor(array: wp.array) -> torch.Tensor:
 61    # Warp cannot expose a null pointer as a Torch tensor for empty arrays.
 62    if array.size == 0:
 63        return torch.as_tensor(array.numpy(), device=str(array.device))
 64    return wp.to_torch(array)
 65
 66
 67class _SliderDynamics:
 68    def __init__(self, model: newton.Model, options: Mapping[str, Any]) -> None:
 69        unknown = set(options) - {"stiffness", "damping", "force_scale"}
 70        if unknown:
 71            raise ValueError(f"Unknown simple solver options: {sorted(unknown)}")
 72        values = {"stiffness": 1.0, "damping": 0.1, "force_scale": 1.0}
 73        values.update(options)
 74        for name, value in values.items():
 75            if not math.isfinite(float(value)) or (
 76                name != "force_scale" and float(value) < 0
 77            ):
 78                raise ValueError(f"Invalid simple solver option {name}={value!r}")
 79        self.model = model
 80        self.stiffness = float(values["stiffness"])
 81        self.damping = float(values["damping"])
 82        self.force_scale = torch.tensor(
 83            float(values["force_scale"]), device=str(model.device), requires_grad=True
 84        )
 85        self.refresh()
 86
 87    def refresh(self) -> None:
 88        model = self.model
 89        types = model.joint_type.numpy()
 90        parents, children = model.joint_parent.numpy(), model.joint_child.numpy()
 91        moving = np.flatnonzero(types == int(newton.JointType.PRISMATIC))
 92        if (
 93            not len(moving)
 94            or not np.isin(
 95                types, [int(newton.JointType.FIXED), int(newton.JointType.PRISMATIC)]
 96            ).all()
 97            or len(children) != model.body_count
 98            or len(set(children.tolist())) != model.body_count
 99            or any(int(children[j]) in parents for j in moving)
100            or not model.joint_enabled.numpy().all()
101        ):
102            raise ValueError(
103                "simple supports independent prismatic leaf joints with fixed ancestors only"
104            )
105        if model.particle_count or getattr(model, "constraint_mimic_count", 0):
106            raise ValueError("simple does not support particles or mimic constraints")
107        moving_shapes = np.isin(model.shape_body.numpy(), children[moving])
108        if np.any(
109            model.shape_flags.numpy()[moving_shapes]
110            & int(newton.ShapeFlags.COLLIDE_SHAPES)
111        ):
112            raise ValueError(
113                "simple does not support collision shapes on moving bodies"
114            )
115        if np.any(model.gravity.numpy()):
116            raise ValueError("simple requires zero gravity")
117        for name in ("joint_target_ke", "joint_target_kd", "joint_friction"):
118            if np.any(getattr(model, name).numpy()):
119                raise ValueError(f"simple does not support nonzero {name}")
120        self.children = torch.as_tensor(
121            children[moving], dtype=torch.long, device=str(model.device)
122        )
123        if np.any(
124            model.body_flags.numpy()[children[moving]] & int(newton.BodyFlags.KINEMATIC)
125        ):
126            raise ValueError("simple requires dynamic slider bodies")
127        mass = _tensor(model.body_mass)[self.children].detach().clone()
128        if not bool(torch.isfinite(mass).all() and (mass > 0).all()):
129            raise ValueError("simple requires finite positive slider mass")
130        self.mass = mass + _tensor(model.joint_armature).detach().clone()
131        if not bool(torch.isfinite(self.mass).all() and (self.mass > 0).all()):
132            raise ValueError("simple requires finite positive effective mass")
133        self.drag = _tensor(model.joint_damping).detach().clone() + self.damping
134        self.lower = _tensor(model.joint_limit_lower).detach().clone()
135        self.upper = _tensor(model.joint_limit_upper).detach().clone()
136        self.effort_limit = _tensor(model.joint_effort_limit).detach().clone()
137        self.velocity_limit = _tensor(model.joint_velocity_limit).detach().clone()
138        child_frames = _tensor(model.joint_X_c)[
139            torch.as_tensor(moving, device=str(model.device))
140        ]
141        self.local_axes = quat_apply(
142            child_frames[:, 3:], _tensor(model.joint_axis)
143        ).detach()
144
145    def create_state(self, native_state: newton.State) -> FunctionalSolverState:
146        return FunctionalSolverState(
147            {
148                name: _tensor(getattr(native_state, name)).detach().clone()
149                for name in ("joint_q", "joint_qd", "body_q", "body_qd", "body_qdd")
150                if getattr(native_state, name, None) is not None
151            }
152        )
153
154    def parameters(self) -> Mapping[str, torch.Tensor]:
155        return {"force_scale": self.force_scale}
156
157    def step(
158        self,
159        state: FunctionalSolverState,
160        control: torch.Tensor,
161        parameters: Mapping[str, torch.Tensor],
162        dt: float,
163    ) -> FunctionalSolverState:
164        q, qd = state.physical["joint_q"], state.physical["joint_qd"]
165        if not isinstance(control, torch.Tensor) or control.shape != q.shape:
166            raise ValueError(
167                "simple control must be a tensor shaped (joint_dof_count,)"
168            )
169        if control.device != q.device or control.dtype != q.dtype:
170            raise ValueError("simple control must match the state device and dtype")
171        if not math.isfinite(dt) or dt <= 0:
172            raise ValueError("simple dt must be positive and finite")
173        force = (parameters["force_scale"] * control).clamp(
174            -self.effort_limit, self.effort_limit
175        )
176        acceleration = (force - self.stiffness * q - self.drag * qd) / self.mass
177        velocity = (qd + dt * acceleration).clamp(
178            -self.velocity_limit, self.velocity_limit
179        )
180        proposed = q + dt * velocity
181        position = proposed.clamp(self.lower, self.upper)
182        velocity = torch.where(
183            proposed != position, torch.zeros_like(velocity), velocity
184        )
185        acceleration = (velocity - qd) / dt
186        # Advance the existing pose by the coordinate delta so explicit root
187        # placement and randomized states are preserved across transitions.
188        previous_pose = state.physical["body_q"]
189        axes = quat_apply(previous_pose[self.children, 3:], self.local_axes)
190        pose = previous_pose.index_copy(
191            0,
192            self.children,
193            torch.cat(
194                (
195                    previous_pose[self.children, :3] + axes * (position - q)[:, None],
196                    previous_pose[self.children, 3:],
197                ),
198                dim=1,
199            ),
200        )
201        spatial = torch.zeros(
202            (self.model.body_count, 6), device=q.device, dtype=q.dtype
203        )
204        zeros = torch.zeros_like(axes)
205        body_qd = spatial.index_copy(
206            0, self.children, torch.cat((axes * velocity[:, None], zeros), dim=1)
207        )
208        body_qdd = spatial.index_copy(
209            0,
210            self.children,
211            torch.cat((axes * acceleration[:, None], zeros), dim=1),
212        )
213        return FunctionalSolverState(
214            {
215                "joint_q": position,
216                "joint_qd": velocity,
217                "body_q": pose,
218                "body_qd": body_qd,
219                "body_qdd": body_qdd,
220            }
221        )
222
223    def commit(self, state: FunctionalSolverState) -> None:
224        # There is no recurrent history. DexSim owns physical publication.
225        pass
226
227    def reset_history(
228        self,
229        state: FunctionalSolverState,
230        reset_state: FunctionalSolverState,
231        world_mask: wp.array | None,
232    ) -> tuple[Mapping[str, Any], None]:
233        return {}, None
234
235
236class _NativeSliderSolver(SolverBase):
237    def __init__(self, model: newton.Model, dynamics: _SliderDynamics) -> None:
238        super().__init__(model)
239        self.dynamics = dynamics
240
241    def step(
242        self,
243        state_in: newton.State,
244        state_out: newton.State,
245        control: newton.Control | None,
246        contacts: newton.Contacts | None,
247        dt: float,
248        *,
249        observables: SolverBase.Observables | None = None,
250    ) -> None:
251        self.validate_observables(observables, contacts)
252        with _torch_scope(self.model.device), torch.no_grad():
253            source = self.dynamics.create_state(state_in)
254            force = _tensor(self.model.joint_f if control is None else control.joint_f)
255            result = self.dynamics.step(source, force, self.dynamics.parameters(), dt)
256            for name, value in result.physical.items():
257                destination = getattr(state_out, name, None)
258                if destination is not None:
259                    _tensor(destination).copy_(value)
260
261    def notify_model_changed(self, flags: newton.ModelFlags | int) -> None:
262        with _torch_scope(self.model.device):
263            self.dynamics.refresh()
264
265
266class SimpleSolverProvider:
267    """Create a minimal, differentiable spring-slider Newton extension.
268
269    Each moving body must be a dynamic prismatic leaf attached to the world or
270    fixed ancestors. Visual shapes and static ground are allowed; moving-body
271    collisions, particles, mimic
272    constraints, gravity, target drives and friction are rejected. Joint mass,
273    armature, damping and effort/velocity/position limits are respected. Limits
274    use hard clamping; gradients at their boundaries are piecewise-defined.
275
276    Options are ``stiffness`` (N/m, default 1), ``damping`` (N s/m, default 0.1)
277    and trainable ``force_scale`` (default 1). Native and functional execution
278    share semi-implicit Euler: first update velocity, then position. This is an
279    eager educational solver, not a general robot/contact solver. Parameters
280    belong to one finalized model and must be checkpointed across rebuilds.
281    """
282
283    def __init__(self) -> None:
284        """Require the extension SDK when the provider is selected.
285
286        Raises:
287            ImportError: The installed SDK lacks the functional service contract.
288        """
289        if (
290            not hasattr(_sdk, "FunctionalDynamics")
291            or not hasattr(NewtonSolverCapabilities, "native_body_accelerations")
292            or not hasattr(NewtonSolverCapabilities, "supported_particle_kinds")
293        ):
294            raise ImportError(
295                "The simple solver requires DexSim's FunctionalDynamics extension API "
296                "with explicit control, particle and acceleration capabilities; "
297                "install a compatible DexSim build."
298            )
299        self.capabilities = NewtonSolverCapabilities(
300            reset=True,
301            cuda_graph=False,
302            external_wrenches=False,
303            supported_control_fields=("joint_f",),
304            runtime_controls=False,
305            native_body_accelerations=True,
306            supported_particle_kinds=(),
307        )
308
309    def register_custom_attributes(
310        self,
311        builder: newton.ModelBuilder,
312        options: Mapping[str, Any],
313    ) -> None:
314        """Use standard Newton attributes; no custom registration is needed.
315
316        Args:
317            builder: Builder owned by DexSim before model finalization.
318            options: Solver options validated during creation.
319        """
320
321    def create(
322        self,
323        context: NewtonSolverContext,
324        options: Mapping[str, Any],
325    ) -> NewtonSolverExtension:
326        """Validate the model and create native and functional views of one solver.
327
328        Args:
329            context: Finalized model and resources borrowed from DexSim.
330            options: Spring stiffness, damping and initial force scale.
331
332        Returns:
333            Model-scoped extension with an independent functional trajectory API.
334
335        Raises:
336            ValueError: The model or options exceed the documented supported scope.
337        """
338        with _torch_scope(context.device):
339            dynamics = _SliderDynamics(context.model, options)
340        return NewtonSolverExtension(
341            native_solver=_NativeSliderSolver(context.model, dynamics),
342            capabilities=self.capabilities,
343            functional=dynamics,
344        )
Complete scene and rollout (demo.py)
  1# ----------------------------------------------------------------------------
  2# Copyright (c) 2021-2026 DexForce Technology Co., Ltd.
  3#
  4# Licensed under the Apache License, Version 2.0 (the "License");
  5# you may not use this file except in compliance with the License.
  6# You may obtain a copy of the License at
  7#
  8#     http://www.apache.org/licenses/LICENSE-2.0
  9#
 10# Unless required by applicable law or agreed to in writing, software
 11# distributed under the License is distributed on an "AS IS" BASIS,
 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13# See the License for the specific language governing permissions and
 14# limitations under the License.
 15# ----------------------------------------------------------------------------
 16"""Run ordinary and functional stepping through public EmbodiChain/Scene APIs."""
 17
 18from __future__ import annotations
 19
 20import argparse
 21import json
 22import subprocess
 23import time
 24from pathlib import Path
 25
 26import numpy as np
 27import torch
 28from dexsim.engine.newton_physics import ProviderNewtonSolverCfg
 29
 30from embodichain.lab.sim import SimulationManager, SimulationManagerCfg
 31from embodichain.lab.sim.cfg import (
 32    ArticulationCfg,
 33    CollisionPropertiesCfg,
 34    NewtonPhysicsCfg,
 35    RenderCfg,
 36    RigidBodyPhysicsCfg,
 37)
 38from embodichain.lab.sim.sensors import Camera, CameraCfg
 39from embodichain.lab.visualization import VisualizationCfg, ViserServerCfg
 40from solver import SimpleSolverProvider
 41
 42
 43def _save_preview(
 44    positions: list[torch.Tensor], reset_position: torch.Tensor, path: Path
 45) -> None:
 46    """Plot the measured functional trajectory and selected-arena reset."""
 47    import matplotlib
 48
 49    matplotlib.use("Agg")
 50    import matplotlib.pyplot as plt
 51
 52    values = torch.stack(positions).detach().cpu().numpy()
 53    reset_values = reset_position.detach().cpu().numpy()
 54    figure, axis = plt.subplots(figsize=(8, 4.5))
 55    for arena_id, color in enumerate(("#2563eb", "#ea580c")):
 56        axis.plot(
 57            range(len(values)),
 58            values[:, arena_id],
 59            marker="o",
 60            color=color,
 61            label=f"arena_{arena_id}",
 62        )
 63        axis.plot(
 64            (len(values) - 1, len(values)),
 65            (values[-1, arena_id], reset_values[arena_id]),
 66            linestyle="--",
 67            marker="o",
 68            color=color,
 69        )
 70    axis.set_xticks(range(len(values) + 1))
 71    axis.set_xticklabels([*(str(step) for step in range(len(values))), "reset"])
 72    axis.set_xlabel("Functional transition")
 73    axis.set_ylabel("Joint position (m)")
 74    axis.set_title("Spring-slider tutorial: rollout and selected-arena reset")
 75    axis.grid(alpha=0.25)
 76    axis.legend()
 77    figure.tight_layout()
 78    path.parent.mkdir(parents=True, exist_ok=True)
 79    figure.savefig(path, dpi=160)
 80    plt.close(figure)
 81
 82
 83def _capture_rgb(sim: SimulationManager, camera: Camera) -> np.ndarray:
 84    """Read the two native offscreen views through EmbodiChain's camera API."""
 85    sim.render_camera_group([camera.group_id])
 86    camera.update(fetch_only=True)
 87    return camera.get_data()["color"][..., :3].cpu().numpy().copy()
 88
 89
 90def _save_offscreen_preview(before: np.ndarray, after: np.ndarray, path: Path) -> None:
 91    """Save initial and replayed RGB frames for both environments."""
 92    from PIL import Image, ImageDraw, ImageFont
 93
 94    height, width = before.shape[1:3]
 95    image = Image.new("RGB", (2 * width, 2 * height))
 96    for row, frames in enumerate((before, after)):
 97        for env_id in range(2):
 98            image.paste(Image.fromarray(frames[env_id]), (env_id * width, row * height))
 99    draw = ImageDraw.Draw(image)
100    try:
101        font = ImageFont.truetype("DejaVuSans.ttf", 18)
102    except OSError:
103        font = ImageFont.load_default()
104    for row, phase in enumerate(("Initial", "After 30 steps")):
105        for env_id in range(2):
106            x, y = env_id * width, row * height
107            draw.rectangle((x, y, x + width - 1, y + 32), fill="white")
108            draw.text(
109                (x + 10, y + 5),
110                f"{phase} - environment {env_id}",
111                fill="black",
112                font=font,
113            )
114    path.parent.mkdir(parents=True, exist_ok=True)
115    image.save(path)
116
117
118def _start_video_encoder(path: Path, width: int, height: int) -> subprocess.Popen:
119    """Start an H.264 encoder for the two side-by-side offscreen views."""
120    path.parent.mkdir(parents=True, exist_ok=True)
121    try:
122        return subprocess.Popen(
123            [
124                "ffmpeg",
125                "-loglevel",
126                "error",
127                "-y",
128                "-f",
129                "rawvideo",
130                "-pixel_format",
131                "rgb24",
132                "-video_size",
133                f"{2 * width}x{height}",
134                "-framerate",
135                "10",
136                "-i",
137                "pipe:0",
138                "-an",
139                "-c:v",
140                "libx264",
141                "-pix_fmt",
142                "yuv420p",
143                str(path),
144            ],
145            stdin=subprocess.PIPE,
146            stderr=subprocess.PIPE,
147        )
148    except FileNotFoundError as exc:
149        raise RuntimeError("--video-path requires ffmpeg on PATH") from exc
150
151
152def _write_video_frame(encoder: subprocess.Popen, rgb: np.ndarray) -> None:
153    """Append one RGB frame per environment without retaining the video in RAM."""
154    combined = np.ascontiguousarray(np.concatenate((rgb[0], rgb[1]), axis=1))
155    encoder.stdin.write(combined.tobytes())
156
157
158def _finish_video_encoder(encoder: subprocess.Popen) -> None:
159    """Flush the encoder and report an unsuccessful conversion."""
160    encoder.stdin.close()
161    error = encoder.stderr.read().decode(errors="replace")
162    if encoder.wait() != 0:
163        raise RuntimeError(f"ffmpeg could not encode the tutorial video: {error}")
164
165
166def run(
167    device: str,
168    preview_path: Path | None = None,
169    *,
170    render_path: Path | None = None,
171    video_path: Path | None = None,
172    viser: bool = False,
173    viser_port: int = 8080,
174    viser_seconds: float = 30.0,
175) -> dict[str, object]:
176    """Demonstrate direct provider creation, parity, gradients and partial reset."""
177    if viser_seconds < 0:
178        raise ValueError("viser_seconds must be non-negative")
179    config = SimulationManagerCfg(
180        headless=True,
181        render_cfg=RenderCfg(
182            renderer=(
183                "fast-rt"
184                if render_path is not None or video_path is not None
185                else "auto"
186            )
187        ),
188        visualization=VisualizationCfg(
189            backend="viser" if viser else "none",
190            env_ids=[0, 1],
191            viser_server=ViserServerCfg(port=viser_port),
192        ),
193        num_envs=2,
194        enable_entity_gizmo=False,
195        startup_summary="off",
196        physics_cfg=NewtonPhysicsCfg(
197            device=device,
198            gravity=(0.0, 0.0, 0.0),
199            physics_dt=0.02,
200            num_substeps=2,
201            requires_grad=True,
202            use_cuda_graph=False,
203            collision_cfg=None,
204            solver_cfg=ProviderNewtonSolverCfg(
205                provider_factory=SimpleSolverProvider,
206                options={"stiffness": 2.0, "damping": 0.2},
207            ),
208        ),
209    )
210    sim = SimulationManager(
211        config,
212        requires_native_renderer=render_path is not None or video_path is not None,
213    )
214    try:
215        slider = sim.add_articulation(
216            ArticulationCfg(
217                uid="slider",
218                fpath=str(Path(__file__).with_name("slider.urdf")),
219                asset_physics_mode="overlay",
220                attrs=RigidBodyPhysicsCfg(
221                    collision_props=CollisionPropertiesCfg(collision_enabled=False),
222                ),
223            )
224        )
225        sim.prepare()
226        camera = None
227        if render_path is not None or video_path is not None:
228            camera = sim.add_sensor(
229                CameraCfg(
230                    uid="slider_preview",
231                    width=640,
232                    height=480,
233                    intrinsics=(600, 600, 320, 240),
234                    extrinsics=CameraCfg.ExtrinsicsCfg(
235                        eye=(0.7, -0.8, 0.55),
236                        target=(0.25, 0.0, 0.2),
237                        up=(0.0, 0.0, 1.0),
238                    ),
239                    enable_color=True,
240                )
241            )
242        if viser:
243            manifest = sim.refresh_visualization()
244            if not any(node.kind == "articulation_link" for node in manifest.nodes):
245                raise RuntimeError("Viser scene has no slider visual geometry")
246            sim.capture_visualization(force=True)
247        scene = sim.spawn_result
248        initial = scene.create_functional_state()
249        params = scene.functional_parameters()
250        force = torch.tensor([4.0, 6.0], device=device, requires_grad=True)
251
252        predicted = scene.functional_step(initial, force, publish=False)
253        torch.testing.assert_close(
254            slider.get_qpos().flatten(), initial.physical["joint_q"]
255        )
256        slider.set_qf(force.detach().reshape(2, 1))
257        sim.update(step=1)
258        torch.testing.assert_close(
259            slider.get_qpos().flatten(), predicted.physical["joint_q"]
260        )
261
262        trajectory = initial
263        positions = [initial.physical["joint_q"]]
264        for _ in range(6):
265            trajectory = scene.functional_step(trajectory, force, publish=False)
266            positions.append(trajectory.physical["joint_q"])
267        saved = trajectory.physical["joint_q"].clone()
268        published = scene.functional_step(trajectory, force, publish=True)
269        positions.append(published.physical["joint_q"])
270        torch.testing.assert_close(
271            slider.get_qpos().flatten(), published.physical["joint_q"]
272        )
273        torch.testing.assert_close(trajectory.physical["joint_q"], saved)
274
275        reset = scene.reset_functional_state(published, arenas=["arena_0"])
276        torch.testing.assert_close(
277            reset.physical["joint_q"][0], initial.physical["joint_q"][0]
278        )
279        torch.testing.assert_close(
280            reset.physical["joint_q"][1], published.physical["joint_q"][1]
281        )
282        if preview_path is not None:
283            _save_preview(positions, reset.physical["joint_q"], preview_path)
284        loss = (
285            trajectory.physical["joint_q"].square().sum()
286            + reset.physical["joint_q"].square().sum()
287        )
288        grad_force, grad_scale = torch.autograd.grad(
289            loss, (force, params["force_scale"])
290        )
291        assert torch.isfinite(grad_force).all() and (grad_force.abs() > 0).all()
292        assert torch.isfinite(grad_scale) and grad_scale.abs() > 0
293        slider.reset(env_ids=[0])
294        torch.testing.assert_close(
295            slider.get_qpos()[0].flatten(), initial.physical["joint_q"][:1]
296        )
297        result = {
298            "device": device,
299            "native_functional_parity": True,
300            "published_position": published.physical["joint_q"].detach().tolist(),
301            "partial_reset_position": reset.physical["joint_q"].detach().tolist(),
302            "force_gradient": grad_force.tolist(),
303            "force_scale_gradient": grad_scale.item(),
304        }
305        if preview_path is not None:
306            result["preview_path"] = str(preview_path)
307        if viser or render_path is not None or video_path is not None:
308            # Replay in the live EmbodiChain scene for Viser and/or native RGB.
309            # The numerical and gradient checks above remain independent.
310            slider.reset()
311            slider.set_qf(force.detach().reshape(2, 1))
312            initial_rgb = _capture_rgb(sim, camera) if camera is not None else None
313            encoder = (
314                _start_video_encoder(video_path, camera.cfg.width, camera.cfg.height)
315                if video_path is not None
316                else None
317            )
318            final_rgb = None
319            try:
320                if encoder is not None:
321                    for _ in range(5):
322                        _write_video_frame(encoder, initial_rgb)
323                for _ in range(30):
324                    sim.update(step=1)
325                    if viser:
326                        sim.capture_visualization(force=True)
327                        time.sleep(0.05)
328                    if encoder is not None:
329                        final_rgb = _capture_rgb(sim, camera)
330                        _write_video_frame(encoder, final_rgb)
331                if encoder is not None:
332                    for _ in range(5):
333                        _write_video_frame(encoder, final_rgb)
334            finally:
335                if encoder is not None:
336                    _finish_video_encoder(encoder)
337            result["visualized_position"] = slider.get_qpos().flatten().tolist()
338            if camera is not None:
339                if render_path is not None:
340                    if final_rgb is None:
341                        final_rgb = _capture_rgb(sim, camera)
342                    _save_offscreen_preview(initial_rgb, final_rgb, render_path)
343                    result["render_path"] = str(render_path)
344                if video_path is not None:
345                    result["video_path"] = str(video_path)
346        if viser:
347            result["viser_url"] = f"http://127.0.0.1:{viser_port}"
348            result["visualized_links"] = sum(
349                node.kind == "articulation_link" for node in manifest.nodes
350            )
351            print(f"Viser preview: {result['viser_url']}", flush=True)
352            time.sleep(viser_seconds)
353        return result
354    finally:
355        sim.destroy(exit_process=False)
356
357
358if __name__ == "__main__":
359    parser = argparse.ArgumentParser(description=__doc__)
360    parser.add_argument("--device", default="cpu", help="cpu or cuda:0")
361    parser.add_argument(
362        "--preview-path", type=Path, help="save the rollout and reset plot as PNG"
363    )
364    parser.add_argument(
365        "--render-path",
366        type=Path,
367        help="save EmbodiChain offscreen RGB before and after replay",
368    )
369    parser.add_argument(
370        "--video-path", type=Path, help="record a side-by-side offscreen MP4"
371    )
372    parser.add_argument(
373        "--viser", action="store_true", help="replay in EmbodiChain Viser"
374    )
375    parser.add_argument("--viser-port", type=int, default=8080)
376    parser.add_argument(
377        "--viser-seconds",
378        type=float,
379        default=30.0,
380        help="seconds to keep the browser scene open after replay",
381    )
382    args = parser.parse_args()
383    try:
384        print(
385            json.dumps(
386                run(
387                    args.device,
388                    args.preview_path,
389                    render_path=args.render_path,
390                    video_path=args.video_path,
391                    viser=args.viser,
392                    viser_port=args.viser_port,
393                    viser_seconds=args.viser_seconds,
394                ),
395                indent=2,
396            )
397        )
398    finally:
399        SimulationManager.flush_cleanup_queue()

Scope and next steps#

This educational solver accepts independent dynamic prismatic leaves with fixed ancestors and zero gravity. It rejects moving-body collisions, particles, mimic constraints, friction and position/velocity target drives. Its parameters belong to one finalized model; save learned values explicitly before rebuilding the scene. See the tutorial directory’s README.md for SDK prerequisites, limit behavior, and notes about differentiating Cartesian losses.