# MaleCNS fly simulation

A runnable neuron-level model using the actual **MaleCNS v1.0** release referenced by [Google's September 3, 2026 article](https://blog.google/innovation-and-ai/technology/research/male-fruit-fly-brain-map/). The same JavaScript simulation runs from Node and in a browser Web Worker.

## What runs

- 166,700 classified neurons, including the brain and ventral nerve cord.
- 25,582,938 directed neuron-pair connections representing 124,177,617 synapses.
- Every released connection between classified neurons, including weight-one edges. No pruning, normalization, learning, or modification of the original integer counts.
- Sparse, delayed leaky integrate-and-fire dynamics. Firing propagates along measured connections, with transmitter-dependent signs.
- A simplified 3D body with position, velocity, yaw/pitch/roll, wing-derived lift, gravity, drag and chamber collisions, with environmental and proprioceptive feedback.
- An orbitable Three.js scene with a three-dimensional fly, animated wings and six visual legs, a food dish, and a 3D trajectory.
- A reduced-order feeding/body model: motor-driven mouth extension, optional assisted swallowing, finite food, crop and gut reservoirs, digestion, energy expenditure, hunger, satiety, fatigue and variable body mass.

This is an exploratory connectome-based model, **not a validated emulation of a living fly**. The anatomy supplies connection counts, not measured physiological synaptic strengths, memories, complete receptor identities, or a learned behavior policy. Body mechanics and sensory encoding are deliberately simple. Six-leg animation visualizes movement; individual joint forces and a deformable thorax are not simulated. Raw-network odor input does not guarantee foraging. **Seek & eat** adds engineered navigation and feeding-body rules. Simulated ingestion is now implemented, but is not a validated biological feeding sequence.

## Reproduce

Requires Python 3.11+, [uv](https://docs.astral.sh/uv/), Node 22+, approximately 2 GB free disk, and roughly 10 GB peak RAM during conversion. Browser runtime is much smaller.

```sh
uv sync
uv run python scripts/download.py
uv run python scripts/prepare.py
node scripts/run.mjs 2000
node scripts/verify.mjs
node scripts/verify-food-3d.mjs
node scripts/verify-feeding.mjs
```

Downloads come directly from the [official Janelia bulk release](https://male-cns.janelia.org/download/). All three original Feather files are kept in `data/raw/` (about 1.1 GB total). Downloads validate the publisher's CRC32C checksum and retain SHA-256 hashes, source URLs, object generations, and byte lengths. The release's much larger synapse-coordinate and microscopy files are not needed for this point-neuron model.

`data/processed/manifest.json` describes the exact selection, transmitter policy, original checksums, group membership, and compressed arrays. Original reconstruction fragments and unclassified segments remain in the raw files but are excluded from simulation. The raw graph has substantially more segment-pair rows than the classified-neuron graph. Classified anchors/orphans are retained when they have a superclass annotation.

## Neural dynamics and assumptions

Let `v` be membrane potential relative to rest, and `g` a synaptic current expressed in mV. Between incoming spikes:

```text
dv/dt = (-v + g) / 20 ms
dg/dt = -g / 5 ms
g_post += released_synapse_count × transmitter_sign × 0.275 mV
```

The two linear equations are integrated analytically between discrete spike checks. Rest/reset is −52 mV, threshold −45 mV; current and voltage reset on firing and freeze during refractoriness. Parameters are inspired by [Shiu et al., Nature (2024)](https://www.nature.com/articles/s41586-024-07763-9) and their [reference implementation](https://github.com/philshiu/Drosophila_brain_model). That study used a different, female dataset; this adaptation is not a reproduction of its experiments or validation on the male CNS.

The interactive default uses a 1 ms step: the 1.8 ms delay becomes 2 ms, and the 2.2 ms refractory interval becomes 3 ms. `parameters.dtMs: 0.2` represents both intervals exactly at higher computation cost. Incoming events occur on the discrete grid. Poisson sensory stimulation is approximated by at most one event per step and respects refractoriness.

Acetylcholine is excitatory; GABA, glutamate, and histamine are modeled as inhibitory. This is a simplifying receptor-independent policy. Dopamine, octopamine, serotonin, and uncertain/missing transmitter identities have zero fast-current contribution. Their connections and counts remain present; neuromodulation is not simulated. There is no spontaneous noise in unstimulated neurons.

The Node default stimulates annotated DNg13 and DNp09 walking neurons at 60 Hz, in addition to sensory input. The browser starts with the wing experiment: DNg02 drive at 60 Hz, walking drive and odor at zero. These are artificial stimulation protocols, separately adjustable to zero, not spontaneous intent or learned navigation. Light drives otherwise spiking approximations of photoreceptors; it is not a detailed graded-potential retina.

## Wings and flight

The released graph routes DNg02 stimulation to 24 annotated DLM/DVM power motor neurons. Their smoothed firing drives a muscle activation variable; wing steering motor pools adjust stroke amplitudes. A mechanical oscillator generates wingbeats independently of the timing of individual neural spikes. Its activation threshold, 80 ms activation time, 160–220 Hz frequency range, and gain equations in `simulation/body.mjs` are chosen approximations, not fitted physiological measurements.

This distinction matters: [fly wing rhythms are generated by stretch-activated muscle mechanics](https://arxiv.org/abs/1301.5148), and [DNg02 regulates wing amplitude](https://pmc.ncbi.nlm.nih.gov/articles/PMC9206711/). [DNg02 activation alone does not normally initiate flapping in real flies](https://pmc.ncbi.nlm.nih.gov/articles/PMC10939832/). Here the model's muscle-activation rule permits flapping after motor recruitment; this is an added engineering rule, not a discovery that the connectome recreates natural flight initiation.

The displayed wing stroke runs **20 times slower** than simulated wing cycles so users can see it. The displayed Hz value is the actual modeled oscillator frequency. Pausing freezes neural and wing state.

“Allow lift-off” enables a coarse average-lift model using a 1 mg body, 5 mm² total wing area, 1.6 mm effective radius, assumed lift coefficient 1.6, gravity, and drag. Pitch and roll follow prescribed wing-output responses; the resulting tilted lift accelerates the body in three dimensions. Yaw is a simplified wing-amplitude readout. There is no rigid-body torque/inertia integration, CFD, stall model, muscle-force solver, or flight stabilization. Sustained ascent and chamber collisions are not validated flying behaviors.

The chamber has a 43 mm center-of-body radius limit and a 60 mm altitude ceiling. Walls remove outward velocity; the floor and ceiling prevent penetration. Disabling lift while airborne lets gravity land the body rather than teleporting it to the floor. Position and attitude feed the 3D view; camera movement never changes simulation state. Drag to orbit, scroll or pinch to zoom, switch between follow and overview, or reset the view. Food placement raycasts onto the floor and reserves space beside the wall.

## Food navigation: raw versus assisted

The original food interaction changed broad olfactory stimulation but supplied the same bilateral walking command regardless of the source direction. The pooled leg-motor readout produced a curved trajectory, not a calibrated navigational response. Adding a food marker never supplied a complete foraging policy. This is a limitation of the interface, sensory encoding and motor interpretation, not evidence that the released connection counts are corrupt.

**Walk** retains raw-network mode, with odor initially off and no navigation assistance. **Seek & eat** enables odor, walking drive, the feeding body and an explicit controller in `simulation/navigation.mjs`:

1. It uses the known source position and body heading to calculate target bearing. This is privileged geometric information, not an inferred biological odor-localization circuit.
2. It turns the bearing error into bounded left/right Poisson stimulation of the annotated DNa02 cells and reduces the bilateral walking command during large turns. The added groups are selected from the released annotation; no connectivity counts change.
3. The body's assisted yaw readout uses the right-minus-left DNa02 firing-rate difference, gated by actual leg-motor recruitment. Forward movement still comes from leg-motor firing. [DNa02 left/right activity has been used as a steering signal in experimental circuit models](https://www.nature.com/articles/s41586-024-07039-2); the gains and recruitment gate here are engineering assumptions, not a calibrated reproduction of that work.
4. Ground proximity within 2.5 mm of the food center activates an explicit contact-hold rule. This stops locomotion at the dish; ingestion additionally requires physical mouth contact and active mouth mechanics. Moving the food releases the hold and recomputes the command without replenishing it. Empty food or modeled satiety pauses assisted navigation.

The assistance is disabled without odor/sensory input or while airborne. **Flap wings** and **Walk** turn it off. Neural-transmission and motor-output ablations prevent assisted translation and rotation from rest. This makes the interaction usable while retaining an honest distinction between engineered navigation and unvalidated raw-connectome behavior.

## Feeding and internal body

Use **Seek & eat**, watch the **Inside the body** panel, and turn on **Body cutaway** for schematic crop/gut geometry. The proboscis has two visible linked segments controlled by a damped extension state; these are a simplified rig, not a complete joint/muscle solver. The food level falls as volume is transferred. **Refill dish** adds an explicitly logged volume; moving the dish does not refill it.

The original MaleCNS annotation identifies bilateral **MN9** extension cells and a pump readout containing **MN10, MN11D, MN11V and MN12D**. MN9 recruitment drives extension without directly stimulating these motor neurons. Proboscis positioning and swallowing are distinct motor processes ([McKellar et al., 2020](https://elifesciences.org/articles/54978)); real ingestion involves coordinated pump motor sequences ([Sui et al., 2026](https://www.nature.com/articles/s41593-026-02412-y)). The present model does not reproduce those sequences. Broad taste input recruits MN9 but the modeled pump pool is often weak.

The default **Swallowing oscillator · assisted** therefore supplies a chosen 0–7 Hz pumping envelope, gated by extension motor recruitment, mouth contact with available food, low body speed and enabled feeding muscles. Turning it off uses the measured pump-pool firing readout instead, which can produce little or no ingestion. No intake is allowed from an empty dish, at a distance, while airborne, without extension, or with feeding/motor output disconnected. Contact taste is independent of the odor switch.

`simulation/physiology.mjs` contains the explicit illustrative parameters:

| Compartment / process | Chosen model value |
| --- | --- |
| Dish / crop / gut capacity | 0.6 / 0.15 / 0.2 µL |
| Intake | 0.006 µL per modeled pump cycle |
| Crop-to-gut transfer / absorption ceiling | 0.008 / 0.006 µL per simulated second |
| Energy reserve | 0–100 abstract units, initially 35; not joules |
| Absorption yield | 900 energy units per µL processed |
| Basal / walking / wing effort costs | 0.04 units/s; 0.006 units/mm; up to 0.55 units/s |
| Satiety | Crop at least 94% full or energy at least 90; hysteretic recovery |

These rates are engineering choices for an interactive demonstration, **not fitted physiology or biological timescales**. The crop fills, passes volume into the gut, and absorption increases energy. Processed fluid leaves the modeled reservoirs; there is no water balance, detailed nutrient chemistry or excretion model. Explicit accounting preserves `dish + ingested = supplied`, `crop + gut + absorbed = ingested`, and `energy + spent = initial energy + absorbed × yield`.

Food in the crop and gut increases body mass using an assumed water-like density. Energy depletion and effort-dependent fatigue reduce leg and wing muscle capacity; rest reduces fatigue. Hunger modifies the gain of olfactory and contact-taste inputs without changing connection counts. Satiety closes the feeding actuator and pauses assisted navigation. These are explicit control rules, not recovered hormonal circuits; the network may still recruit other muscles while navigation is paused. Each layer can be disabled independently in the body panel, and exports include body state, parameters, intake, food additions and compartment histories.

Sensory feedback uses body-derived envelopes every 20 ms, not precise wing-phase-locked haltere spikes. The neural model can produce high wing-power firing and flapping during other stimuli too; physiological firing rates and behavior selectivity are not calibrated.

## Body and causality

Leg motor readout groups are the `vnc_motor` neurons with `fl`, `ml`, or `hl` subclasses, partitioned by annotated side. Smoothed mean firing rates determine two virtual drives. Their sum sets forward velocity and their difference sets turn rate. Drag and a circular wall constrain motion. These gains and the differential-drive body are engineering assumptions; they do not reproduce fly muscle biomechanics. The fly's updated pose changes antenna odor/touch input on the next frame.

`results/run.json` contains the seed, parameters, inputs, timings, spikes, and body trajectory. `results/verification.json` records reproducibility and causal interventions: no input leaves the network silent; no synaptic transmission stops motor firing and movement; sensory-only stimulation reaches motor neurons; disabling the body readout stops movement while neurons continue firing. Small analytical checks also verify current integration, sign, and delay. None of these checks establishes biological behavioral accuracy.

Wing checks additionally verify bilateral power-neuron recruitment, oscillation and lift, no flapping without synaptic transmission or motor readout, and changed neural activity when body feedback is disabled. Sensor checks cover odor distance, airborne leg-contact removal, and sensory ablation. See [the sensor interface and upgrade path](docs/SENSORS.md).

`scripts/verify-food-3d.mjs` tests multiple food directions and seeds, source relocation, sustained contact hold, assistance ablations, wall/ceiling collisions and gravity-driven landing. It also checks Three.js scene geometry, 3D wing transformations and floor raycasting without a browser or GPU. Results are in `results/food-3d-verification.json`. No browser DOM, WebGL-rendered image or physical-device visual QA is claimed.

`scripts/verify-feeding.mjs` verifies finite food and energy/volume accounting, mouth contact, crop/gut bounds, satiety, fatigue recovery, mass-dependent lift, raw versus assisted pumping, and feeding ablations. A full-network run reaches food, ingests, digests and becomes satiated. Three.js mouth coordinates are checked against the ingestion contact calculation. Evidence is in `results/feeding-verification.json`.

## Browser architecture

The lossless browser export is approximately **74.4 MB compressed**, with about **154 MB of connectivity arrays** after decompression, plus neuron state, metadata, and rendering memory. A 33 GB allocation is unnecessary for this model. Use a modern desktop browser; loading may exceed practical limits on low-memory mobile devices.

The worker loads hashed gzip chunks and executes this same engine locally. No GPU, cloud inference, or neuron-compute backend is required. UI rendering is separate from simulation time; the displayed speed reports simulated seconds per wall-clock second. It never advances the body ahead of the neurons to suggest real-time performance. Every connectivity chunk is hash-checked during loading.

```sh
node scripts/export-web.mjs
cd web
npm install
npm run dev
```

`node scripts/verify-worker.mjs http://localhost:3000` checks the actual worker code using Node's worker threads, fetch, Web Crypto, and gzip Web APIs over HTTP. It compares spike totals and altitude with the Node reference and checks reset, export, and disconnected-wing behavior. This does not exercise a browser DOM, renderer, or physical mobile device. WebMCP exposes a read-only state tool when supported; no supporting WebMCP browser validation context was available.

## Attribution

MaleCNS data: FlyEM / HHMI Janelia, University of Cambridge, MRC Laboratory of Molecular Biology, and Google Research; Berg et al. (2026). [Dataset project](https://male-cns.janelia.org/) and [CC BY 4.0 license](https://creativecommons.org/licenses/by/4.0/). The compressed export is a derived representation; the simulation assumptions are this project's additions. The sources remain separate from generated code.
