Skip to content

Step-by-Step Tutorial: Creating 3D Animal Digital Twins in Annolid

This guide walks you step by step through creating, customizing, driving, and experimenting with 3D Animal Digital Twins in Annolid—covering Mouse, Rat (Rat v2 + NCAP spinal circuits), and Drosophila (FlyBody + LIF spiking connectome) across GUI, CLI, Annolid Bot, and Python workflows.

Depending on your research goal, Annolid lets you work in both directions:

  • Interactive & Sim-to-Real Digital Twins: Configure or automatically match a 3D digital twin to your real lab arena, lighting, coat strain, and camera angle—then render pixel-exact synthetic pose and body-part datasets to train vision models with zero manual labeling.
  • Real-to-Sim Digital Twins: Lift 2D/3D tracked keypoints (from monocular depth or calibrated multi-camera rigs) into a physically bounded 3D biomechanical twin to inspect joint angles, antagonistic muscle forces, mechanical power, and latent neural circuit phenotypes.
3 Built-In Species Mouse 3D · 41-Bone Rat v2 · FlyBody
10 Neuroscience Arenas Open Field, EPM, Barnes, Y/T-Maze & more
Zero-Dependency Core Offline Three.js + pure-NumPy IK/NCAP/LIF
Real-to-Sim & Sim-to-Real Video matching, 31-DOF IK & Colab training

Annolid three-species 3D animal digital twins showing procedural Mouse 3D, 41-bone Long-Evans Rat v2 with spinal NCAP, and Drosophila FlyBody with LIF brain Figure 1: Annolid's three built-in 3D animal digital twin families—procedural Mouse 3D (10 neuroscience arenas), 41-bone skinned Long-Evans Rat v2 with spinal NCAP locomotion, and Drosophila FlyBody with LIF connectome control.


Choose Your Digital Twin Path

Goal Starting Input Best Workflow in Annolid Jump To
Explore an interactive 3D Mouse, Rat, or Fly twin immediately None (built-in) View → 3D & Reconstruction → 3D Examples Step 1
Clone your lab arena & camera into a 3D twin to train pose/part models 1+ unlabeled .mp4 videos AI & Models → Sim-to-Real Studio… / annolid-run sim2real Step 2
Drive a 3D digital twin from tracked real-animal video poses Tracked pose.ndjson (+ optional depth.ndjson) Run Simulation to 3D Viewer… / annolid-run predict simulation_runner Step 3
Run in-silico spinal ablations, optogenetics, or associative learning Python script annolid.simulation (RatNCAPController, FlyBrainController) Step 4

Prerequisites & Optional Runtimes

Annolid's interactive 3D viewers (Three.js ES modules bundled offline) and pure-NumPy biomechanics/neural circuit controllers (annolid.simulation) work out of the box in standard annolid[gui] installations—no external CDNs, SciPy, PyTorch, or MuJoCo required.

Install optional backends only when you need headless synthetic rendering or MuJoCo physics:

  • Headless 3D Mouse / Rat synthetic dataset generation (Sim-to-Real Studio):
.venv/bin/python -m playwright install chromium
  • Optional MuJoCo FlyBody physics backend: See Simulation and FlyBody or run scripts/setup_flybody_uv.sh --venv-dir .venv311 --python 3.11 --flybody-path /path/to/flybody.

Step 1: Launch and Customize an Interactive 3D Digital Twin (GUI)

The fastest way to create and explore a 3D digital twin is inside Annolid's built-in offline Three.js 3D viewer.

