flybody is an anatomically-detailed body model of the fruit fly Drosophila melanogaster for the MuJoCo physics simulator and reinforcement learning applications.
The fly model was developed in a collaborative effort by Google DeepMind and HHMI Janelia Research Campus.
We envision our model as a platform for fruit fly biophysics simulations and for modeling neural control of sensorimotor behavior in an embodied context; see our accompanying publication.
- Quick Start
- Installation
- Project Structure
- Architecture Overview
- Task Environments
- Data Downloads
- Scripts
- Development
- Contributing
- Tutorials & Notebooks
- Citing flybody
- License
import numpy as np
import mediapy
from flybody.fly_envs import walk_imitation
# Create walking imitation environment.
env = walk_imitation()
# Run environment loop with random actions for a bit.
for _ in range(100):
action = np.random.normal(size=59) # 59 is the walking action dimension.
timestep = env.step(action)
# Generate a pretty image.
pixels = env.physics.render(camera_id=1)
mediapy.show_image(pixels)Also see the tutorial notebook or .
uv is the recommended package manager for flybody. It handles virtual environments and dependency resolution in a single tool.
-
Install uv (if not already installed):
curl -LsSf https://astral.sh/uv/install.sh | sh -
Clone and set up:
git clone https://github.com/TuragaLab/flybody.git cd flybody uv venv --python 3.10 source .venv/bin/activate
-
Core installation β minimal install for experimenting with the fly model in MuJoCo or prototyping task environments:
uv pip install -e . -
ML extension (optional) β adds TensorFlow and Acme for running policy networks:
uv pip install -e ".[tf]" -
Ray training extension (optional) β adds Ray for distributed DMPO training:
uv pip install -e ".[ray]" -
Dev tools (optional) β adds ruff, JupyterLab, tqdm:
uv pip install -e ".[dev]" -
Everything:
uv pip install -e ".[all]"
Or use the setup script:
bash scripts/setup.sh # core
bash scripts/setup.sh --all # everythingClick to expand conda/pip instructions
-
Clone and create a conda environment:
git clone https://github.com/TuragaLab/flybody.git cd flybody conda create --name flybody -c conda-forge python=3.10 pip ipython cudatoolkit=11.8.0 conda activate flybodyInstall in one of the modes (add
-efor editable/developer mode): -
Core:
pip install -e . -
ML extension:
pip install -e ".[tf]" -
Ray training:
pip install -e ".[ray]"
Click to expand remote pip instructions
pip install git+https://github.com/TuragaLab/flybody.git # core
pip install "flybody[tf] @ git+https://github.com/TuragaLab/flybody.git" # ML
pip install "flybody[ray] @ git+https://github.com/TuragaLab/flybody.git" # Ray-
You may need to set MuJoCo rendering environment variables:
export MUJOCO_GL=egl export MUJOCO_EGL_DEVICE_ID=0
-
For ML and Ray extensions,
LD_LIBRARY_PATHmay need an update:CUDNN_PATH=$(dirname $(python -c "import nvidia.cudnn;print(nvidia.cudnn.__file__)")) export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/:$CUDNN_PATH/lib
-
Verify your installation:
uv run pytest tests/ -v
flybody/
βββ README.md # This file
βββ AGENTS.md # AI agent guidance
βββ pyproject.toml # Package config & dependencies
βββ LICENSE # Apache 2.0
βββ fly-white.png # Hero image
β
βββ flybody/ # Source package
β βββ __init__.py
β βββ fly_envs.py # β
Environment factory functions
β βββ fruitfly/ # Walker model
β β βββ fruitfly.py # FruitFly composer.Walker class
β β βββ assets/ # MuJoCo XML + 85 OBJ meshes
β β βββ fruitfly.xml # Main fly model definition
β β βββ floor.xml # Floor arena for visualization
β βββ tasks/ # RL task definitions
β β βββ base.py # FruitFlyTask, Flying, Walking base classes
β β βββ flight_imitation.py # Flight trajectory tracking
β β βββ walk_imitation.py # Walking trajectory tracking
β β βββ walk_on_ball.py # Tethered walking on floating ball
β β βββ vision_flight.py # Vision-guided flight (bumps/trench)
β β βββ template_task.py # Empty no-op task for testing
β β βββ rewards.py # Reward functions
β β βββ trajectory_loaders.py # HDF5 trajectory dataset loaders
β β βββ synthetic_trajectories.py # Synthetic trajectory generation
β β βββ pattern_generators.py # Wing pattern generators
β β βββ task_utils.py # Task utility functions
β β βββ constants.py # Physics timestep constants
β β βββ arenas/ # Arena definitions (ball, hills)
β βββ agents/ # RL agents (TF/Ray)
β β βββ agent_dmpo.py # DMPO agent
β β βββ learning_dmpo.py # DMPO learner
β β βββ losses_mpo.py # MPO loss functions
β β βββ actors.py # Actor implementations
β β βββ network_factory.py # Network factory for DMPO
β β βββ network_factory_vis.py # Vision network factory
β β βββ ray_distributed_dmpo.py # Ray-distributed DMPO
β β βββ remote_as_local_wrapper.py # Ray remote wrapper
β β βββ counting.py # Step counters
β β βββ utils_ray.py # Ray utilities
β β βββ utils_tf.py # TensorFlow utilities
β βββ train_dmpo_ray.py # β
Distributed training script
β βββ download_data.py # Figshare data download
β βββ ellipsoid_fluid_model.py # Ellipsoid fluid dynamics
β βββ inverse_kinematics.py # Inverse kinematics solver
β βββ quaternions.py # Quaternion math utilities
β βββ loggers.py # MLflow training logger
β βββ utils.py # Rendering & display utilities
β
βββ tests/ # Test suite
β βββ test_flybare.py # Stand-alone fly model tests
β βββ test_flywalker.py # FruitFly walker class tests
β βββ test_core.py # Core RL environment tests
β βββ test_walking_env.py # Walking imitation env tests
β βββ test-tf.py # TensorFlow policy test
β βββ common.py # Shared test utilities
β
βββ docs/ # Tutorial notebooks
β βββ getting-started.ipynb
β βββ fly-env-examples.ipynb
β βββ fly-on-ball-minimal.ipynb
β βββ controller-reuse-vision-flight.ipynb
β βββ sensory-input-tracking.ipynb
β
βββ scripts/ # Orchestration scripts
β βββ setup.sh # Environment setup
β βββ download_data.sh # Data download
β βββ run_tests.sh # Test runner
β βββ lint.sh # Lint runner
β βββ train.sh # Training launcher
β βββ export_all.sh # Master export orchestrator
β βββ render_environments.py # Render still images
β βββ generate_rollout_videos.py # Generate rollout videos
β βββ export_model_data.py # Export model/env data
β βββ explore_physics.py # Standalone physics exploration
β βββ track_sensory_data.py # Sensory data tracking
β βββ explore_task_utils.py # Task utility exercises
β βββ inspect_walker.py # Walker anatomy inspection
β βββ vision_pipeline.py # Vision pipeline
β βββ explore_quaternions.py # Quaternion operations
β βββ explore_rewards.py # Reward function analysis
β βββ explore_arenas.py # Arena construction
β βββ benchmark_envs.py # Environment benchmarks
β
βββ output/ # Generated exports (gitignored)
β βββ images/ # PNG renders from all environments
β βββ videos/ # MP4 rollout videos
β βββ data/ # JSON model parameters & env specs
β βββ physics/ # Physics exploration output
β βββ sensory/ # Sensory data plots
β βββ task_utils/ # Task utility test output
β βββ walker/ # Walker anatomy data
β βββ vision/ # Vision pipeline output
β βββ quaternions/ # Quaternion operations output
β βββ rewards/ # Reward analysis output
β βββ arenas/ # Arena renders
β βββ benchmark/ # Environment benchmark data
β βββ *.log # Execution logs
β
βββ .github/workflows/ # CI pipelines
βββ pytest.yml # Core tests (Python 3.10)
βββ pyversions.yml # Multi-version tests (3.10β3.12)
βββ lint.yml # Ruff linting
βββ tf-test.yml # TensorFlow policy test
flybody is built on the dm_control composer framework. The architecture follows a layered pattern:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β fly_envs.py β
β Factory functions (user-facing API) β
β flight_imitation Β· walk_imitation Β· walk_on_ball β
β vision_guided_flight Β· template_task β
ββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββ€
β FruitFly β Tasks β Arenas β
β (Walker) β FruitFlyTask (base) β floors β
β fruitfly.py β βββ Flying (flight base) β ball β
β β βββ Walking (walk base) β hills β
β 85 OBJ mesh β βββ FlightImitation β β
β fruitfly.xmlβ βββ WalkImitation β β
β β βββ WalkOnBall β β
β β βββ VisionFlight β β
ββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββ€
β dm_control Β· MuJoCo β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Class | Module | Role |
|---|---|---|
FruitFly |
flybody.fruitfly.fruitfly |
Composer Walker β builds the fly model from XML, manages observables and actuators |
FruitFlyTask |
flybody.tasks.base |
Base task β wires walker + arena, defines reward/termination interface |
Flying |
flybody.tasks.base |
Configures fly model for flight (wing params, fluid model, leg disable) |
Walking |
flybody.tasks.base |
Configures fly model for walking (wing retract, adhesion, leg contact) |
All environments are created via factory functions in fly_envs.py:
| Function | Task | Action Dim |
|---|---|---|
flight_imitation() |
Track flying reference trajectory | 22 |
walk_imitation() |
Track walking reference trajectory | 59 |
walk_on_ball() |
Walk on a floating ball (tethered) | 59 |
vision_guided_flight() |
Fly through bumps/trench with vision | 22 |
template_task() |
Empty no-op task for testing | 59 |
Requires the fly to track a reference flying trajectory from an HDF5 dataset. Reward is based on joint angle and body position matching. Uses the Flying base class with ellipsoid fluid dynamics.
Requires the fly to track a reference walking trajectory. Supports inference mode (no dataset needed) for testing. Uses the Walking base class with adhesion actuators.
Tethered walking on a floating ball. Supports both position and force actuators. Minimal task suitable for quick experiments and RL prototyping.
Flight through procedurally generated arenas (bumps or trench) using monocular or binocular eye cameras. Combines locomotion with visual processing.
Empty no-op task that returns a constant reward of 1. Used for unit testing and as a starting point for new tasks.
Supplementary data (reference trajectories, trained policies) are hosted on Figshare:
# Via script
bash scripts/download_data.sh
# Via Python
from flybody.download_data import figshare_download
figshare_download('walking-imitation-dataset')
figshare_download('flight-imitation-dataset')
figshare_download('trained-policies')
figshare_download('controller-reuse-checkpoints')Available dataset keys:
| Key | Description |
|---|---|
walking-imitation-dataset |
Reference walking trajectories (HDF5) |
flight-imitation-dataset |
Reference flight trajectories (HDF5) |
trained-policies |
Pre-trained policy checkpoints |
controller-reuse-checkpoints |
Checkpoints for controller reuse experiments |
Data is downloaded and extracted to flybody-data/ by default.
Thin orchestration scripts live in scripts/. They wrap the real methods in the package β no business logic in scripts.
| Script | Purpose | Usage |
|---|---|---|
setup.sh |
Create venv and install with uv | bash scripts/setup.sh [--tf|--ray|--dev|--all] |
download_data.sh |
Download figshare datasets | bash scripts/download_data.sh [KEY...] |
run_tests.sh |
Run pytest suite | bash scripts/run_tests.sh [PYTEST_ARGS...] |
lint.sh |
Run ruff linting | bash scripts/lint.sh [--fix] |
train.sh |
Launch Ray distributed training | bash scripts/train.sh |
export_all.sh |
Generate images, videos, data, and more | bash scripts/export_all.sh [--all|--images|--videos|--data|--physics|--sensory|--task-utils|--walker|--vision|--quaternions|--rewards|--arenas|--benchmark] |
The export pipeline uses real flybody methods to generate rendered images, rollout videos, model data, and more. All scripts support --output-dir, --width, --height, and other CLI flags:
| Script | Methods Used | Output |
|---|---|---|
render_environments.py |
fly_envs.*(), env.physics.render() |
PNGs in output/images/ |
generate_rollout_videos.py |
fly_envs.*(), utils.rollout_and_render() |
MP4s in output/videos/ |
export_model_data.py |
FruitFly(), env.observation_spec() |
JSONs in output/data/ |
explore_physics.py |
FruitFly, mjcf.Physics, joint/actuator manipulation, wing animation, mocap sites |
PNGs + MP4s in output/physics/ |
track_sensory_data.py |
Per-step observables (joints_pos, velocimeter, world_zaxis), matplotlib plots |
PNGs + JSON in output/sensory/ |
explore_task_utils.py |
All 14 task_utils functions: retract_wings, real2canonicalβcanonical2real, root2comβcom2root, etc. |
JSONs + PNGs in output/task_utils/ |
inspect_walker.py |
Walker anatomy: observable_joints, actuators, end_effectors, cameras, body tree |
JSON + PNGs in output/walker/ |
vision_pipeline.py |
Eye camera rendering, walker/left_eye/right_eye obs, vision-guided flight |
MP4s + PNGs in output/vision/ |
explore_quaternions.py |
All 18 quaternions.* functions: algebra, rotation, metrics, angular velocity |
JSONs in output/quaternions/ |
explore_rewards.py |
compute_diffs, reward_factors_deep_mimic, sensitivity analysis |
JSONs in output/rewards/ |
explore_arenas.py |
BallFloor, Hills, SineTrench, SineBumps construction and rendering |
PNGs + JSON in output/arenas/ |
benchmark_envs.py |
All env factory timing, constants.py validation |
JSONs in output/benchmark/ |
# Generate everything
bash scripts/export_all.sh
# Or selectively
bash scripts/export_all.sh --images # Rendered stills only
bash scripts/export_all.sh --videos # Rollout videos only
bash scripts/export_all.sh --data # Model/env data only
bash scripts/export_all.sh --physics # Standalone physics exploration
bash scripts/export_all.sh --sensory # Sensory data tracking
bash scripts/export_all.sh --task-utils # task_utils exercises
bash scripts/export_all.sh --walker # Walker anatomy inspection
bash scripts/export_all.sh --vision # Vision pipeline
bash scripts/export_all.sh --quaternions # Quaternion operations
bash scripts/export_all.sh --rewards # Reward analysis
bash scripts/export_all.sh --arenas # Arena exploration
bash scripts/export_all.sh --benchmark # Environment benchmarksuv run ruff check flybody/ # Check
uv run ruff check flybody/ --fix # Auto-fix# Core tests (no TF/Ray required)
uv run pytest tests/test_flybare.py tests/test_core.py tests/test_flywalker.py tests/test_walking_env.py -v
# All tests
uv run pytest tests/ -v
# With rendering (requires MUJOCO_GL=egl and GPU)
MUJOCO_GL=egl uv run pytest tests/ -v| Workflow | Trigger | What it tests |
|---|---|---|
pytest.yml |
push/PR to main, dev | Core tests (Python 3.10) |
pyversions.yml |
push/PR to main, dev | test_flybare + test_core on Python 3.10β3.12 |
lint.yml |
push/PR to main, dev | Ruff lint check |
tf-test.yml |
push/PR to main, dev | TensorFlow policy network test |
Drag-and-drop fruitfly.xml or floor.xml into MuJoCo's simulate viewer for interactive visualization.
See the docs/ directory for Jupyter notebooks:
| Notebook | Description |
|---|---|
| Getting Started | Create environments, step with random actions, render images |
| Fly Environment Examples | Flight, walking, and vision-guided flight demos |
| Fly on Ball Minimal | Minimal tethered fly-on-ball walking example |
| Controller Reuse & Vision Flight | Transfer learning and vision-guided flight |
| Sensory Input Tracking | Tracking sensory inputs and body state |
Run notebooks with:
uv pip install -e ".[dev]"
uv run jupyter lab docs/See our accompanying publication. Thank you for your interest in our fly model :)
@article{flybody,
title = {Whole-body physics simulation of fruit fly locomotion},
author = {Roman Vaxenburg and Igor Siwanowicz and Josh Merel and Alice A Robie and
Carmen Morrow and Guido Novati and Zinovia Stefanidi and Gert-Jan Both and
Gwyneth M Card and Michael B Reiser and Matthew M Botvinick and
Kristin M Branson and Yuval Tassa and Srinivas C Turaga},
journal = {Nature},
volume = {643},
pages = {1312--1320},
year = {2025},
doi = {https://doi.org/10.1038/s41586-025-09029-4},
url = {https://www.nature.com/articles/s41586-025-09029-4},
}