# Fruit fly simulation: practical companion

Prepared by dotSuper on 15 September 2026.

[Read the full article](https://dotsuper.net/feeds/applied-systems/how-to-build-fruit-fly-brain-simulation)
[Download the original MaleCNS teaching notebook](https://dotsuper.net/guides/fruit-fly-simulation/malecns-starter.ipynb)

## Scope and execution status

We have not executed these instructions or independently reproduced the papers.
The commands below are starting instructions, not a validated environment lock.
The authors' repositories are the operational references.

There are three separate projects:

1. A published FlyWire/Brian2 neural simulation.
2. A small MaleCNS graph teaching exercise.
3. An anatomical body simulation using flybody.

The MaleCNS notebook is not a physiological model and does not control the body.

## A. Published neural model

Primary references:
- [Paper](https://www.nature.com/articles/s41586-024-07763-9)
- [Repository](https://github.com/philshiu/Drosophila_brain_model)
- [Environment](https://github.com/philshiu/Drosophila_brain_model/blob/main/environment.yml)
- [Example](https://github.com/philshiu/Drosophila_brain_model/blob/main/example.ipynb)
- [Implementation](https://github.com/philshiu/Drosophila_brain_model/blob/main/model.py)

Run these shell commands after installing Git and Conda:

~~~bash
git clone https://github.com/philshiu/Drosophila_brain_model.git
cd Drosophila_brain_model
conda env create -f environment.yml
conda activate brian2
jupyter notebook example.ipynb
~~~

The supplied environment is named brian2. Skip the notebook's Colab-only
installation cell on a local machine. Keep the version-630 neuron CSV and
connectivity Parquet paired. Switching to version 783 requires its matching
pair and an appropriate input-ID selection, not just one newer file.

### An optional smaller first run

This is an editorial adaptation for learning the API, not the paper protocol.
In the authors' notebook, run the import/configuration cells and the cell
defining neu_sugar first. Then use a separate cell like this in place of the
full experiment cell:

~~~python
from copy import deepcopy
from datetime import datetime, timezone
from pathlib import Path
from brian2 import ms
from model import default_params, run_exp

small = deepcopy(default_params)
small["n_run"] = 1
small["t_run"] = 100 * ms

small_config = dict(config)
small_config["n_proc"] = 1
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
folder = Path("results") / ("dotsuper-smoke-" + stamp)
folder.mkdir(parents=True, exist_ok=False)
small_config["path_res"] = str(folder)

run_exp(
    exp_name="sugar_smoke",
    neu_exc=neu_sugar,
    params=small,
    **small_config,
)
~~~

This still loads the model's connectivity. It is not a guarantee of low RAM
requirements. A single short trial cannot establish robust biological results.
Restore the relevant published settings when attempting reproduction.

The returned file contains simulated events. Inspect its schema before analysis.
Use the same run duration and trial count when computing rates:

~~~python
import utils as utl

spikes = utl.load_exps([str(folder / "sugar_smoke.parquet")])
if spikes.empty:
    print("No recorded events. Inspect inputs, duration and model configuration.")
else:
    rate, rate_std = utl.get_rate(
        spikes,
        t_run=small["t_run"],
        n_run=small["n_run"],
    )
    display(rate)
~~~

Do not interpret a one-trial standard deviation as a useful uncertainty estimate.
Use distinct names/directories for subsequent input or intervention conditions.
The upstream function can skip existing output files, so pay attention to its
messages rather than assuming every call performed a new experiment.

If the current upstream code fails, keep the error and environment record and
consult the repository issue tracker. This guide does not claim that those
upstream files were runtime-tested by dotSuper.

## B. MaleCNS teaching notebook

[Dataset documentation](https://male-cns.janelia.org/download/)
[neuPrint authentication](https://connectome-neuprint.github.io/neuprint-python/docs/quickstart.html)
[Query API](https://connectome-neuprint.github.io/neuprint-python/docs/queries.html)

Use a separate environment. Example macOS/Linux shell setup, assuming Python
3.10 is installed:

~~~bash
python3.10 -m venv .venv-malecns
source .venv-malecns/bin/activate
python -m pip install jupyterlab neuprint-python pandas numpy scipy matplotlib
jupyter lab
~~~

On Windows, activate the equivalent environment using its Scripts activation
command instead of the Unix source command.

Open malecns-starter.ipynb in Jupyter. The notebook:

1. Prompts for your own token if NEUPRINT_APPLICATION_CREDENTIALS is unset.
2. Looks up a documented seed type in male-cns:v1.0.
3. Selects no more than 200 nodes and retains internal directed connections.
4. Preserves the graph and its query settings.
5. Runs a deliberately non-biological positive propagation rule.
6. Compares intact propagation with one model-only node ablation.
7. Exports tables, a labelled plot, input hashes and a credential-free manifest.

The initial neighbour query can return more than 200 cells. The cap is applied
to the retained model, not to the size of the server's response.

**The graph update does not include neural firing rates, biological time,
neurotransmitter signs, receptors or a body.** Its output units are arbitrary.
It is a transparent data-handling and model-comparison exercise.

Use your own neuPrint token locally. Do not publish a token or a client-object
dump. Clear any sensitive notebook outputs before sharing. Do not put a token
in a URL, a public repository or a support screenshot.

The queried dataset retains its own attribution requirements. The original
notebook code license below does not relicense the dataset or third-party code.

## C. Anatomical body simulation

[flybody repository](https://github.com/TuragaLab/flybody)
[Published paper](https://www.nature.com/articles/s41586-025-09029-4)
[Official getting-started notebook](https://colab.research.google.com/github/TuragaLab/flybody/blob/main/docs/getting-started.ipynb)

Example isolated local core installation, assuming Git and Conda are installed:

~~~bash
git clone https://github.com/TuragaLab/flybody.git
cd flybody
conda create -n flybody-core -c conda-forge python=3.10 pip
conda activate flybody-core
python -m pip install -e .
~~~

This is a core-only adaptation. It deliberately omits the optional TensorFlow,
Acme, Ray and CUDA training stack. Follow the upstream instructions for training
or controller examples that need those packages.

A short API illustration, adapted from the documented walking environment:

~~~python
import numpy as np
from flybody.fly_envs import walk_imitation

env = walk_imitation()
timestep = env.reset()
spec = env.action_spec()

for _ in range(20):
    action = np.clip(
        np.zeros(spec.shape, dtype=spec.dtype),
        spec.minimum,
        spec.maximum,
    )
    timestep = env.step(action)
    if timestep.last():
        break
~~~

This is a zero-input interface exercise, not a walking controller. It has not
been executed by dotSuper. It does not load MaleCNS or any FlyWire brain model.

Rendering requires a compatible graphics backend. The official Colab example
expects a GPU and configures EGL; those settings are not universal instructions
for a Mac or other local system. Use the platform-specific upstream guidance.

For locomotion, use a documented policy or its training workflow. Keep the body,
environment, controller parameters and observations matched. Random or zero
actuator commands do not reproduce the paper's walking or flying behaviour.

## D. A useful experiment record

Use one fresh folder per run. A report should state:

- Question and preselected readout.
- Source, dataset version, IDs and graph-selection rule.
- Data checksums and source-code revision.
- Model equations, units and explicitly assumed parameters.
- Input, intervention, trial count and random seed handling.
- Baseline and evaluation metric.
- Observed outcome, including null or failed results.
- Why the result does or does not support a biological claim.

For closed-loop work, additionally document sensory encoding, neural update
rate, motor decoding, actuator bounds, physics update rate and feedback timing.

Keep measured data, inferred labels, editorial parameter choices and learned
parameters separately identified.

## E. Further implementations

- [Flyvis official implementation](https://github.com/TuragaLab/flyvis)
- [Flyvis tutorials](https://turagalab.github.io/flyvis/)
- [Visual-system paper](https://www.nature.com/articles/s41586-024-07939-3)
- [Fly-connectomic graph controller, arXiv preprint v3](https://arxiv.org/abs/2602.17997v3)

The preprint is a different evidence category from a peer-reviewed publication.
No source institution endorses dotSuper or this companion.

## License for original dotSuper notebook code

MIT License

Copyright (c) 2026 dotSuper

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

This license covers the original dotSuper notebook code, not the MaleCNS data,
the authors' repositories, their papers or their images.