1A. Mouse 3D Digital Twin (Multi-Strain & 10 Arenas)

  1. Launch Annolid (annolid).
  2. Open View → 3D & Reconstruction → 3D Examples → Two Mice (or type open threejs example two mice in Annolid Bot).
  3. Use the Simulation Controls drawer in the top-right corner to build your digital twin setup:
  4. Arena: Switch live among 10 calibrated neuroscience apparatuses—Open Field, Home Cage (Bedding), Circular Open Field, Elevated Plus Maze, Y-Maze, T-Maze, Three-Chamber Social, Light-Dark Box, Barnes Maze, and Novel Object (NOR).
  5. Subjects & Coats: Spawn 1–6 subjects, choose coat strains (such as black C57BL/6 and white BALB/c), and adjust Proportions, Fur Detail, and optional neuroscience Headstage / Miniscope attachments.
  6. Behavior & Camera: Switch gaits (walk, trot, gallop), toggle Pose Skeleton Overlay (13 anatomical keypoints), adjust slow-motion playback (0.25×–1.5×), or attach a follow camera to any mouse.

Two-Mouse 3D digital twin in an open-field arena showing realistic fur, ears, vibrissae, and grounded paws Figure 2: Interactive Mouse 3D digital twin in the open-field arena with strain-calibrated coats and grounded articulated limbs.

Top-down view of the Mouse 3D digital twin with the 13-keypoint anatomical skeleton overlay and live HUD Figure 3: Top-down view with the 13-keypoint pose skeleton overlay enabled and live behavioral state, gait frequency, and coordinate HUD.

1B. Long-Evans Rat v2 3D Biomechanical Twin & Spinal NCAP Controller

  1. Open View → 3D & Reconstruction → 3D Examples → Rat NCAP 3D Simulation (for live interactive spinal controls) or Rat NCAP Simulation Example (for a pre-generated stand → walk → trot → bound gait-transition timeline).
  2. Customize the 41-bone, 55-hinge-joint skinned Long-Evans Rat v2 rig right inside the viewer:
  3. Coat Skin: Switch live among black_hooded, cinnamon, and gray.
  4. Arena & Terrain: Choose treadmill, bumpy_terrain (adjustable bump amplitude), open_field, circular_open_field, or elevated_plus_maze.
  5. Neuromechanical Interface: Compare flexor_extensor (antagonistic spring muscles), position_stiffness, position, and direct torque.
  6. Brainstem & Spinal Circuit Controls: Ramp speed (0.00–1.00 m/s) to trigger spontaneous gait transitions, watch the real-time Spinal Oscilloscope & Hildebrand Footfall Diagram, or drag the V0v + V0d Commissural Scale toward 0.0 to reproduce the classic trot-to-bound ablation phenotype in silico.

Three bundled Long-Evans Rat v2 3D digital twin coat skins: black_hooded, cinnamon, and gray Figure 4: The three bundled 41-bone Long-Evans Rat v2 digital twin coats (black_hooded, cinnamon, and gray) rendered in Annolid's Three.js viewer.

1C. Drosophila FlyBody 3D Twin & Connectome Optogenetics

  1. Open View → 3D & Reconstruction → 3D Examples → FlyBody 3D Example to inspect the articulated 3D Drosophila twin with interactive timeline scrubbing and 3D camera controls.
  2. Open View → 3D & Reconstruction → 3D Examples → Fly-Brain → Mouse to experiment with Annolid's LIF Spiking Connectome panel—trigger live Chrimson optogenetic buttons (Walk DNp09, Moonwalk MDN, Freeze Pair1, Groom aDN1, Escape LC4→DNp01) and Reward (PAM DA) / Punish (PPL1 DA) associative Mushroom Body plasticity while watching real-time neural spike rasters drive the 3D body.

FlyBody 3D Drosophila digital twin inside Annolid's Three.js simulation viewer with timeline and camera controls Figure 5: Articulated Drosophila FlyBody 3D digital twin inside Annolid's Three.js viewer with timeline scrubbing and joint telemetry.

Interactive LIF spiking Drosophila connectome HUD with Chrimson optogenetic triggers and dopaminergic plasticity driving a 3D animal twin Figure 6: Live LIF spiking connectome panel showing real-time sensory, Mushroom Body, central complex, and descending neuron spike rasters alongside Chrimson optogenetic controls.


