Python API

World

An Elodin simulation begins with a World object. The World object is the root of the simulation hierarchy and provides methods for composing and running the simulation. The World object also provides helper methods for displaying entities and graphs in the editor.

class elodin.World

The Elodin simulation world.

  • __init__() -> elodin.World

    Create a new world object.

  • spawn(archetypes, name) -> elodin.EntityId

    Spawn a new entity with the given archetypes and name.

    • archetypes : one or many Archetypes,
    • name : optional name of the entity
  • insert(id, archetypes) -> None

    Insert archetypes into an existing entity.

  • insert_asset(asset) -> handle reference

    Insert a 3D asset into the world.

  • shape(mesh, material) -> elodin.Shape

    Create a shape as an Elodin Shape Archetype.

    • mesh: the mesh of the shape,
    • material: the material of the shape
  • glb(url) -> elodin.Scene

    Load a GLB asset as an Elodin Scene Archetype.

    • url: the URL or filepath of the GLB asset
  • sensor_camera(entity, name, width=None, height=None, fov=None, near=0.01, far=1000.0, pos_offset=[0,0,0], rot_offset=[0,0,0], format="rgba", effect="normal", effect_params={}, camera_model=None, lens_hfov=None, create_frustum=False, show_ellipsoids=False, frustums_color=None, projection_color=None, frustums_thickness=0.006, frustums_up_marker="none", frustums_up_marker_overlay=True, fps=None, cinematic=False, ev100=None, bloom=None, environment=None, frustums_face_alpha=0.17647059) -> None

    Register a virtual sensor camera on an entity. The headless GPU render-server emits one frame per camera every 1 / fps µs of simulation time and pushes the bytes back to the database. The simulation reads frames asynchronously with ctx.read_msg("entity.name", timestamp=...).

    • entity : elodin.EntityId, the entity the camera is attached to.
    • name : string, the camera name. Combined with the entity name to form the full identifier (e.g., entity "drone" + name "scene_cam" → "drone.scene_cam").
    • width : int | None, frame width in pixels. Required unless supplied by camera_model.
    • height : int | None, frame height in pixels. Required unless supplied by camera_model.
    • fov : float | None, vertical field of view in degrees. Defaults to 90.0 without a model. Mutually exclusive with lens_hfov.
    • near : float, near clipping plane, defaults to 0.01.
    • far : float, far clipping plane, defaults to 1000.0.
    • pos_offset : list[float], body-frame translation from the entity origin in metres, defaults to [0, 0, 0]. Applied first.
    • rot_offset : list[float], body-frame rotation as [roll, pitch, yaw] in degrees (intrinsic X/Y/Z, aerospace convention), defaults to [0, 0, 0] (camera looks along body +X with body +Z as up). Applied around the camera's own axes after pos_offset and inherits the entity's attitude — when the host banks, the camera image banks with it.
    • format : string, "rgba" (RGBA8), "gray8" (luma), or "h264" (Annex-B encoded in the render server). h264 uses a GPU encoder when available (h264_nvenc, h264_videotoolbox) and OpenH264 otherwise. Override with ELODIN_H264_ENCODER=cpu|auto|<ffmpeg-name>. Defaults to "rgba".
    • effect : string, final GPU sensor-output effect: "normal", "thermal", "night_vision", "depth", or "lwir". Defaults to "normal". "depth" uses real linearized camera depth.
    • effect_params : dict, effect-specific nested parameters. LWIR supports palette, agc, dde, mtf_blur_px, detector noise, scene temperatures, atmospheric transmission, and sky_offset_dn (cosmetic sky black level). Auto AGC adapts from the scene temperature statistics with sky masked out and freezes on sky-only views.
    • camera_model : string | None, calibrated camera preset. "boson640p" supplies 640×512, 60 Hz, the Boson+ detector defaults, and an 18° horizontal lens.
    • lens_hfov : float | None, physical horizontal field of view in degrees. Converted to vertical fov using the resolved image aspect ratio. Mutually exclusive with fov.
    • create_frustum : bool, draw this camera's 3D frustum in schematic viewports that enable show_frustums. Defaults to False.
    • frustums_color : three- or four-element normalized RGB(A) list for the frustum edges.
    • projection_color : three- or four-element normalized RGB(A) list for the separate 2D far-plane projection overlay.
    • show_ellipsoids : bool, render ellipsoid debug objects in this sensor camera. Defaults to False.
    • fps : float | None, target rendering rate in frames per second of sim time. The renderer treats this as a target — if the GPU cannot sustain it (e.g., several high-resolution cameras), frames are spaced further apart in sim time but the simulation never blocks. Defaults to the camera-model rate, or 30.0 without a model.
    • cinematic : bool, same meaning as KDL viewport cinematic=#true. When true, the sibling render-server loads the cinematic Earth stack for this camera. Defaults to False.
    • ev100 : float | None, camera exposure. With cinematic=True the default is 13.5. Requires cinematic=True.
    • bloom : dict | None, viewport bloom settings (preset, intensity, threshold, threshold_softness). None with cinematic=True uses the cinematic preset. Requires cinematic=True.
    • environment : dict | None, schematic environment { } (sun, ambient_scale, sky_color, atmosphere, earth). earth may be True for the house look. Omitted with cinematic=True implies Earth, a 100 klx sun, and ambient 0.05. Requires cinematic=True.
    • frustums_face_alpha : float, opacity of the filled 3D frustum volume from 0.0 to 1.0, independent of edge and 2D-projection alpha. Defaults to the historical 45/255 (0.17647059).

    At most one cinematic environment owner is allowed: a KDL viewport cinematic=#true or sensor_camera(cinematic=True), never both, never two of either. Mixing them raises ValueError before the GPU starts.

    The camera transform follows the entity as a rigid body: as the entity moves and rotates, the camera mount position and orientation rotate with it in body frame.

    Frames render continuously and are pushed to the DB automatically — there is no per-call render trigger. To simulate camera latency, read with a timestamp offset: ctx.read_msg("drone.scene_cam", timestamp=ctx.timestamp - 33_000) returns the frame as it would have appeared 33 ms ago.

  • thermal_tag(entity, temperature_c, emissivity=1.0) -> None

    Assign an apparent LWIR surface temperature to an entity's rendered mesh. LWIR sensor cameras render tagged entities through a temperature mask, allowing an object's thermal polarity to differ from its visible color.

    • entity : elodin.EntityId, the entity whose object_3d visual is tagged.
    • temperature_c : float, apparent surface temperature in degrees Celsius.
    • emissivity : float, value from 0.0 to 1.0. Defaults to 1.0.
    world.thermal_tag(target_drone, temperature_c=18.0, emissivity=0.92)
    world.sensor_camera(
        entity=aircraft,
        name="ir_cam",
        camera_model="boson640p",
        lens_hfov=18.0,
        effect="lwir",
        effect_params={
            "palette": "white_hot",
            "agc": {"mode": "auto", "low": 0.01, "high": 0.99},
        },
    )
  • run(system, simulation_rate, generate_real_time, telemetry_rate, default_playback_speed, max_ticks, optimize, is_canceled, pre_step, post_step, db_path, interactive, start_timestamp, log_level, backend, on_receipt, workers, pre_commit, timing, synchronous_commits, determinism_trace) -> None

    Run the simulation.

    • system : elodin.System, the systems to run, can be supplied as a list of systems delineated by pipes.
    • simulation_rate : float, optional, simulation frequency in Hz. Defaults to 120.0.
    • generate_real_time : bool, optional, if True, pace tick generation to real time (default False).
    • telemetry_rate : float | None, optional, DB commit/sync frequency in Hz. Defaults to simulation_rate. Must evenly divide simulation_rate.
    • default_playback_speed : float, optional, the default playback speed of the Elodin client when running this simulation, defaults to 1.0 (real-time).
    • max_ticks : integer, optional, the maximum number of ticks to run the simulation for before stopping.
    • optimize : bool, optional flag to enable runtime optimizations for the simulation code, defaults to False. If optimizations are enabled, the simulation will start slower but run faster.
    • is_canceled : Callable[[], bool], optional, a polling function checked during the simulation loop. If it returns True, the simulation exits gracefully. Useful for integrating with external control systems (e.g., a GUI stop button, or a watchdog timeout).
    • pre_step : Callable[[int, StepContext], None], optional, a callback function called before each simulation tick. Receives the tick number and a elodin.StepContext for direct database access. Useful for injecting external data (e.g., from hardware-in-the-loop systems) before the physics step runs.
    • post_step : Callable[[int, StepContext], None], optional, a callback function called after each simulation tick. Receives the tick number and a elodin.StepContext for direct database access. Useful for reading simulation results and sending data to external systems (e.g., SITL flight controllers).
    • db_path : string, optional, the path to the database directory. If not provided, a temporary database is created. When provided, Elodin records project-local Python source files to {db_path}/simulation_source/ for analysis and provenance.
    • interactive : bool, optional, controls simulation behavior after reaching max_ticks, defaults to True. When True, the simulation pauses but remains running for continued interaction in the Elodin editor. When False, the simulation terminates completely after reaching max_ticks.
    • start_timestamp : int, optional, the starting timestamp for the simulation in microseconds. If None (default), uses the current system time (epoch-based). Set to 0 for zero-based timing where the simulation starts at t=0.
    • log_level : str, optional, log level for the embedded Elodin-DB instance (error, warn, info, debug, trace). Defaults to info unless RUST_LOG is set.
    • backend : str, optional, execution backend. Defaults to "cranelift". Supported values are "cranelift" (CPU), "jax-cpu", and "jax-gpu".
    • on_receipt : Callable[[dict], None], optional, called with the run's receipt when it stops.
    • workers : int, optional, threads the Cranelift backend runs independent calls on, the simulation thread included: entity chunks of @el.map systems and the per-entity calls of @el.map_seq. Defaults to 1. Results do not depend on the count once it is above 1; going from 1 to more can change the last bits of reductions. to_jax(workers=...) traces systems the same way.
    • pre_commit : a callable (tick, WorldStepContext), an elodin.NativeStepHook, or a list of them run in order, called after each tick and before its DB commit. See pre-commit hooks.
    • timing : elodin.Timing, optional, what the receipt measures. Defaults to Timing.summary().
    • synchronous_commits : bool, optional, has each commit in the DB, and last_updated past it, before the next cycle's pre_commit hooks run, so at most one commit is ever in flight. The writer thread still appends it, during the pacing and the next systems step, and the next cycle waits for it before its hooks; the receipt counts that wait in commit. The loop then also waits out DB write stalls, so keep the DB on storage that does not stall. Defaults to False.
    • determinism_trace : [elodin.DeterminismTrace], optional, records the run's deterministic witness.

    When neither pre_step nor post_step is given, no component sets wait_for_write, no history handle or timestamped writer was prepared, and synchronous_commits is False, a writer thread appends each commit to the DB, so DB stalls stay off the simulation thread. Clients then see a commit, and last_updated move past it, up to a few cycles later. The receipt's sync.commits says which way the run committed: write_behind or synchronous.

  • build(system, simulation_rate, generate_real_time, telemetry_rate, default_playback_speed, max_ticks, optimize, db_path, backend, start_timestamp, workers, timing) -> elodin.Exec

    Build and compile the simulation executor without starting the runtime loop. Exec.run(ticks) advances it and records each tick at its simulation time, so repeated calls continue one history.

    • system : elodin.System, the systems to compile.
    • simulation_rate : float, optional, simulation frequency in Hz (ticks per second), defaults to 120.0.
    • generate_real_time : bool, optional, when True, paces simulation to real-time wall clock speed. Defaults to False.
    • telemetry_rate : float | None, optional, telemetry/writeback frequency in Hz. Defaults to simulation_rate when unset.
    • default_playback_speed : float, optional, the default playback speed used by clients.
    • max_ticks : integer, optional, the maximum number of ticks configured on the built executor.
    • optimize : bool, optional, enables optimization passes during compilation.
    • db_path : string, optional, the path to the database directory.
    • backend : str, optional, execution backend. Defaults to "cranelift".
    • start_timestamp : int, optional, the timestamp of the initial state in microseconds; tick n is recorded at start_timestamp + n / simulation_rate. If None (default), uses the current system time. Set to 0 for zero-based timing.
    • workers, timing : as for run. Exec.last_receipt() returns the receipt of the latest Exec.run.
  • to_jax(system, simulation_rate=120.0, default_playback_speed=1.0, max_ticks=None, workers=None) -> elodin.jaxsim.JaxSim

    Build the world for JAX instead of running it: no runtime loop, database or recipes. The result steps the simulation as pure JAX functions, and exports it for a native C++ host.

    • system, simulation_rate, default_playback_speed, max_ticks : as for build.
    • workers : int | None, trace the systems as run(workers=...) runs them on the Cranelift backend: @el.map systems in chunks of two entities when above 1, and @el.map_seq once per entity. The step then reproduces that run bit for bit, and JaxSim.export_model compiles its independent calls to run on that many threads; pass 1 for a run without workers. None traces as the JAX backends do: whole columns for @el.map, and jax.lax.scan for @el.map_seq.
  • export_model(system, path, simulation_rate=120.0, default_playback_speed=1.0, max_ticks=None, workers=None, interfaces=None, cpu="native") -> elodin.jaxsim.JaxSim

    Build and export a passive synchronous model, then return its JaxSim. The native caller owns invocation order, logical- and wall-time policy, files, I/O, hooks, and processes.

    • interfaces : dict[str, elodin.BatchHandle] | None, optional named row views. Each field keeps its batch alias, component, entity order, row size, and read or write access. Interfaces describe data only; they do not prescribe callbacks or hook order.
    • cpu : "native" enables this CPU's features in step.o; "generic" uses the baseline of this machine's architecture. For a machine with another OS or architecture, compile the step there with package.py --cpu.
    • Other arguments are as for to_jax.
  • prepare_component(name, entities, access="read") -> elodin.ComponentHandle

    Resolve once the rows of component name for entities, in that order, for pre-commit hooks. access="write" lets hooks write them; building the world fails if a system also writes the component. Spawning afterwards invalidates the handle.

  • prepare_batch(fields) -> elodin.BatchHandle

    Group handles over the same number of rows, keyed by field name, so a hook views them together.

  • prepare_component_history(name) -> elodin.HistoryHandle

    Resolve once the entity.component pair name (e.g. "drone.world_pos"), for hooks to read its committed DB history with WorldStepContext.read_at. Transient components have no history and are rejected.

  • prepare_message_history(name) -> elodin.HistoryHandle

    The same for the message log name (e.g. "drone.scene_cam"), which may not exist yet when it is prepared.

  • prepare_timestamped_writer(fields) -> elodin.TimestampedWriter

    Resolve once the components that WorldStepContext.defer_write appends to: fields maps each value's key to an entity.component pair, which must be marked external_control so the simulation never writes it.

  • prepare_witness(batches, channels=None, external=None, stages=None) -> elodin.Witness

    Choose what a run's deterministic witness records: batches maps names to elodin.BatchHandles. channels and external map channel names to (batch, row_bytes), one row per row of one of those batches, which hooks fill with WorldStepContext.witness_bytes or as native-hook columns. External channels hold what came from outside the simulation: a replay feeds them back to the hooks, and no comparison looks at them. stages keeps only the stages it names.

  • replay_pre_commit(trace, pre_commit, live=False) -> dict

    Run pre_commit, the same list of hooks as the run that recorded the witness file trace, on the rows it kept exactly, without the systems, recipes or DB, and compare what each hook writes with the recording. Uses the witness last prepared on this world. Before each hook, the world holds the rows that hook saw in the run, and its external channels hold the recorded bytes unless live. Hooks whose stage the witness leaves out are not run. Stops at the first mismatch. Returns ticks replayed, skipped_ticks that kept only digests, records and bytes compared, and first_mismatch or None.