Step 2: Clone Your Lab Video Into a Matched 3D Digital Twin (Sim-to-Real)

If you want a 3D digital twin that mirrors your specific lab recording (same arena geometry, camera angle, lighting/IR look, animal scale, coat contrast, and occluders) and automatically generates labeled pose or body-part datasets, use Sim-to-Real Studio.

GUI Walkthrough (5 Guided Tabs)

Open AI & Models → Sim-to-Real Studio (3D Sim → Colab)… (or type /sim2real in Annolid Bot).

Tab 1: Example Videos & Match

  1. Choose a Project Folder (for example ./projects/my_mouse_digital_twin).
  2. Click Add Video(s)… (or Add Image Folder…) and select one or more representative recordings.
  3. Leave Species Hint on Auto-Detect (Mouse / Rat / Fly) (or pin mouse, rat, or fly) and Sampling on Diverse (Foreground + Motion Coreset).
  4. Click Sample Videos & Match 3D Simulation. Annolid extracts clean per-video median arena backgrounds and automatically infers species, arena type, camera perspective, illumination/IR profile, subject count, calibrated 3D body scale (0.75–1.35), and optical blur/noise statistics.

Sim-to-Real Studio Tab 1 showing Example Videos & Match controls for sampling real footage and inferring a matched 3D digital twin environment Figure 7: Sim-to-Real Studio Tab 1 (Example Videos & Match) where Annolid samples diverse frames from your recordings and infers a matched 3D arena, camera, and photometric profile.

Tab 2: 3D Sim Dataset

  1. Review the auto-matched Simulation Engine (Mouse 3D, Rat 3D, or FlyBody 3D), Arena Geometry, Camera View, Lighting / IR, Coat Pair, Occluder, Headstage, Subject Count, and Body Scale.
  2. Select your Dataset Task:
  3. YOLO Pose Estimation (yolo_pose): exports pixel-exact 3D-projected keypoints (mouse13, calms7, topdown6, or 16-point Rat v2) + data.yaml, pose_schema.json, and optional COCO Keypoints.
  4. YOLO Instance / Part Segmentation (yolo_seg): exports whole instances, coarse parts, 5-part semantic_parts, 11-part fine_parts, or hierarchical_parts (whole animal + parts).
  5. Keep Match example video photometry checked, and optionally check Composite simulated subjects onto extracted real arena background so your 3D twin renders directly on your real cage floor with soft contact shadows.
  6. Select one or more Scenarios / Behaviors (such as arena_explore, social_huddle, curled_groom, rearing_social) and click Generate Environment-Matched Synthetic Dataset.

Sim-to-Real Studio Tab 2 showing 3D simulation domain-matching controls, pose schema and part-granularity selectors, photometry matching, and behavior scenario list Figure 8: Sim-to-Real Studio Tab 2 (3D Sim Dataset) displaying full control over the matched 3D digital twin's species, arena, camera, coat, photometry, background compositing, and behavior scenarios.

Tabs 3–5: Train, Iterate & Report

Switch to Tab 3: 3. Train & Iterate to train YOLO, DINOv3 KPSEG, or Keypoint R-CNN on your synthetic digital-twin dataset (locally or on a Google Colab GPU), review automated domain-gap diagnostics in Tab 4: 4. Iterations & Advisor, and open the shareable HTML5/SVG report in Tab 5: 5. Report.

CLI & Annolid Bot Equivalents

Run the exact same video-to-3D-digital-twin workflow headlessly from the terminal:

# 1. Sample real mouse footage and infer matching 3D digital twin parameters
annolid-run sim2real sample \
  --video ./recordings/social_trial_01.mp4 \
  --project ./projects/my_mouse_twin \
  --species mouse \
  --task yolo_pose \
  --pose-schema mouse13 \
  --sampling-strategy diverse \
  --samples-per-video 24

# 2. Render environment-matched 3D digital twin frames composited onto your real arena
annolid-run sim2real generate \
  --project ./projects/my_mouse_twin \
  --composite-bg \
  --frames-per-scenario 24

# 3. Train & evaluate on your real video (local or --train-backend colab --gpu T4)
annolid-run sim2real iterate \
  --project ./projects/my_mouse_twin \
  --model yolo \
  --iterations 1 \
  --train-backend local \
  --epochs 30

# 4. Build Markdown + HTML5/SVG report
annolid-run sim2real report --project ./projects/my_mouse_twin

For a Rat digital twin, swap --species rat --rat-coat black_hooded --rat-interface flexor_extensor --scenarios trot walk gait_transition. You can also ask Annolid Bot in plain English:

"Sample my mouse videos in ./recordings, build a matching 3D mouse pose dataset (calms7), and train a model in the background."


Step 3: Drive a 3D Digital Twin From Real Animal Tracking (Real-to-Sim)

Once you have tracked keypoints from a real recording (pose.ndjson or per-frame LabelMe .json files—for example from FastPose Studio, YOLO-Pose, or DINO-KPSEG), you can reconstruct a physically valid 3D digital twin driven directly by your animal's real trajectory.

3A. Generate a Keypoint-to-Model Mapping File

Map your dataset's keypoint names to the 3D digital twin's anatomical body sites (rat_ncap or flybody):

# Generate a Rat v2 keypoint mapping template (or inspect annolid/configs/rat_ncap_template.yaml)
annolid-run predict simulation_runner \
  --backend rat_ncap \
  --template-keypoints nose,head,thorax,pelvis,left_forepaw,right_forepaw,left_hindpaw,right_hindpaw \
  --write-mapping-template ./rat_mapping.yaml

# Or generate a FlyBody mapping template from an existing pose_schema.json
annolid-run predict flybody \
  --pose-schema ./pose_schema.json \
  --write-mapping-template ./flybody_mapping.yaml

3B. Lift 2D Poses to 3D and Fit the Digital Twin (CLI or GUI)

You can lift 2D poses into 3D in two ways:

  • Monocular Video + Depth Sidecar: Run Video Depth Anything to export depth.ndjson, then pass --depth-ndjson depth.ndjson --depth-sample-mode median_patch (spike-resistant 3×3 median depth sampling).
  • Calibrated Multi-Camera Rig: Use triangulate_multiview_pose_frames() + enforce_anatomical_skeleton_constraints() from annolid.simulation (shown in Step 4).

Run the Real-to-Sim fit from the CLI:

annolid-run predict simulation_runner \
  --backend rat_ncap \
  --input ./tracked/pose.ndjson \
  --depth-ndjson ./tracked/depth.ndjson \
  --depth-sample-mode median_patch \
  --mapping ./rat_mapping.yaml \
  --smooth-mode one_euro \
  --out-ndjson ./tracked/rat_digital_twin_fit.ndjson

Or run and view directly inside Annolid's desktop GUI:

  1. Open View → 3D & Reconstruction → 3D Examples → Run Simulation to 3D Viewer….
  2. Pick Backend (Rat NCAP (Rat v2), FlyBody, or Identity), browse to your Input (pose.ndjson), Mapping (.yaml), optional Depth (depth.ndjson), set Smoothing (one_euro or kalman), and choose an Output .ndjson path.
  3. Click OK to fit the 3D digital twin and stream it straight into the Three.js 3D viewer.
  4. To reopen any saved digital twin rollout later, click View → 3D & Reconstruction → 3D Examples → Open FlyBody / Simulation Output… and choose your .ndjson or .json file.

Step 4: Run In-Silico Biomechanical and Neural Circuit Experiments (Python)

Annolid's pure-NumPy annolid.simulation API lets you script reproducible digital-twin rollouts, inverse kinematics (IK), inverse dynamics (ID), spinal circuit inference, and connectome perturbations with zero heavy ML dependencies.