Backend Selection

Elodin supports CPU execution for both cranelift and JAX backends, with optional GPU support for JAX. You can choose the backend in code with the backend argument or override it at runtime with the ELODIN_BACKEND environment variable.

If ELODIN_BACKEND is set, it takes precedence over the backend= argument passed to run() and build().

BackendEngineDevice/TargetNotes
craneliftcranelift-mlircpuDefault backend
jax-cpuJAXcpuJAX CPU target
jax-gpuJAXgpuJAX GPU target
# Force GPU backend regardless of backend= passed in Python
ELODIN_BACKEND=jax-gpu python main.py

class elodin.jaxsim.JaxSim

A world built for JAX by World.to_jax. Its state is a list of arrays, one per component, each holding every entity's value; a component held by one entity has no entity axis.

sim = world.to_jax(system, simulation_rate=120.0)
state = sim.set(sim.state, "world_vel", "ball", [0, 0, 0, 1, 0, 0])
for _ in range(100):
    state = sim.step_fn(state)
print(sim.get(state, "world_pos", "ball"))
  • state : the current state, which step, get_state and set_state use.

  • workers : the workers the systems were traced for; 1 without it.

  • step_fn(state) -> list : the state after one tick. Pure, so it composes with jax.jit, jax.vmap and jax.lax.scan. It advances tick, and carries over the components no system writes.

  • get(state, component_name, entity_name=None) -> array : a component's value for one entity, or for every entity.

  • set(state, component_name, entity_name, value) -> list : a copy of state with the value written; entity_name=None writes every entity's value at once.

  • step(max_steps) -> None, get_state(component_name=None, entity_name=None), set_state(component_name, entity_name, value) -> None : the same on state, in place.

  • export_model(path, interfaces=None, cpu="native") -> None

    Write one passive state transition for a caller-owned C or C++ runtime. See Custom C++ Runtimes.

    FileContents
    step.stablehlo.mlirstep_fn as StableHLO, from every component's value to its next value
    step.oThe same tick compiled ahead of time by the Cranelift backend for cpu, defining elodin_model_kernel_step; with workers above 1, its independent calls run on the loader's worker threads
    state.binstate as raw little-endian bytes, in state order
    schema.jsonThe versioned layout of the model: its time step and tick, typed components with their entity rows, and optional named interfaces
    model-manifest.jsonThe target step.o was compiled for, and the SHA-256 and size of each file

    Model schema ABI 1 records the nominal time step, the tick and time-step components, the export workers, and each component's dtype, shape, row bytes, metadata and written_by_step, which is true for every system output and for the tick. The nominal time step is the simulation_time_step the state holds, which Elodin keeps in whole nanoseconds: 0.008333333 s at 120 Hz. libs/elodin-model/package.py produces static and shared CMake targets, C and C++ headers, provenance, and a runtime SBOM, and with --cpu compiles step.o again on the machine that packages.

Monte Carlo Campaign API

The el.monte_carlo submodule lets a simulation declare tunable parameters and read the current campaign row. Outside elodin monte-carlo, declared defaults are returned so the same simulation still runs normally.

PARAMS = el.monte_carlo.params_spec(
    mass=el.monte_carlo.Param(float, default=1.5, min=0.5, max=5.0),
    target_x=el.monte_carlo.Param(float, default=30.0),
)

p = el.monte_carlo.params(PARAMS)
mass = p["mass"]
db_path = p.db_path
  • Param(type_, default=None, min=None, max=None) declares a JSON-serializable tunable value.
  • params_spec(**params) records a parameter schema for elodin monte-carlo template and python sim.py params.
  • params(spec=None) reads ELODIN_MONTE_CARLO_CONTEXT and returns defaults plus row overrides. It exposes run_id, seed, db_path, db_addr, cache_dir, run_dir, slots(), and as_overrides_dict().
  • result(**values) writes scalar run outputs to result.json in the current run directory; the campaign runner merges these into results.csv.

s10 Recipe API

world.recipe(recipe) registers an external process that Elodin launches next to the simulation, gates on readiness, and tears down when the simulation exits. See Process Orchestration (s10) for ordering, lifecycle, and SITL/HITL patterns.

world.recipe(el.s10.PyRecipe.process(
    name="controller",
    cmd="./controller",
    ready=el.s10.Ready.tcp("127.0.0.1:9000"),
))
  • el.s10.PyRecipe.process(name, cmd, args=None, cwd=None, env=None, restart_policy=None, depends_on=None, ready=None, ready_timeout=None, silence=False) runs a command.
  • el.s10.PyRecipe.cargo(name, path, package=None, bin=None, args=None, cwd=None, env=None, restart_policy=None, depends_on=None, ready=None, ready_timeout=None, silence=False) builds a Rust crate, then runs its binary.
  • el.s10.Ready.tcp(addr), .unix(path), .file(path), .delay(ms), and .log(pattern) are readiness probes. log only works in elodin monte-carlo campaigns. ready_timeout accepts strings such as "500ms" or "30s" (default "30s").
  • el.s10.RestartPolicy.Never (default) or .Instant.
  • args, cwd, and probe addresses and paths expand ${NAME} / ${NAME:-default} from the environment when the process is spawned.

class elodin.EntityId

Integer reference identifier for entities in Elodin.

class elodin.StepContext

Context object passed to pre_step and post_step callbacks, providing direct database read/write access. This enables Software-In-The-Loop (SITL) and Hardware-In-The-Loop (HITL) workflows where external systems need to exchange data with the simulation at each tick.

StepContext provides direct database access within the same process, avoiding the overhead of a separate TCP connection. This is essential for high-frequency lockstep synchronization with external flight controllers or sensor systems. SITL & HITL compares it with pre_commit hooks.

Properties

  • tick -> int

    The current simulation tick count (0-indexed).

  • timestamp -> int

    The current simulation timestamp in microseconds since epoch. This value is calculated as start_timestamp + (tick * (1.0 / simulation_rate)).

Methods

  • read_component(pair_name, timestamp=None) -> numpy.ndarray

    Read component data from the database.

    • pair_name : string, the full component name in "entity.component" format (e.g., "drone.accel", "drone.world_pos")
    • timestamp : int, optional, microseconds since epoch. When None (the default), returns the most recent sample. When provided, returns the sample with the greatest timestamp <= the requested one (floor / sample-and-hold semantics). Timestamps past the most recent write clamp to the latest sample.

    Returns a NumPy array containing the component data. The array dtype matches the component schema and is always 1D; reshape if needed.

    Raises RuntimeError if the component doesn't exist, has no data, or the requested timestamp is before the very first sample.

    Historical reads use the same memory-mapped time-series that the latest-only path does, so the additional cost is one binary search over a contiguous timestamp index (a few hundred nanoseconds for typical histories). Use this to look up sensor values from earlier ticks (e.g. for finite-difference estimators) without leaving the simulation process.

  • write_component(pair_name, data, timestamp=None) -> None

    Write component data to the database.

    • pair_name : string, the full component name in "entity.component" format (e.g., "drone.motor_command")
    • data : numpy.ndarray, the component data to write
    • timestamp : int, optional, the timestamp (microseconds since epoch) to write at. If None, uses the current simulation timestamp.

    Raises RuntimeError if the component doesn't exist, or ValueError if the data size doesn't match the component schema.

    Timestamps must be monotonically increasing per component. Writing with a timestamp less than the last write will raise a TimeTravel error.

  • component_batch_operation(reads=[], writes=None, write_timestamps=None, read_timestamps=None) -> dict[str, numpy.ndarray]

    Perform multiple component reads and writes in a single database operation. This is more efficient than calling read_component/write_component multiple times, as it only acquires the database lock once for all operations.

    • reads : list[str], list of component names to read (e.g., ["drone.accel", "drone.gyro"])
    • writes : dict[str, numpy.ndarray], optional, dict mapping component names to numpy arrays to write
    • write_timestamps : dict[str, int], optional, dict mapping component names to timestamps (microseconds since epoch). Components not in this dict use the current simulation timestamp.
    • read_timestamps : dict[str, int], optional, dict mapping component names to timestamps (microseconds since epoch). Components present in this dict are read with floor / sample-and-hold semantics; components not in this dict return the most recent sample. Past-the-end timestamps clamp to the latest sample.

    Returns a dict mapping read component names to their numpy array values.

    Use batch operations when reading or writing multiple components in a single callback for better performance at high tick rates. read_timestamps lets you mix latest-only and historical reads in the same single-lock operation.

  • read_msg(msg_name, timestamp=None) -> numpy.ndarray | None

    Read a message payload from the database as a numpy uint8 array. Used to fetch sensor camera frames produced by the headless render server, log lines from fsw/gstreamer, and any other timestamped message stream.

    • msg_name : string, the message name (e.g., "drone.scene_cam").
    • timestamp : int, optional, microseconds since epoch. When None (the default) returns the most recent message. When provided, returns the message with the greatest timestamp <= the requested one (floor / sample-and-hold semantics). Timestamps past the most recent message clamp to the latest.

    Returns the numpy uint8 array of the message payload, or None if no message exists at or before the requested timestamp (or no message exists at all).

    Use timestamp=ctx.timestamp - latency_us to read a sensor camera frame as it would have appeared latency_us µs ago. This is how you model camera latency in flight-software-in-the-loop simulations.

  • truncate() -> None

    Truncate all component data and message logs in the database, resetting the tick counter to 0. This clears all stored time-series data while preserving component schemas and metadata.

    Use this to control the freshness of the database and ensure reliable data from a known tick. Common use case: clearing warmup data before starting the actual simulation run.

    After truncate(), any subsequent write_component() calls in the same callback will write at the start timestamp (tick 0), preventing TimeTravel errors on the next tick.

  • stop_recipes() -> None

    Gracefully terminate all s10-managed recipes (external processes).

    This signals all processes managed by s10 (registered via world.recipe()) to shut down gracefully. The processes receive SIGTERM and have approximately 2 seconds to clean up before being force-killed.

    Use this to ensure clean shutdown of external processes (like Betaflight SITL) before the simulation exits, preventing memory corruption or resource leaks.

    This only has an effect when the simulation is run directly with python main.py run. Under elodin editor, elodin run, and elodin monte-carlo, the simulation runs with --no-s10 and this is a no-op; the simulation exiting already stops every recipe. It is also a no-op if no recipes were registered. See Process Orchestration (s10).

    Call stop_recipes() before the simulation exits to allow external processes time to clean up. You may want to add a brief delay (e.g., time.sleep(0.5)) after calling this method to ensure the processes have finished shutting down.

Example: SITL Integration

This example demonstrates a typical Software-In-The-Loop workflow where a flight controller receives sensor data and returns motor commands:

import elodin as el
import numpy as np
import time

# External flight controller interface (e.g., Betaflight SITL)
flight_controller = FlightControllerBridge()
MAX_TICKS = 10000

def sitl_post_step(tick: int, ctx: el.StepContext):
    """Post-step callback for lockstep SITL synchronization."""

    # Read sensor data from the physics simulation using batch operation
    sensor_data = ctx.component_batch_operation(
        reads=["drone.accel", "drone.gyro", "drone.world_pos"]
    )

    accel = sensor_data["drone.accel"]
    gyro = sensor_data["drone.gyro"]
    position = sensor_data["drone.world_pos"]

    # Send sensor data to flight controller, receive motor commands
    motors = flight_controller.step(
        accel=accel,
        gyro=gyro,
        timestamp=ctx.timestamp
    )

    # Write motor commands back to the simulation
    ctx.write_component("drone.motor_command", motors)

    # Print status every 1000 ticks
    if tick % 1000 == 0:
        print(f"Tick {tick}: motors={motors}, pos={position}")

    # Graceful shutdown before simulation ends
    if tick >= MAX_TICKS - 1:
        ctx.stop_recipes()  # Signal s10 processes to terminate
        time.sleep(0.5)     # Allow time for graceful shutdown

# Run simulation with SITL callback
world.run(
    system,
    simulation_rate=1000.0,  # 1kHz for flight controller
    max_ticks=MAX_TICKS,
    post_step=sitl_post_step,
    db_path="sitl_data",
    interactive=False,  # Headless mode
)

For writing data at custom timestamps (e.g., logging historical sensor readings):

def log_with_timestamps(tick: int, ctx: el.StepContext):
    # Write current data at simulation timestamp (default)
    ctx.write_component("drone.motor_command", motors)

    # Write historical data at a specific timestamp
    historical_ts = ctx.timestamp - 100_000  # 100ms ago (microseconds)
    ctx.write_component("drone.sensor_log", sensor_data, timestamp=historical_ts)

    # Batch write with per-component timestamps
    ctx.component_batch_operation(
        writes={
            "drone.data_a": data_a,
            "drone.data_b": data_b,
        },
        write_timestamps={
            "drone.data_b": custom_timestamp,  # Custom timestamp for data_b
            # data_a uses current simulation timestamp
        }
    )

Pre-commit hooks

A pre_commit hook runs after each tick and before its DB commit, on world columns resolved once with World.prepare_component and World.prepare_batch. Unlike post_step, it does not go through the DB: what it reads is the tick's result, and what it writes reaches the world, the same commit, and the systems on the next tick. SITL & HITL explains when to use each.

exchange = world.prepare_batch({
    "position": world.prepare_component("position", agents),
    "target": world.prepare_component("object_position", targets),
    "command": world.prepare_component("command", agents, access="write"),
})

def exchange_step(tick: int, ctx: el.WorldStepContext) -> None:
    with ctx.batch(exchange) as view:
        view.command[...] = controller(view.position, view.target)

world.run(system, pre_commit=exchange_step, workers=8)

A hook can also read committed DB history, such as camera frames another process recorded, and queue timestamped writes that land after the commit:

frames = world.prepare_message_history("drone.scene_cam")
truth = world.prepare_component_history("drone.world_pos")
evidence = world.prepare_timestamped_writer({"frame": "drone.capture_frame"})

def history_step(tick: int, ctx: el.WorldStepContext) -> None:
    found = ctx.read_at(frames, capture_time, "exact")       # (timestamp, bytes) or None
    pose = ctx.read_at(truth, capture_time, "at_or_before")  # (timestamp, value) or None
    ctx.defer_write(evidence, ctx.timestamp + 1, {"frame": frame_id})

world.run(system, pre_commit=[exchange_step, history_step])

A list of hooks is one ordered boundary:

  1. Hooks run in list order, Python and native alike.
  2. A hook sees the world writes of the hooks before it.
  3. History reads see committed DB samples only, not the world of the current tick, whose commit comes after the hooks.
  4. Deferred writes are appended after the commit, in hook and call order, equal timestamps included. They do not move last_updated.
  5. A hook that raises, or a native hook that returns nonzero, stops the later hooks, the cycle's commit and the run. Its queued writes are dropped.

A deferred write that fails, for example with a timestamp older than its component's last sample, stops the run after the commit. The receipt's failed_hook names the hook (index and name) and says whether the cycle's commit had landed (committed). Preparing a history handle or a timestamped writer makes commits synchronous, so the hooks read every earlier commit and deferred writes follow theirs; with the writer thread, a cycle's deferred writes land just before the next cycle's hooks.

class elodin.WorldStepContext

Passed to pre_commit callbacks.

  • tick, timestamp : the tick just run and its time in microseconds.
  • view(handle) -> numpy.ndarray : the handle's rows, read-only for a read handle. Writes to a write handle's view reach the world when the callback returns. Views are copies and end with the callback.
  • batch(batch) -> BatchView : views every field of a batch, as attributes or items.
  • record(handle) -> None : records the handle's component, which must use Recording.manual(), at this commit.
  • read_at(history, timestamp, selection) -> (int, numpy.ndarray) | None : the committed sample of an elodin.HistoryHandle at timestamp. selection="exact" takes only a sample at that timestamp and never falls back to an older one; "at_or_before" takes the newest sample at or before it. Returns the sample's own timestamp and a copy of its value (a message as uint8 bytes), or None when nothing matches.
  • defer_write(writer, timestamp, values) -> None : queues values, one per key of an elodin.TimestampedWriter, to append at timestamp after this cycle's commit.
  • witness_bytes(name, data) -> None : fills witness channel name with the bytes of data, an array of any dtype holding every row of the channel's batch. Raises ValueError on any other size, and KeyError for an unknown channel. Does nothing when the run records no witness.
  • witness_replay(name) -> numpy.ndarray | None : in a replay, the recorded bytes of external channel name as uint8 rows; otherwise None. A hook that does I/O does it only when this returns None.
  • stop_recipes() -> None : stops the s10 recipes, as StepContext.stop_recipes.