Example A: Rat v2 31-DOF IK, Muscle Forces & Spinal Circuit Ablation

from annolid.simulation import (
    run_rat_ncap_rollout,
    solve_rat_v2_ik_sequence,
)

# 1. Compare intact vs. V0 commissural-ablated spinal circuit rollouts
intact = run_rat_ncap_rollout(
    steps=90,
    behavior="trot",
    interface="flexor_extensor",
    coat="black_hooded",
)
ablated = run_rat_ncap_rollout(
    steps=90,
    behavior="trot",
    interface="flexor_extensor",
    coat="black_hooded",
    ablation="v0v_v0d",
    ablation_scale=0.0,
)
print("Intact gait  :", intact["metadata"]["dominant_gait"])   # "trot"
print("V0-ablated   :", ablated["metadata"]["dominant_gait"])  # "bound"

# 2. Run Real-to-Sim 31-DOF IK, exact KKT muscle ID & blind spinal phenotype inference
keypoints_3d_seq = [frame["keypoints_3d"] for frame in intact["frames"][:60]]
fit = solve_rat_v2_ik_sequence(
    keypoints_3d_seq,
    dt=0.02,
    interface_type="flexor_extensor",
)
print("IK RMSE (m)     :", fit["summary"]["mean_ik_rmse_m"])                  # ~0.0056 m
print("Joint violations:", fit["summary"]["joint_limit_violations"])          # 0
print("Torque residual :", fit["inverse_dynamics"]["torque_residual_rmse_nm"])# ~0.022 N*m
print("Phenotype       :", fit["spinal_circuit_inference"]["phenotype_class"])# "intact_trot"
print("V0 integrity    :", fit["spinal_circuit_inference"]["v0_integrity_index"])

Example B: Multi-Camera Triangulation & Rigid-Bone Projection

from annolid.simulation import (
    RAT_V2_RIGID_BONE_EDGES,
    CameraCalibration,
    enforce_anatomical_skeleton_constraints,
    triangulate_multiview_pose_frames,
)

cam0 = CameraCalibration.from_look_at(
    name="cam0",
    position=[0.7, 0.0, 0.5],
    target=[0.0, 0.0, 0.05],
    fx=820.0,
    fy=820.0,
    cx=320.0,
    cy=240.0,
    distortion=(0.08, -0.02, 0.001, -0.001),
)
# Pass your dictionary of {camera_name: list_of_2d_frame_dicts} and {camera_name: CameraCalibration}
# frames_3d, tri_summary = triangulate_multiview_pose_frames(views_by_cam, calibrations, outlier_reproj_thresh_px=10.0)
# clean_3d, skel_diag = enforce_anatomical_skeleton_constraints(frames_3d, RAT_V2_RIGID_BONE_EDGES, iterations=8)

Example C: Drosophila LIF Connectome Optogenetics & Associative Plasticity

from annolid.simulation import (
    FlyBrainController,
    build_plastic_fly_connectome,
    build_spiking_fly_connectome,
)

# Inspect or perturb a 1,470-neuron LIF spiking connectome (pass your action_spec from FlyBody)
# ctrl = FlyBrainController(
#     action_spec,
#     behavior="walk_imitation",
#     connectome=build_spiking_fly_connectome(seed=7),
#     dynamics="spiking",
#     synaptic_noise_std=0.2,
# )
# ctrl.stimulate_cell_type("MDN", current=2.4, duration_sec=0.12)  # trigger moonwalk
# ctrl.set_ablation("VNC_MDN_Inh", scale=0.0)                      # Kir2.1 silencing

Step 5: Reproducible Captures, Troubleshooting & Next Steps

  • Deterministic Mouse 3D dataset export: Re-generate reproducible seeded captures directly from the command line:
.venv/bin/python scripts/generate_two_mice_pose_dataset.py --output ./two_mice_preview