All but tick and timestamp raise once the callback returns.

class elodin.NativeStepHook

A pre_commit hook in a shared library. It runs without the GIL, and can split the batch's rows across the workers threads.

  • NativeStepHook.load(path, input, symbol, workers=1) -> elodin.NativeStepHook

    Load symbol, and {symbol}_init and {symbol}_destroy if present, from the library at path. Each tick calls symbol once per worker, concurrently, each on a contiguous share of input's rows. input is an elodin.BatchHandle.

The library exports C functions over these types, ABI version 1, which elodin_step_hook.h declares:

#include <stdint.h>

typedef struct {
    const char *name;     /* the batch field */
    uint8_t *data;        /* every row of the batch, back to back */
    uint64_t row_bytes;
    uint32_t writable;    /* nonzero for a write field */
} ElodinColumn;

typedef struct {
    uint32_t abi_version;
    uint64_t tick;
    int64_t timestamp;    /* microseconds */
    uint64_t rows;
    uint64_t row_start;   /* this call owns rows [row_start, row_end) */
    uint64_t row_end;
    const ElodinColumn *columns;
    uint64_t column_count;
    void *state;          /* what init stored, or NULL */
    char *error;          /* a failing call writes a NUL-terminated message here */
    uint64_t error_capacity;
} ElodinStep;

int32_t my_step(const ElodinStep *step);                    /* 0 on success */
int32_t my_step_init(const ElodinStep *step, void **state); /* optional; once, over every row */
void my_step_destroy(void *state);                          /* optional; after the run */

A call may write only writable columns, and only its own rows. A nonzero return stops the run with the call's message in the receipt. The receipt's callbacks.hooks reports each hook's queue time, slowest-partition time and worker occupancy.

When the run records a witness, each witness channel on the hook's input batch is one more column after the batch fields, named after the channel, with the channel's row_bytes. It is zeroed before each tick, and writable, except an external channel in a replay, which holds the recorded bytes and has writable == 0. A hook can look its channels up by name at init and treat a read-only external channel as the sign that it is replayed.

Deterministic witnesses

A witness records the exact bytes a run produces at fixed points of each tick, and digests them into a tree, so two runs that should be identical can be compared byte for byte and the first difference named. It is meant for lockstep runs with external controllers, where a run must repeat exactly.

witness = world.prepare_witness(
    {"exchange": exchange, "objects": objects_state},
    channels={"controller.ingress": (exchange, 1024),    # what the hook sent
              "controller.response": (exchange, 80)},    # what it took from each reply
    external={"controller.reply": (exchange, 104)},      # the replies themselves
)

def exchange_step(tick: int, ctx: el.WorldStepContext) -> None:
    ctx.witness_bytes("controller.ingress", frames)
    replies = ctx.witness_replay("controller.reply")     # recorded bytes in a replay, else None
    if replies is None:
        replies = send_and_receive(frames)
        ctx.witness_bytes("controller.reply", replies)
    ...

world.run(system, pre_commit=[exchange_step],
          determinism_trace=el.DeterminismTrace("run.witness", witness, raw=True))

Each tick, the witness takes these stages, in order:

StageRecords
after_systemsevery row of every field of every batch
after_hook:Nthe channels hook N filled, every write field, and the deferred writes hook N queued; then the external channels
after_commitfor every row of every field, whether the commit recorded it

The commit decides what it records on the simulation thread, so the DB writer's timing cannot change a witness. A channel no hook filled is recorded as absent.

Each record is hashed with BLAKE3-256 over its little-endian bytes, rows in batch order whatever the hook's partitioning. A stage's digest hashes its records' digests, a tick's digest hashes the tick, its simulation time and its stages' digests, and the root hashes the schema and every tick. External channels are never hashed. Labels are stored but not hashed either: the build, the hook names, a native hook's partitions and the start timestamp. A Python hook and a native hook that fill the same channels give the same root.

class elodin.DeterminismTrace

  • DeterminismTrace(path, witness, raw=False, reference=None, stop_after_first_mismatch=False)

    • path : where to write the witness file.
    • witness : an elodin.Witness from World.prepare_witness.
    • raw : True keeps the exact bytes of every tick, and a (start, stop) pair those of ticks start to stop - 1. Otherwise the file keeps only digests, about 1 KB per tick for a few dozen records. Raw bytes do not change the root.
    • reference : a witness file to compare with as the run goes. Its schema must match. The first tick that differs is the receipt's witness.first_mismatch, and the 16 ticks on either side of it keep their exact bytes. A run stays successful when it differs from its reference.
    • stop_after_first_mismatch : ends the run a few ticks after the first mismatch.

    A witness thread hashes, compares and writes each tick from a block the simulation thread fills; if it falls 1,024 ticks behind, the run fails. Nothing is ever dropped.

module elodin.determinism

  • compare(left, right, stop_at_first=False) -> dict : compares two witness files tick by tick, and below the first differing digest, the bytes when both files kept them. Returns identical, first_mismatch or None, the numbers of ticks compared and mismatched_ticks, and a summary of each file. Ticks missing from one file are a mismatch; files with different schemas, such as another entity order or stage list, raise ValueError naming the difference.
  • replay_hook(trace, library, symbol, live=False) -> dict : replays the native hook symbol of the shared library library on the rows trace kept, like World.replay_pre_commit but without the simulation's source: the batch is rebuilt from the file.
  • describe(mismatch) -> str : the lines elodin determinism prints.

A mismatch names the tick, the stage, the hook, the record by its kind (field, channel, deferred or recorded) and name, and when both sides have the bytes, the entity, row and byte within the row, with each side's byte as left and right. A channel row takes the entity of its batch's first field. In a run with a reference and in a replay, left is the reference or the recording.

Witness files

A file is the magic ELWITNES, the format version (1) and a JSON header with the schema, its digest and the labels; then one frame per tick, with the tick, its timestamp, a digest per hashed record and, when kept, every record's bytes; then a JSON trailer with the tick count, the root and the run's failure, if any. A version other than 1 is refused. Comparison never looks at the labels.

Any program can write one; many-agents-cpp does from C++. All integers are little-endian:

file    := "ELWITNES" version:u32 header_len:u32 header_json frame* trailer
frame   := 0x01 tick:u64 timestamp:i64 digest:[u8; 32]* raw:u8 (len:u32 bytes)*
trailer := 0x02 json_len:u32 trailer_json
  • Header. {"format":"elodin.witness","version":1,"hash":"blake3-256 over little-endian bytes","schema_digest":…,"schema":…,"labels":…}. The schema has entities ([id, name] pairs, by id), batches (each name and fields: name, component, dtype, shape, row_bytes, access, entities), channels (name, batch, row_bytes, external), stages, and records (stage, kind, name, batch or null, index, row_bytes), keys in that order. schema_digest is the hex BLAKE3 of the schema as compact JSON with keys in that order; a reader recomputes it and refuses a file whose digest differs. The labels are build, start_timestamp and hooks (name, batch or null, partitions); elodin determinism replay-hook finds a native hook by its label's name, batch and non-empty partitions.
  • Records come in the order of records, which lists stage by stage: for after_systems, every field of every batch; for after_hook:N, the channels that are not external, the write fields, one deferred record, then the external channels; for after_commit, a recorded record per field with one byte per row, 1 when the commit recorded that row.
  • Frames hold one digest per record that is not external, in record order. A record's digest is the BLAKE3 of its bytes, rows in batch order, except a channel no hook filled, which is 32 zero bytes. With raw set to 1, every record follows as its length and bytes, external ones included and an unfilled channel as length 0.
  • Digests. A stage's digest is the BLAKE3 of its records' digests back to back. A tick's is the BLAKE3 of the tick (u64), its simulation time (i64, the timestamp minus start_timestamp) and its stages' digests. The root, in the trailer {"ticks":…,"root":…,"failure":null}, is the BLAKE3 of the schema digest followed by every tick's digest.

Run receipts

Every run builds a versioned receipt (elodin.run_receipt.v1), passed to on_receipt, returned by Exec.last_receipt(), and written to $ELODIN_SIM_SUMMARY_JSON when set. It covers the cycles after warmup: count, sum, min, exact p50/p95/p99, and max of every phase (copy_db_to_world, world_run, pre_commit, commit, deferred_writes, post_step, their callback sum, pacing, and total_cycle); pacing lateness and resets; DB sync counters, including whether commits were synchronous or write_behind, rows scanned, drained and committed, and the writer thread's lag and queue depth; backend bytes and compile times; hook timings, history queries, misses and bytes, and deferred-write batches, rows, bytes and failures under callbacks; under witness, the witness file's path, root, ticks, raw_ticks and bytes_written, the simulation thread's capture time per cycle, the witness thread's writer_ns, its queue_high_water, the first_mismatch with the reference and the witness's failure; the failure and failed_hook of a run a hook or the witness stopped; and the sections it did not collect under unavailable.

class elodin.Timing

What a receipt measures, from least to most perturbing.

  • Timing.summary() : phase times of every cycle; always on.
  • Timing.systems() : also the inclusive and exclusive time of each compiled function on the Cranelift backend, so of each system under its name. A system small enough to inline counts toward its caller. Probes cost systems.probe_pair_ns per call and keep calls on one thread.
  • Timing.operations() : also sampled time per kind of operation.

Neither level writes debug artifacts; ELODIN_CRANELIFT_DEBUG_DIR stays separate.

class elodin.Panel

A configuration object for creating a panel view in the Elodin Client UI.

  • Panel.viewport(track_entity, track_rotation, fov, active, pos, looking_at, show_grid, hdr, name) -> elodin.Panel

    Create a viewport panel.

    • track_entity : elodin.EntityId, optional, the entity to track.
    • track_rotation : boolean, whether to track the rotation of the entity, defaults to True.
    • fov : float, the field of view of the camera, defaults to 45.0.
    • active : boolean, whether the panel is active, defaults to False.
    • pos : list, optional, the position of the camera.
    • looking_at : list, optional, the point the camera is looking at.
    • show_grid : boolean, whether to show the grid, defaults to False.
    • hdr : boolean, whether to use HDR rendering, defaults to False.
    • name : string, optional, the name of the panel.
  • Panel.graph(*entities, name) -> elodin.Panel

    Create a graph panel.

    • *entities : Sequence of elodin.GraphEntity objects to include in the graph.
    • name : string, optional, the name of the panel.
  • Panel.vsplit(*panels, active) -> elodin.Panel

    Create a vertical split panel.

    • *panels : Sequence of elodin.Panel objects to vertically split across.
    • active : boolean, whether the panel is active, defaults to False.
  • Panel.hsplit(*panels, active) -> elodin.Panel

    Create a horizontal split panel.

    • *panels : Sequence of elodin.Panel objects to horizontally split across.
    • active : boolean, whether the panel is active, defaults to False.

class elodin.GraphEntity

A configuration object for creating a graph entity in the Elodin Client UI.

  • __init__(entity_id, *components) -> elodin.GraphEntity

    Create a graph entity.

    • entity_id : elodin.EntityId, the entity to graph.
    • *components : Sequence of elodin.ShapeIndexer indexes of components to graph.

class elodin.Mesh

A built in class for creating basic 3D meshes.

  • Mesh.cuboid(x: float, y: float, z: float) -> elodin.Mesh

    Create a cuboid mesh with dimensions x, y, and z.

  • Mesh.sphere(radius: float) -> elodin.Mesh

    Create a sphere mesh with radius radius.

class elodin.Material

A built in class for creating basic 3D materials.

  • Material.color(r: float, g: float, b: float) -> elodin.Material

    Create a material with RGB color values.

class elodin.Shape

Shape describes a basic entity for rendering 3D assets in Elodin.

  • __init__(mesh, material) -> elodin.Shape

    Create a shape archetype initialized to the provided mesh and material.

    • mesh : handle reference returned from World.insert_asset() using the elodin.Mesh class.
    • material : handle reference returned from World.insert_asset() using the elodin.Material class.

class elodin.Scene

Scene describes a complex scene entity loaded from a glb file.

  • __init__(glb) -> elodin.Scene

    Create a scene from a loaded file.

    • glb : handle reference returned from World.insert_asset() using the elodin.Glb class.

Example

This example creates a simple simulation with a spinning cuboid body:

import elodin as el
import jax.numpy as jnp

@el.map
def spin(f: el.Force, inertia: el.Inertia) -> el.Force:
    return f + el.Force(torque=(inertia.mass() * jnp.array([0.0, 1.0, 0.0])))

w = el.World(frame=el.Frame.ENU)

mesh = w.insert_asset(el.Mesh.cuboid(0.1, 0.8, 0.3))
material = w.insert_asset(el.Material.color(25.3, 18.4, 1.0))

cuboid_id = w.spawn([el.Body(), el.Shape(mesh, material)], name="cuboid")

camera = el.Panel.viewport(pos=[0.0, -5.0, 0.0], hdr=True, name="camera")
graph = el.Panel.graph(
    el.GraphEntity(cuboid_id, *el.Component.index(el.WorldPos)[:4]), name="graph"
)

w.spawn(el.Panel.vsplit(camera, graph), name="main_view")

sys = el.six_dof(sys=spin)
sim = w.run(sys, simulation_rate=120.0, backend="cranelift")



6 Degrees of Freedom Model

Elodin has a built-in 6 Degrees of Freedom (6DoF) system implementation for simulating rigid bodies, such as flight vehicles. You can review the implementation here. Using the associated elodin.Body archetype and prebuilt components, we can create a 6DoF system that aligns closely with this familiar model from Simulink.

function elodin.six_dof

  • six_dof(time_step, sys, integrator) -> elodin.System

    Create a system that models the 6DoF dynamics of a rigid body in 3D space. The provided set of systems can be integrated as effectors using the provided integrator and simulated in a world with a given time_step.

    • time_step : float, The time step used when integrating a body's acceleration into its velocity and position. Defaults to the simulation step (1.0 / simulation_rate) provided in World.run(...) if unset
    • sys : one or more elodin.System instances used as effectors
    • integrator : elodin.Integrator, default is Integrator.Rk4

    Most integrators evaluate the effectors several times per step, at different times within it. The global elodin.StageTime component holds the seconds past the start of the step for the current evaluation (zero outside six_dof), so effectors that depend on time can follow it. The tick is incremented before the systems run, so the effectors' time is (tick[0] - 1) * dt[0] + stage_time[0] for an el.Query[el.SimulationTick], an el.Query[el.SimulationTimeStep], and an el.Query[el.StageTime]. StageTime is measured in the simulation step even when six_dof integrates with its own time_step, so this time advances with the simulation either way.

class elodin.Integrator

  • elodin.Integrator.Rk4 -> elodin.Integrator

    Runge-Kutta 4th Order (RK4) Integrator: Elodin provides a built-in implementation for a 4th order Runge-Kutta integrator. The RK4 integrator is a numerical method used to solve ordinary differential equations. It evaluates the effectors 4 times per step. You can review the implementation here.

  • elodin.Integrator.Rk2 -> elodin.Integrator

    Heun's method, a second-order Runge-Kutta method that evaluates the effectors 2 times per step. It costs half as much as Rk4, and suits time steps short enough that second-order accuracy is enough, or dynamics with discontinuities such as contacts, where higher orders gain little.

  • elodin.Integrator.Rk3 -> elodin.Integrator

    Kutta's third-order Runge-Kutta method, which evaluates the effectors 3 times per step.

  • elodin.Integrator.Verlet -> elodin.Integrator

    Velocity Verlet, a second-order method that evaluates the effectors 2 times per step. When forces depend only on position, as in gravitational N-body problems, it is symplectic: energy errors stay bounded over long runs instead of drifting, as they do with the Runge-Kutta integrators, and orbits keep their size. Forces that depend on velocity, such as drag or the gyroscopic torque of a spinning body, leave it second order but not symplectic. You can review the implementation here.

  • elodin.Integrator.Rk78 -> elodin.Integrator

    The eighth-order solution of Fehlberg's 7(8) Runge-Kutta pair, which evaluates the effectors 13 times per step. Its error shrinks 256 times per halving of the time step, so it suits long, smooth propagations, such as orbits, where it can take much larger steps than Rk4 for the same accuracy.

  • elodin.Integrator.Dp54 -> elodin.Integrator

    The fifth-order solution of the Dormand-Prince 5(4) pair (the pair behind MATLAB's ode45), which evaluates the effectors 7 times per step. Elodin keeps the time step fixed.

    Dp54 and Rk78 estimate each step's error from their embedded lower-order solution. A body that has the elodin.StepError component, for example from el.C(el.StepError, jnp.zeros(4)), receives the estimate after every step: attitude (rad), position, angular velocity, and velocity. It is the difference between the pair's two solutions, which approximates the lower-order solution's error and usually exceeds the error of the solution Elodin keeps, but it is an estimate, not a guarantee. Graphed over a run, it shows whether the time step is small enough and where the dynamics are hardest to integrate.

  • elodin.Integrator.SemiImplicit -> elodin.Integrator

    Semi-Implicit Integrator: Elodin provides a built-in implementation for a semi-implicit Euler integrator. The semi-implicit integrator is a numerical method used to solve ordinary differential equations. You can review the implementation here.

    The semi-implicit integrator updates angular velocity with an explicit Euler step, so the gyroscopic term $\omega_b \times I\omega_b$ is evaluated at the start of each step. For bodies with unequal principal moments that spin quickly relative to the time step, angular momentum and rotational kinetic energy drift (typically growing) even with no applied torque. Use Integrator.Rk4 or a smaller time step for spinning or tumbling bodies.

class elodin.Body

Body is an archetype that represents the state of a rigid body with six degrees of freedom. It provides all of the spatial information necessary for the elodin.six_dof system

Example

A simple example of a 6DoF system that models gravity acting on a rigid body in 3D space.

import elodin as el
import jax.numpy as jnp

SIM_TIME_STEP = 1.0 / 120.0

@el.map
def gravity(f: el.Force, inertia: el.Inertia) -> el.Force:
    return f + el.Force(linear=(inertia.mass() * jnp.array([0.0, -9.81, 0.0])))

w = el.World(frame=el.Frame.ENU)
w.spawn(el.Body(), name="example")
sys = el.six_dof(sys=gravity, integrator=el.Integrator.Rk4)
sim = w.run(sys, SIM_TIME_STEP)

You should never need to use the six_dof time_step parameter unless you need to simulate a sensor at a specific frequency different from the world simulation. This is an advanced feature and should be used with caution, and likely a symptom of needing to move your testing into your flight software & communicate with the simulation over Impel.

# lower frequency time step
SIX_DOF_TIME_STEP = 1.0 / 60.0
sys = el.six_dof(time_step=SIX_DOF_TIME_STEP, sys=gravity)
sim = w.run(sys, SIM_TIME_STEP)



Terrain

See Terrain for elodin.Terrain, height-grid preparation and JAX height queries.

Components

Components are containers of data that is associated with an entity. See ECS Data Model for more context on entities and components.

To define a new component, add elodin.Component as metadata to a base class using typing.Annotated. The base class can be jax.Array or some other container of array data. This is an example of a component that annotates jax.Array:

import elodin as el

Wind = typing.Annotated[
    jax.Array,
    el.Component(
        "wind",
        el.ComponentType(el.PrimitiveType.F64, (3,)),
        metadata={"element_names": "x,y,z"},
    ),
]

class elodin.Component

A container of component metadata.

  • __init__(name, type = None, asset = False, metadata = {}, recording = None) -> elodin.Component

    Create a new component with:

    • Unique name (e.g. "world_pos, "inertia").
    • Component type information (via elodin.ComponentType). This is optional if the base class already provides component type information as part of __metadata__, which is the case for elodin.Quaternion, elodin.Edge, and all spatial vector algebra classes.
    • Flag indicating whether the component is an asset (e.g. a mesh, texture, etc.).
    • Other metadata that is optional (e.g. description, units, labels, etc.).
    • When its values are recorded (elodin.Recording), described below.
    import elodin as el
    
    el.Component(
        "wind",
        el.ComponentType(el.PrimitiveType.F64, (3,)),
        metadata={"element_names": "x,y,z"},
    ),

    The above example defines a "wind" component that is a 3D vector of float64 values. The "element_names" entry is an example of optional metadata. It specifies the labels for each element of the vector that are displayed in the component inspector.

    Reserved metadata keys

    The metadata dict accepts arbitrary string keys, but a few keys have special meaning across Elodin tools:

    KeyValueEffect
    element_namescomma-separated string (e.g. "x,y,z", "q0,q1,q2,q3")Labels for each element of a vector or matrix component. Used by the component inspector and as column suffixes when exporting with elodin-db export --flatten.
    private"true"Component is omitted from elodin-db export by default (pass --include-private to include it). Useful for marking internal scratch state (e.g. large covariance matrices) that downstream consumers shouldn't see.
    transient"true"Simulation component remains available to systems in memory but is never registered with or recorded to Elodin DB. It is absent from DB schemas, the editor, replication, and exports.
    external_control"true"Component is writable from external clients (e.g. Betaflight or a HITL bridge) over the Impeller protocol, and from pre_commit hooks, including their deferred writes. The simulation will not overwrite values written externally.
    record_every_tick"true"Opt out of sparse recording and write a sample at every telemetry commit even when its bytes are unchanged.

    Component recording is sparse by default: the simulation writes a sample only when its bytes differ from the latest recorded value. This preserves state semantics while avoiding duplicate rows. Set record_every_tick="true" only for consumers that require dense samples. Editor line plots and Exec.history() carry sparse values forward. Point and bar plots show recorded samples only; raw database exports remain change streams with per-component row counts.

    transient is a simulation-runtime storage contract, not an export filter. A transient component cannot also set external_control, wait_for_write, or record_every_tick, and DB-backed APIs such as StepContext.read_component, StepContext.write_component, and Exec.history cannot access it. Direct database writers are unaffected by this key.

    Recording

    recording= sets when a commit records the component, counting telemetry commits:

    elodin.RecordingRecords
    on_change()when its bytes differ from the last recorded value; the default
    every_commit()at every commit; same as record_every_tick="true"
    every(n)at every nth commit, changed or not
    manual()at the commits a pre_commit hook asks for with ctx.record(handle)
    initial_only()once, when the run starts
    transient()never; same as transient="true"

    It is stored in the reserved metadata keys above, plus recording, so the DB, editor and followers keep working. A metadata value that contradicts it is an error.

    Command = ty.Annotated[
        jax.Array,
        el.Component(
            "command",
            el.ComponentType(el.PrimitiveType.F64, (3,)),
            metadata={"external_control": "true"},
            recording=el.Recording.every(10),
        ),
    ]

    Example combining a label hint with the export-skip flag:

    import elodin as el
    import jax
    import typing as ty
    
    EstCov = ty.Annotated[
        jax.Array,
        el.Component(
            "estimate_covariance",
            el.ComponentType(el.PrimitiveType.F64, (18, 18)),
            metadata={"private": "true"},
        ),
    ]
  • Component.name(component) -> string

    The unique name of the component.

  • Component.index(component) -> elodin.ShapeIndexer

    A shape indexer that can be used to access the component data.

class elodin.ComponentType

ComponentType describes the shape and data type of a component. The shape is a tuple of integers that specifies the size of each dimension (e.g. () for scalars, (3,) for 3D vectors). The data type is an elodin.PrimitiveType.

  • __init__(dtype, shape) -> elodin.ComponentType

    Create a component type from a data type and shape.

class elodin.Edge

An edge is a relationship between two entities. See elodin.GraphQuery for information on how to use edges in graph queries.

  • __init__(left, right) -> elodin.Edge

    Create an edge between two entities given their unique ids.



Archetypes

An archetype is a combination of components with a unique name. To define a new archetype, create a subclass of elodin.Archetype with the desired components as fields. Here is an example of an archetype for a kalman filter:

To automatically generate __init__(), you can use the @dataclass decorator.

import elodin as el
from dataclasses import dataclass

@dataclass
class KalmanFilter(el.Archetype):
    p: P
    att_est: AttEst
    ang_vel_est: AngVelEst
    bias_est: BiasEst

The archetype can then be used to attach components to entities:

world.insert(
    satellite,
    KalmanFilter(
        p=np.identity(6),
        att_est=el.Quaternion.identity(),
        ang_vel_est=np.zeros(3),
        bias_est=np.zeros(3),
    ),
)



Systems

Systems are the building blocks of simulation; they are functions that operate on a set of input components and produce a set of output components. Elodin provides decorators that allow for systems to be easily defined from functions.

@elodin.system

This is a lower-level primitive; for many cases @elodin.map – a wrapper around @elodin.system – is easier to use.

This is a lower-level API for defining a system. A function decorated with @elodin.system accepts special parameter types (such as elodin.Query and elodin.GraphQuery) that specify what data the system needs access to. It returns an elodin.Query containing one or more components. Some examples of @elodin.system are:

import elodin as el

@el.system
def gravity(
    graph: el.GraphQuery[GravityEdge],
    query: el.Query[el.WorldPos, el.Inertia],
) -> el.Query[el.Force]: ...

@el.system
def apply_wind(
    w: el.Query[Wind], q: el.Query[el.Force, el.WorldVel]
) -> el.Query[el.Force]: ...

A system's name identifies it in compiled code and in Timing.systems() receipts. It defaults to the function's module and qualified name, such as sim.apply_wind; @el.system(name="wind"), @el.map(name=...) and @el.map_seq(name=...) set it.

@elodin.map

Graph queries cannot be used with @elodin.map. Use @elodin.system instead.

This is a higher-level API for defining a system that reduces the boilerplate of @elodin.system by unpacking the input and output queries into individual components, and wrapping the body of the function in a query.map(ret_type, ...) call. It is useful for systems with simple data flow patterns. Some examples of @elodin.map are:

import elodin as el

@el.map
def gravity(f: el.Force, inertia: el.Inertia) -> el.Force: ...

@el.map
def gyro_omega(vel: el.WorldVel) -> GyroOmega: ...

The following systems are equivalent as the @elodin.map definition effectively desugars to the @elodin.system one:

import elodin as el

@el.map
def gravity(f: el.Force, inertia: el.Inertia) -> el.Force:
    return f + el.SpatialForce(linear=inertia.mass() * jnp.array([0.0, -9.81, 0.0]))

@el.system
def gravity(query: el.Query[el.Force, el.Inertia]) -> el.Query[el.Force]:
    return query.map(
        el.Force,
        lambda f, inertia: f + el.SpatialForce(linear=inertia.mass() * jnp.array([0.0, -9.81, 0.0])),
    )

@elodin.map_seq

@elodin.map_seq is similar to @elodin.map. In fact they will produce the same results numerically but their performance differs.

@elodin.map_seq maps over items sequentially, so it does lose some parallelism, but it also preserves jax.lax.cond()'s behavior, which only evaluates one of its consequents. @elodin.map translates all jax.lax.cond()s to jax.lax.select()s, which always evaluates both of its consequents. So in cases where one of your consequents is both expensive and seldom, @elodin.map_seq can be faster than @elodin.map.

On the Cranelift backend, @elodin.map_seq compiles the function once and calls it for each entity. For a large per-entity function, such as a filter update over a covariance matrix, this is faster than @elodin.map; for small functions @elodin.map remains faster.

import elodin as el

@el.map_seq
def gravity(f: el.Force, inertia: el.Inertia) -> el.Force: ...

@el.map_seq
def gyro_omega(vel: el.WorldVel) -> GyroOmega: ...

The following systems are equivalent as the @elodin.map_seq definition effectively desugars to the @elodin.system one:

import elodin as el

@el.map_seq
def gravity(f: el.Force, inertia: el.Inertia) -> el.Force:
    return f + el.SpatialForce(linear=inertia.mass() * jnp.array([0.0, -9.81, 0.0]))

@el.system
def gravity(query: el.Query[el.Force, el.Inertia]) -> el.Query[el.Force]:
    return query.map_seq(
        el.Force,
        lambda f, inertia: f + el.SpatialForce(linear=inertia.mass() * jnp.array([0.0, -9.81, 0.0])),
    )

class elodin.Query

Query is the primary mechanism for accessing data in Elodin. It is a view into the world state that is filtered by the components specified in the query. Only entities that have been spawned with all of the query's components will be selected for processing. For example, the query Query[WorldPos, Inertia] would only select entities that have both a WorldPos and an Inertia component (typically via the Body archetype).

  • map(ret_type, map_fn) -> elodin.Query

    Apply a function map_fn to the query's components and return a new query with the specified ret_type return type. map_fn should be a function that takes the query's components as arguments and returns a single value of type ret_type.

    import elodin as el
    
    @el.system
    def gravity(query: el.Query[el.Force, el.Inertia]) -> el.Query[el.Force]:
        return query.map(
            el.Force,
            lambda f, inertia: f + el.SpatialForce(linear=inertia.mass() * jnp.array([0.0, -9.81, 0.0])),
        )

    In this example, ret_type is el.Force and map_fn is a lambda function with the signature (el.Force, el.Inertia) -> el.Force.

    To return multiple components as output, ret_type must be a tuple:

    import elodin as el
    
    @el.system
    def multi_out_sys(query: el.Query[A]) -> el.Query[C, D]:
        return query.map((C, D), lambda a: ...)

class elodin.GraphQuery

GraphQuery is a special type of query for operating on edges in an entity graph. Edges represent relationships between entities and are fundamental for modeling physics systems such as gravity.

A GraphQuery requires exactly one type argument, which must be an annotated elodin.Edge component. For example, GraphQuery[GravityEdge] is a valid graph query if GravityEdge is a component with Edge as the base class:

GravityEdge = typing.Annotated[elodin.Edge, elodin.Component("gravity_edge")]
  • edge_fold(left_query, right_query, return_type, init_value, fold_fn) -> elodin.Query

    For each edge, query the left and right entity components using left_query and right_query, respectively. Then, apply the fold_fn function to those input components to compute the return_type output component(s).

    The return_type component(s) must belong to the left entity of the edge.

    A single left entity may have edges to multiple right entities, but it can only hold a single value for each return_type component. So, the fold_fn computations for each entity's edges must be accumulated into a single final value. To carry the intermediate results, fold_fn takes an "accumulator" value as the first argument. Its output is set as the accumulator value for the next iteration. init_value is the initial value of the accumulator.

    edge_fold makes no guarantees about the order in which edges are processed. For associative operators like +, the order the elements are combined in is not important, but for non-associative operators like -, the order will affect the final result.

    See the Three-Body Orbit Tutorial for a practical example of using edge_fold to compute gravitational forces between entities.



Primitives

class elodin.PrimitiveType

  • elodin.PrimitiveType.F64 -> elodin.PrimitiveType

    A constant representing the 64-bit floating point data type.

  • elodin.PrimitiveType.U64 -> elodin.PrimitiveType

    A constant representing the 64-bit unsigned integer data type.

class elodin.Quaternion

Unit quaternions are used to represent spatial orientations and rotations of bodies in 3D space.



Spatial Vector Algebra

Elodin uses Featherstone’s spatial vector algebra notation for rigid-body dynamics as it is a compact way of representing the state of a rigid body with six degrees of freedom. You can read a short into here or in Rigid Body Dynamics Algorithms (Featherstone - 2008).

class elodin.SpatialTransform

A spatial transform is a 7D vector that represents a rigid body transformation in 3D space.

class elodin.SpatialMotion

A spatial motion is a 6D vector that represents either the velocity or acceleration of a rigid body in 3D space.

  • __init__(angular, linear) -> elodin.SpatialMotion

    Create a spatial motion from an angular and a linear vector. Both arguments are optional and default to zero vectors.

    • angular : jax.Array with shape (3), default is [0, 0, 0]
    • linear : jax.Array with shape (3), default is [0, 0, 0]
  • linear() -> jax.Array

    Get the linear part of the spatial motion as a vector with shape (3,).

  • angular() -> jax.Array

    Get the angular part of the spatial motion as a vector with shape (3,).

  • __add__(other) -> elodin.SpatialMotion

    Add two spatial motions.

class elodin.SpatialForce

A spatial force is a 6D vector that represents the linear force and torque applied to a rigid body in 3D space.

  • __init__(arr, torque, force) -> elodin.SpatialForce

    Create a spatial force from either arr or torque and force. If no arguments are provided, the spatial force is initialized to zero torque and force.

    • arr : jax.Array with shape (6)
    • torque : jax.Array with shape (3), default is [0, 0, 0]
    • force : jax.Array with shape (3), default is [0, 0, 0]
  • force() -> jax.Array

    Get the linear force part of the spatial force as a vector with shape (3,).

  • torque() -> jax.Array

    Get the torque part of the spatial force as a vector with shape (3,).

  • __add__(other) -> elodin.SpatialForce

    Add two spatial forces.

class elodin.SpatialInertia

A spatial inertia is a 7D vector that represents the mass and the symmetric 3x3 moment of inertia tensor of a rigid body, expressed in the body frame about its center of mass. The layout is $[I_{xx}, I_{yy}, I_{zz}, I_{xy}, I_{xz}, I_{yz}, m]$, and the full tensor is

$$I = \begin{bmatrix} I_{xx} & I_{xy} & I_{xz} \\ I_{xy} & I_{yy} & I_{yz} \\ I_{xz} & I_{yz} & I_{zz} \end{bmatrix}$$

If the body axes are its principal axes, the off-diagonal entries are zero and only the diagonal is needed.

The off-diagonal entries are the signed entries of the tensor matrix, $I_{xy} = -\int xy , dm$, not products of inertia. CAD tools usually report products of inertia $P_{xy} = +\int xy , dm$; negate them before passing them in ($I_{xy} = -P_{xy}$).

  • __init__(mass, inertia=None, inertia_off_diag=None) -> elodin.SpatialInertia

    Create a spatial inertia from a scalar mass, an optional tensor diagonal $[I_{xx}, I_{yy}, I_{zz}]$, and optional off-diagonal entries $[I_{xy}, I_{xz}, I_{yz}]$. If inertia is not provided, the diagonal is set to the mass along all axes. If inertia_off_diag is not provided, it is zero.

    • mass : real scalar (int, float, or 0-D array)
    • inertia : real array-like with shape (3,), optional
    • inertia_off_diag : real array-like with shape (3,), optional

    Ints, lists, tuples, and int or float32 arrays are converted to float64. Concrete (non-traced) values are validated. A TypeError or ValueError is raised if:

    • an argument is not real-valued (e.g. a bool, string, or complex number) or has the wrong shape
    • the mass is not finite and > 0
    • an inertia entry is not finite
    • the tensor is not positive-definite
    • the principal moments violate the triangle inequality $\lambda_1 + \lambda_2 \geq \lambda_3$, which every physical rigid body satisfies

    Values traced inside a system (e.g. in @el.map) are checked for shape only and must already be float64; cast them with .astype(jnp.float64) if needed.

  • from_array(arr) -> elodin.SpatialInertia

    Create a spatial inertia from a real array-like with shape (7,) in the layout above. Concrete values are converted and validated the same way as __init__.

  • mass() -> jax.Array

    Get the scalar mass of the spatial inertia.

  • inertia_diag() -> jax.Array

    Get the tensor diagonal $[I_{xx}, I_{yy}, I_{zz}]$ with shape (3,).

  • inertia_off_diag() -> jax.Array

    Get the signed off-diagonal tensor entries $[I_{xy}, I_{xz}, I_{yz}]$ with shape (3,).

  • inertia_matrix() -> jax.Array

    Get the full symmetric inertia tensor with shape (3, 3).

  • asarray() -> jax.Array

    Get the underlying 7D array.



Elodin DB Client

The elodin.db module is a standalone Elodin DB client for plain Python processes — ones that are not an Elodin simulation. It can start or connect to a database, write telemetry (batched, typed, and shaped), and read it back (latest value, historical ranges, live streams, fixed-rate replay, SQL, and message logs). See the Python Client guide for a walkthrough; inside simulation callbacks use elodin.StepContext instead.

All timestamps in the public API are microseconds (int), the database's native resolution.

import elodin.db as edb

class elodin.db.Client

Client for a running Elodin DB (external elodin-db run or an embedded elodin.db.Server). Usable as a context manager.

  • connect(addr) -> elodin.db.Client (classmethod)

    Connect to a database. Writers and the latest-value subscription reconnect automatically with exponential backoff.

    • addr : string, e.g. "127.0.0.1:2240".
  • table_writer(schema, queue="drop-oldest", maxlen=1024, timestamp="us") -> elodin.db.TableWriter

    Create a batched writer for a fixed set of components sharing one timestamp.

    • schema : dict[str, Field], component name → field spec (e.g. {"drone.imu.accel": edb.f64[3].labeled("x", "y", "z")}).
    • queue : string, overflow policy for write_nowait: "drop-oldest" (default; evicts the oldest queued row so fresh telemetry wins) or "drop-newest" (discards the incoming row).
    • maxlen : int, bounded queue depth, defaults to 1024.
    • timestamp : string, shared timestamp unit: "us" (default) or "ns" for nanosecond sources (the database stores microseconds).
  • send(name, values, timestamp_us) -> None

    Convenience single-component f64 write (one writer cached per name). Prefer table_writer for hot loops.

  • components() -> dict[str, ComponentInfo]

    All components registered in the database (name → elodin.db.ComponentInfo).

  • earliest_timestamp() -> int

    Earliest data timestamp in the database (microseconds).

  • latest(name) -> elodin.db.Sample | None

    Latest sample seen on the real-time stream. Starts a background subscription on first call, so it may return None until data flows. Values keep their true dtype and shape (an i64 counter comes back as int64, a 3×3 tensor as shape (3, 3)).

  • time_series(name, start_us, stop_us, limit=None) -> (numpy.ndarray, numpy.ndarray)

    Historical samples of name in [start_us, stop_us), paginated internally for large ranges. Returns (timestamps, values): timestamps is int64 microseconds of shape (N,); values has shape (N, *component_shape) and the component's dtype.

  • stream(names, rate_hz=None, start=None, maxlen=1024) -> elodin.db.ComponentStream

    Iterate rows of the named components.

    • names : string | list[str], components to include.
    • rate_hz : float, optional. None (default) streams new data live; a value replays recorded data at a fixed rate.
    • start : replay start (requires rate_hz): "earliest" (default), "latest", or an int microsecond timestamp.
    • maxlen : int, bounded row-queue depth. Replay streams backpressure instead of dropping rows.
  • sql(query) -> pyarrow.Table

    Run a DataFusion SQL query over the same socket. Component time series are exposed as tables named by elodin.db.sql_table_name (e.g. drone.imu.accel → drone_imu_accel), each with a time column plus one column per element.

  • send_msg(name, payload, timestamp_us) -> None

    Append one message to the log named name. Payload encoding is a v1 convenience: bytes pass through untouched, str is UTF-8, anything else is JSON.

  • get_msgs(name, start_us, stop_us, limit=None, raw=False) -> list[(int, payload)]

    Historical messages as [(timestamp_us, payload)]. Bounds follow the database's message-log semantics: the range is inclusive of stop_us, and start_us snaps to the message at or before it. Payloads are JSON-decoded when they parse as JSON; pass raw=True for bytes.

  • msg_stream(name, maxlen=1024, raw=False) -> elodin.db.MessageStream

    Live stream of new messages on name as (timestamp_us, payload) tuples. Bursts may coalesce to the latest message per server wake; use get_msgs for lossless history.

  • state() -> string

    Connection state of the latest-value subscription: "Disconnected", "Connecting", "Connected", or "Reconnecting".

  • close() -> None

    Stop the client's background threads and cached writers.

class elodin.db.Server

Embedded Elodin DB server — the same engine as elodin-db run — for tests, notebooks, and single-process setups. Usable as a context manager.

  • start(path, addr="127.0.0.1:2240") -> elodin.db.Server (static)

    Bind addr (errors such as port-in-use raise immediately) and serve the database at path on a background thread until stop() or process exit.

  • addr -> string, path -> string

    The bound address and data directory.

  • stop() -> None

    Stop the server; existing data stays on disk.

class elodin.db.TableWriter

Batched telemetry writer: every write emits exactly one Impeller Table packet — a shared i64 timestamp followed by each field's values — one packet per tick, not one per component. All declared fields are required on every write; use one writer per rate group. Reconnects automatically, replaying the metadata + vtable handshake. Usable as a context manager.

  • write(timestamp_us=None, values=None, *, timestamp_ns=None) -> None

    Blocking write; raises if the row cannot be handed to the socket. Pass the kwarg matching the writer's timestamp unit.

    • values : dict[str, array-like], one entry per declared field.
  • write_nowait(timestamp_us=None, values=None, *, timestamp_ns=None) -> None

    Non-blocking write for control loops: costs microseconds, never blocks, and never raises for transport reasons. On overflow or an unreachable database, rows are shed per the queue policy and counted in dropped.

  • dropped -> int

    Rows shed so far (queue overflow or connection loss).

  • last_error -> string | None

    Most recent transport error or database rejection — e.g. re-registering an existing component with a different shape surfaces here asynchronously.

  • state() -> string

    "Connected" or "Disconnected".

  • row_size -> int

    Packed row size in bytes (timestamp + all fields).

  • close() -> None

    Close the writer and join its thread.

Timestamps must be monotonically increasing per component; the database rejects out-of-order writes.

Schema fields (elodin.db.Field)

Field specs declare a component's dtype, shape, and optional element labels. The module exposes one instance per primitive type — f64, f32, i8…i64, u8…u64, bool_ — which you index and label:

edb.f64                            # scalar
edb.f32[3]                         # vector of 3
edb.f64[3, 3]                      # rank-2 tensor (up to rank 3)
edb.f64[3].labeled("x", "y", "z")  # editor axis labels (element_names)
  • __getitem__(dims) -> elodin.db.Field — set the shape (int or tuple, up to rank 3).
  • labeled(*names) -> elodin.db.Field — one label per element; drives Editor axis labels.
  • dtype -> numpy.dtype, count -> int, nbytes -> int.

class elodin.db.Sample

One component sample from Client.latest.

  • name : string — component name.
  • timestamp_us : int.
  • values : numpy.ndarray — true dtype and shape.

class elodin.db.StreamRow

One row from Client.stream: the requested components present in that tick.

  • timestamp_us : int — the newest sample timestamp in the row.
  • values : dict[str, numpy.ndarray]; also indexable directly (row["drone.imu.accel"]).
  • timestamps : dict[str, int] — each component's own sample timestamp. A batched stream carries each component's latest value, so when mixing rates a slow component's sample can be older than timestamp_us.

class elodin.db.ComponentStream / elodin.db.MessageStream

Iterators returned by Client.stream and Client.msg_stream. Iteration ends when the stream is closed or its connection fails. Both are context managers; call close() to stop the underlying subscription.

class elodin.db.ComponentInfo

Component schema + metadata from Client.components().

  • name : string, prim_type : string (e.g. "f64"), shape : list[int], element_names : list[str], metadata : dict[str, str].

function elodin.db.sql_table_name

  • sql_table_name(component_name) -> string

    The DataFusion table name the database derives from a component name (e.g. drone.imu.accel → drone_imu_accel). Delegates to the exact conversion the server uses, so it can never drift.

Set ELODIN_DB_LOG=debug (any tracing filter works) to surface the embedded server's and client's diagnostics from an elodin.db-using process.



Schematic Syntax for 3D Objects

When visualizing entities in the Elodin editor, you can define 3D objects using KDL schematic syntax. The object_3d declaration connects a visual representation to an entity's world_pos component.

Basic Shapes

Create basic geometric shapes with customizable dimensions and colors:

object_3d ball.world_pos {
    sphere radius=0.2 {
        color 25 50 255  // RGB values (0-255), optional alpha
    }
}

object_3d box.world_pos {
    box x=1.0 y=1.0 z=1.0 {
        color 255 128 0
    }
}

object_3d ground.world_pos {
    plane width=20 depth=20 {
        color 32 128 32
    }
}

object_3d cylinder.world_pos {
    cylinder radius=0.5 height=2.0 {
        color 100 100 200
    }
}

A plane is a horizontal ground rectangle in the object's frame (XY, normal +Z / up). Identity attitude (0,0,0,1, …) therefore stays a floor after the frame→Bevy basis change.

Ellipsoids with Dynamic Scaling

Create ellipsoids that can dynamically change size based on component values:

object_3d satellite.world_pos {
    ellipsoid scale="(1, 1, 2)" {
        color 200 200 0
    }
}

The scale parameter accepts an EQL expression for dynamic sizing. It must evaluate to at least 3 values in meters. The expression can be a literal tuple, a vector component, indexed component values, scalar-vector math, or values from multiple components:

object_3d vehicle.world_pos {
    ellipsoid scale="2.0 * vehicle.pos_std_var" {
        color 200 200 0
    }
}

object_3d vehicle.world_pos {
    ellipsoid scale="1.91*(vehicle.pos_std_var[1], vehicle.pos_std_var[0], vehicle.pos_std_var[2])" {
        color 200 200 0
    }
}

object_3d vehicle.world_pos {
    ellipsoid scale="3.0 * (vehicle.pos_std_var[1], 0.0, target.pos_std_var[2])" {
        color 200 200 0
    }
}

GLB Models

Load external 3D models from GLB files with optional transformations:

object_3d aircraft.world_pos {
    glb path="f22.glb" scale=0.01 translate="(0, 0, 1.5)" rotate="(0, 90, 0)"
}

GLB Parameters:

  • path (required): Path or URL to the GLB file
  • scale (optional): Uniform scale multiplier (default: 1.0)
  • translate (optional): Translation offset as "(x, y, z)" tuple in meters (default: "(0, 0, 0)")
  • rotate (optional): Rotation as "(x, y, z)" Euler angles in degrees (default: "(0, 0, 0)")

Example use cases:

Scale down a large model:

object_3d rocket.world_pos {
    glb path="rocket.glb" scale=0.1
}

Offset model origin to center of mass:

object_3d drone.world_pos {
    glb path="drone.glb" translate="(0, 0, -0.05)"
}

Rotate model to match simulation frame:

object_3d vehicle.world_pos {
    glb path="car.glb" rotate="(0, 0, 180)"
}

Combine all transformations:

object_3d jet.world_pos {
    glb path="jet.glb" scale=0.01 translate="(0, 0, 0.5)" rotate="(0, 90, 0)"
}

Notes:

  • Transformations are applied in order: scale → rotate → translate
  • Rotations use XYZ Euler order
  • Coordinates are in the simulation's coordinate frame
  • The parent entity's world_pos determines the base position, and these transformations are applied as offsets



EQL Viewport Formulas

When defining viewport positions in schematics, you can use EQL (Elodin Query Language) formulas to apply rotations and translations to entity positions. These formulas are chainable and operate on elodin.WorldPos (SpatialTransform) data.

Rotation Formulas

Rotation formulas modify the orientation quaternion of a spatial transform. All angles are specified in degrees.

Body-Frame Rotations

Body-frame rotations apply relative to the entity's local coordinate system (the axes rotate with the entity):

  • rotate_x(angle) - Rotate about the body X axis (roll)
  • rotate_y(angle) - Rotate about the body Y axis (pitch)
  • rotate_z(angle) - Rotate about the body Z axis (yaw)
  • rotate(x, y, z) - Apply combined XYZ Euler rotations in order

Example - FPV camera rotated 90° right:

viewport name=FPVCamera pos="aircraft.world_pos.rotate_z(-90)" show_grid=#true

World-Frame Rotations

World-frame rotations apply relative to the world coordinate system (independent of entity orientation):

  • rotate_world_x(angle) - Rotate about the world X axis
  • rotate_world_y(angle) - Rotate about the world Y axis
  • rotate_world_z(angle) - Rotate about the world Z axis
  • rotate_world(x, y, z) - Apply combined XYZ Euler rotations in world frame

Example - Camera tilted down 15° in world space:

viewport name=TopView pos="satellite.world_pos.rotate_world_y(-15)" look_at="earth.world_pos"

Translation Formulas

Translation formulas modify the position component of a spatial transform.

Body-Frame Translations

Body-frame translations move the camera relative to the entity's local axes (the offset direction rotates with the entity):

  • translate_x(distance) - Translate along body X axis (forward/back)
  • translate_y(distance) - Translate along body Y axis (left/right)
  • translate_z(distance) - Translate along body Z axis (up/down)
  • translate(x, y, z) - Apply combined XYZ translation

An optional trailing true (.translate(x, y, z, true), also on translate_x/y/z and direction) uses the absolute orientation sense (att · offset), matching orientation=absolute meshes. The default (or false) matches orientation=relative. In ENU the two coincide; cameras chasing absolute objects in ECEF/NED should pass true.

Example - Camera 2m behind and 1m above in body frame:

viewport name=ChaseCamera pos="car.world_pos.translate_x(-2.0).translate_z(1.0)"

World-Frame Translations

World-frame translations move the camera in world coordinates (the offset stays fixed regardless of entity orientation):

  • translate_world_x(distance) - Translate along world X axis (East in ENU)
  • translate_world_y(distance) - Translate along world Y axis (North in ENU)
  • translate_world_z(distance) - Translate along world Z axis (Up in ENU)
  • translate_world(x, y, z) - Apply combined XYZ translation

Example - Chase camera at fixed world offset:

viewport name=Viewport pos="drone.world_pos.translate_world(-5, -5, 3)" look_at="drone.world_pos"

Geo-Frame Conversion Formulas

Directed converters re-express positions (and free directions) between ENU, NED, and ECEF. The source frame is in the method name — it is never inferred from schematic coordinate.

Points / poses (affine; ECEF ↔ local uses the schematic coordinate lat/lon/alt origin):

  • ecef_to_ned(), ned_to_ecef(), ecef_to_enu(), enu_to_ecef(), enu_to_ned(), ned_to_enu()

Vectors (rotation only — use for velocities, up= vectors, etc.):

  • ecef_to_ned_vector(), ned_to_ecef_vector(), ecef_to_enu_vector(), enu_to_ecef_vector(), enu_to_ned_vector(), ned_to_enu_vector()

These work in viewport / object_3d EQL and in query_plot EQL (translated to SQL with the schematic origin baked in). ENU ↔ NED needs no origin; ECEF conversions error if origin is unset.

A plain graph plots raw component elements straight from the database and cannot apply a conversion, so it rejects these formulas — use query_plot instead. Both the whole component (rocket.world_pos.ecef_to_ned()) and an explicit element triple ((rocket.world_pos[4], rocket.world_pos[5], rocket.world_pos[6]).ecef_to_ned()) are accepted.

coordinate frame="ECEF" lat=28.5 lon=-80.6

# Local NED chase offset while the sim pose is ECEF
viewport pos="rocket.world_pos.ecef_to_ned().translate(-2, 0, 0, true).ned_to_ecef()"
         look_at="rocket.world_pos"

# Plot NED northing from an ECEF world_pos (query_plot)
query_plot query="rocket.world_pos.ecef_to_ned()"

Math Formulas

sqrt(), abs(), sign(), degrees(), arccos(), clip(min, max), atan2(x), and norm() evaluate in viewport, object_3d, and vector_arrow EQL as they do in graphs, e.g. rocket.world_pos.translate(0, 0, rocket.drag.norm()). Integer components promote to floats in arithmetic and indexing.

Chaining Formulas

All rotation and translation formulas can be chained together to create complex camera behaviors:

// Rotate 90° right, then move 2m left in new orientation, then offset up 5m in world space
viewport pos="jet.world_pos.rotate_z(-90).translate_y(-2.0).translate_world_z(5.0)"

// Multiple rotations
viewport pos="satellite.world_pos.rotate_x(45).rotate_z(90)"

// Body-frame position then world-frame adjustment
viewport pos="aircraft.world_pos.translate(1, 0, 0.5).translate_world(0, 0, 10)"

Usage Notes

  • Body-frame functions (rotate, translate) are ideal for:

    • FPV cameras that move with the vehicle
    • Wing-mounted or cockpit cameras
    • Camera positions defined relative to vehicle geometry
  • World-frame functions (rotate_world, translate_world) are ideal for:

    • Chase cameras that maintain fixed world offset
    • Orbital cameras
    • External tracking cameras
  • Rotations are applied before translations when chained

  • The old + operator for viewport positions is equivalent to translate_world()