Skip to content

Latest commit

 

History

92 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

celeganssim

A whole-organism simulator for Caenorhabditis elegans.

It simulates all 300 neurons and 95 body-wall muscles over the published electron-microscopy connectome, drives a biomechanical body through a viscous medium, and runs the animal from a fertilised egg through four larval stages to senescence and death. You can poke it anywhere on its body, knock out genes by name, laser-ablate individual neurons, and run the standard behavioural assays.

Arena view: an adult worm mid-undulation, dorsal and ventral body-wall muscle activation drawn along the body in teal and violet, its recent track behind it and a scale bar

Teal is dorsal muscle, purple is ventral. The alternation running down the body is the undulatory wave that moves the animal.


Install and run

git clone https://github.com/vdmkenny/celeganssim && cd celeganssim
python -m venv .venv && .venv/bin/pip install -e .
.venv/bin/python scripts/fetch_data.py     # downloads ~43 MB, then builds
.venv/bin/worm serve                       # http://127.0.0.1:8080

Requires Python 3.10+ and numpy. The viewer is standard library and vanilla JavaScript, with no build step. Datasets are not redistributed here: fetch_data.py pulls each from its publisher, verifies it, and builds the processed files.

The connectome is Cook et al.'s corrected July 2020 release, published as an Excel workbook and read by scripts/xlsx.py, a standard-library reader added so the project keeps its numpy-only dependency. The 2019 edgelist and the White et al. 1986 file are downloaded for comparison and are not used to build anything.

worm serve            # live browser viewer
worm validate         # 52 checks against published measurements, in parallel
worm params           # audit every model parameter and its provenance
worm assay all        # run the standard behavioural assays
worm gene unc-25      # look up a locus
worm info             # genome and connectome summary
worm export run.csv --seconds 120 --neuron AVAL
worm batch --genotype wild-type --genotype unc-25 --replicates 5

What it does

Mechanosensation

Touch is a position along the body. The six touch receptor neurons tile the animal with overlapping graded receptive fields, so where you prod it determines which cells respond. Anterior touch drives reversal, posterior touch drives forward acceleration, and mid-body touch falls where the ALM and PLM fields cross over and is unreliable. These follow from the connectome rather than from rules: PLM has no chemical output at all, reaching the forward command interneuron PVC purely through gap junctions.

Mechanotransduction is phasic, as measured: the receptor current fires at stimulus onset and offset and adapts within tens of milliseconds, so the neurons report change rather than load (O'Hagan et al. 2005). Repeated plate taps habituate: synaptic depression at the touch cells' output synapses (Wicks & Rankin 1997) halves the evoked response over twelve taps and rest restores it (Rankin et al. 1990). The decrement lives in the difference of the two antagonistic tap reflexes (Wicks & Rankin 1995), which is why a localised poke habituates far less than a whole-body tap. The suprathreshold binary response does not habituate here and deeper depression sensitises it through PLM disinhibition, a wiring-level limit tracked as an expected failure.

Harsh touch (100-200 uN) is a separate channel. FLP covers the head and is reversal-biased in the wiring; PVD tiles the rest of the body and favours forward. Both are MEC-4 independent, so harsh responses survive in mec-4 mutants.

Exploration and chemotaxis

Left alone, the animal reverses on its own: a generator injects pulses into the real backward command cells at the measured rates (about 2 per minute off food, fewer on food, Gray et al. 2005; goa-1 roughly triples it, Segalat et al. 1995). Chemotaxis is a biased random walk on top of that machinery: the pirouette rate is multiplied down when the animal climbs a salt gradient and up when it descends, with the measured 3x asymmetry (Pierce-Shimomura et al. 1999) and an ASE-style seconds-scale integration of dC/dt, gated by the real ASE genome gains so che-1 and tax-4 silence it by mechanism. Honest accounting. An earlier chemotaxis-index pass turned out to be an arena artifact: on a small toroidal plate the scoring band covered 30% of the surface, so a salt-blind animal scored 0.6-0.7 by wrapping through it. The assay now uses Ward's geometry instead, an attractant spot and a control spot with the animals released between them, where an animal that cannot smell scores zero by symmetry rather than by the arena being the right size.

Both halves of the mechanism are now present. Klinokinesis modulates the pirouette rate, and klinotaxis curves the forward runs: measured as the rate at which heading error to the source falls during a run, it goes from -0.02 deg/s with the steering off to -0.65 deg/s with it on, a clean dose response. Together they are enough to move a plate: released midway between an attractant and a control spot, wild type finishes on the attractant side with an index of +0.50 while che-1, which cannot taste salt, ends up at -0.83, the wrong side of a plate it cannot navigate. The plate has no handedness of its own: omega turns here are always ventral, so each animal is given a side to lie on the way a worm on agar is, and a population averages the turn direction out. Without that, every animal curled the same way and accumulated 371 degrees of rotation in ten minutes, which an assay reads as behaviour. A steady gait curl remains, unrelated to orientation, tracked as issue #34.

The search itself has a history: dopamine carries the memory of food. In the minutes after leaving a lawn the reversal rate runs at the local-search value, then decays to a low dispersal rate over tens of minutes (Gray et al. 2005), and cat-2, which cannot make dopamine, never elevates above dispersal while its baseline stays intact (Hills et al. 2004).

A reversal ends in an omega turn with a probability that rises with how far the animal backed up, read from Gray et al.'s measured curve: rare after a single backward bend, near-certain after four. Stronger stimuli hold the reversal longer through the command balance itself, so harsh touch earns both a longer retreat and a sharper turn without either being scripted to. Escape vigor is latched at reversal onset from the command excess, the published AVA-transient relationship; the omega turn coils the anterior body and reorients it by about 133 degrees, the measured figure. The turn comes from a travelling wave running along a gently curved body rather than from a deep static bend: bending harder saturates the muscle targets, kills the wave and the thrust with it, and the animal spins in place.

Modulation

Monoamines do not travel down the wired connectome. A cell that makes dopamine releases it into the tissue and every cell carrying a cognate receptor responds, synaptic partner or not, so they are a second layer: 2,626 ligand-receptor edges of which only 6% are also chemical synapses (Bentley et al. 2016). Each receptor carries the sign of its measured coupling, so DOP-3 (Gi) inhibits where DOP-1 (Gq) excites on the same cell, and the ligand-gated chloride channels inhibit directly.

Basal slowing falls out of it. Food contact excites the eight dopaminergic cells, dopamine reaches the cholinergic motor neurons through DOP-3, and the animal slows 13.9% on encountering a lawn, inside the measured band. It is mechanism rather than a formula, and the knockouts say so: cat-2 slows 0.1% because it makes no dopamine, tph-1 slows 16.1% because serotonin is not what carries this response, and dop-1 slows more than wild type because removing the excitatory receptor leaves DOP-3 unopposed. Receptor genes are therefore experimental tools here, not inert annotations.

The layer is deliberately quiet at rest. Release is measured as a deviation from the animal's own slow baseline, so an undisturbed animal receives no net modulation and the resting operating point every other constant is calibrated against does not move.

Genetics

Thirty-one loci are mapped onto the subsystems their products implement. Knockouts reach only the cells that CeNGEN single-cell RNA-seq measures the gene in:

Gene Expressed in Effect
mec-4 the six touch receptor neurons gentle touch abolished, harsh touch intact
unc-25 28 cells: DD, VD, RME, AVL, DVB, RIS, RIB GABA lost, animal hypercontracts
che-1 ASEL, ASER salt sensing lost, odour intact
cat-2 the eight dopaminergic neurons no dopamine: basal slowing and area-restricted search both lost
daf-2 158 cells lifespan roughly doubles, requires daf-16

worm gene <name> resolves any of the 46,926 annotated loci to its WormBase ID, chromosome and coordinates.

Neuron ablation

Alt-click any cell in the network view to kill it: it stops sending and receiving, and the surviving network's resting state is re-solved around the loss.

Ablation Result
AVB + PVC forward drive falls to 0.00, reversals intact
AVA + AVD + AVE touch-evoked reversal abolished
ALM + AVM anterior touch sensitivity lost

Network view

Network view with AVAL pinned, showing all 106 of its connections highlighted while the rest of the graph dims. Link colour is the synapse sign derived per edge from postsynaptic receptor expression: teal excitatory, orange inhibitory, grey gap junction

All 448 cells laid out sensory to interneuron to motor to muscle, ordered to minimise edge crossings, with node brightness tracking live drive. Hover any cell for its transmitter, current drive and strongest partners with weights. Pin it, or watch it in the trace panel to see its activation over the last 30 seconds.

Life cycle

Runs from fertilised egg to death on measured timings: 14.2 h of embryogenesis with milestones, 50.7 h from hatch to adult across four larval stages, dauer entry under crowding and scarcity, a sperm-limited brood of ~300 over ~5 days, then senescence and death at a lifespan that scales with temperature and genotype.

Assays

Each reports the metric its original paper reports and carries that paper's reference value.

Assay Measures
chemotaxis chemotaxis index on a salt gradient
thermotaxis drift relative to remembered cultivation temperature
touch-habituation response decrement over repeated taps
basal-slowing speed drop on encountering food
touch-response reversal probability by body position
lifespan egg to death, with brood size and reproductive period

Data export

CSV or JSON of trajectory, behavioural state, developmental stage and named neuron activations, with fixed seeds. worm batch compares genotypes across replicates.


How it works

Environment      gradients, bacterial lawn, temperature, oxygen, touch
      |
SensorySystem    modality -> named neurons, via receptive fields, gated by genes
      |
NervousSystem    448 cells, graded-potential ODEs over the real connectome
      |
Simulation       reads command interneurons -> behavioural state machine
      |
Muscle pacer     the scripted wave current -> 95 REAL muscle cells
      |
Body             muscle calcium -> force -> viscoelastic body
      |
                 resistive force theory -> movement -> back to Environment

C. elegans neurons do not spike; they are isopotential, graded-release cells. The model is the standard leaky-integrator formulation of Wicks et al. (1996) and Kunert et al. (2014):

C dV_i/dt = -G_leak(V_i - E_leak,i) - I_gap_i - I_syn_i + I_ext_i
I_gap_i   = sum_j g_gap * Gg[i,j] * (V_i - V_j)
I_syn_i   = sum_j g_syn * Gs[i,j] * s_j * (V_i - E_ij)
ds_j/dt   = a_r * phi(V_j) * (1 - s_j) - a_d * s_j

Integration is exponential Euler, unconditionally stable, at roughly 4x real time on a laptop. The per-cell activation threshold is solved as a linear system so the resting network sits at its own equilibrium. Passive properties follow patch clamp: a 0.25 nS leak for a 4 GOhm input resistance, and 3 pS per gap-junction contact, since measured coupling is reported whole-cell across all contacts a pair shares. Leak reversals are solved so the network equilibrium lands on measured resting potentials.

The 95 body-wall muscles are cells in the same network and carry their own measured passive properties: they rest at -25 mV against a neuron's -65 mV, have a capacitance of 70 pF against 1.5 pF, and a membrane time constant of 70 ms against 6 ms. The depolarised rest reflects a high chloride permeability rather than a potassium equilibrium.

Muscle force follows calcium rather than membrane potential, so each muscle carries a calcium stage: two first-order filters whose combined impulse response is the measured transient, rising with a 250 ms and decaying with an 880 ms time constant and peaking 0.44 s after excitation. Contractile calcium in this animal comes from sarcoplasmic release through the ryanodine receptor UNC-68 gated by EGL-19. Calcium here is normalised drive, not a concentration: no C. elegans muscle calcium measurement has ever been calibrated to nM or uM.

At the neuromuscular junction, acetylcholine acts on a non-selective cation channel reversing near 0 mV and GABA on the chloride-permeant UNC-49 receptor reversing near -30 mV, so against a -25 mV resting potential GABA contributes 5 mV of hyperpolarising drive and acts largely by shunting. The per-contact neuromuscular conductance is calibrated so that a muscle's achievable whole-cell cholinergic conductance matches the 8.5 nS measured by patch clamp. Achievable rather than nominal matters here: the synaptic release variable cannot exceed a_r/(a_r + a_d), so a synapse delivers at most a sixth of its per-contact conductance and spans only 1.83x from rest to saturation.

Muscle fires all-or-none calcium action potentials, and those spikes are what drive contraction. The inward conductance is measured twice over: Jospin's peak EGL-19 density of 199 S/F at 70 pF gives 13.9 nS, and the measured maximum upstroke rate of 1.38 V/s across 70 pF needs 9.2 nS against the 8.9 nS the steady-state density gives. Inactivation is partial, and its residual is measured too, the maintained component being 127 S/F of the 199 S/F peak. The repolarising side is fitted, since neither SHK-1 nor SLO-2 has a published body-wall muscle current-voltage relation; it is fitted to the measured waveform, reproducing a 45.6 mV spike of 18.7 ms half-width against a measured 45 to 53 mV and 15.5 to 20 ms.

Module Role
worm/genome.py annotation, gene lookup, knockouts, expression
worm/connectome.py wiring to conductance matrices, network layout
worm/nervous_system.py graded-potential dynamics, ablation
worm/sensory.py environment to current, mechanosensory receptive fields
worm/modulation.py slow monoamine layer: volume transmission by receptor
worm/body.py oscillator, muscle to curvature, low-Reynolds locomotion
worm/kinematics.py gait measurement: frequency, wavelength, wave direction
worm/lifecycle.py embryo, larval stages, dauer, feeding, ageing, death
worm/simulation.py closed loop, escape-response state machine
worm/assays.py standard assays with reference values
worm/validate.py 52 checks: 34 behavioural, 18 consistency, gaps as expected failures
worm/parameters.py audited parameter registry, provenance tags enforced by a check
worm/server.py, viewer/ live browser viewer

Data

Dataset Source Contents
Genome annotation NCBI RefSeq GCF_000002985.6 (WBcel235) 46,926 genes, 19,983 protein-coding
Connectome Cook et al., corrected July 2020 release, via OpenWorm ConnectomeToolbox 473 cells, 7,762 edges (302 neurons, 95 body-wall muscles)
Developmental connectomes Witvliet et al. 2021, via OpenWorm ConnectomeToolbox 8 reconstructions, L1 to adult, 858 to 2,496 edges (data only, issue #27)
Neuron metadata OpenWorm owmeta type and transmitter for 302 neurons
Expression CeNGEN via wormneuroatlas 130 genes cached per neuron class: knockout loci, ligand-gated receptors, and 35 ion channels
Cell classification WormAtlas lineage and anatomical class
Receptor pharmacology derived from RefSeq product descriptions 72 ligand-gated receptors with ion selectivity
Monoamine connectome Bentley et al. 2016, via OpenWorm ConnectomeToolbox 2,626 extrasynaptic edges naming ligand and receptor
Neuropeptide connectome Bentley et al. 2016, via OpenWorm ConnectomeToolbox 8,931 extrasynaptic edges, 15 ligands, 12 receptors (data only, issue #13)
Functional atlas Randi et al. 2023, bundled with wormneuroatlas measured signal propagation between 300 neurons, used to bound what the wiring predicts (docs/citations.md)

Sources are audited for peer review and corrections by scripts/audit_citations.py, with the findings in docs/citations.md.

The datasets disagree in specific ways, each handled in code where it arises: gap junctions are listed in both directions, so the matrix is filled directly rather than symmetrised; cell naming differs between sources and is normalised; owmeta leaves 57 neurons unannotated, which come from the systematic transmitter atlases; and cells that stain GABA-positive but lack unc-25 take GABA up rather than making it, so are not modelled as GABAergic.


Validation

CLAIMS.md maps every claim here to the mechanism producing it, tagged measured, published, tuned or scripted, so the difference between what the model knows and what it assumes stays visible.

worm validate runs 52 checks against published measurements: 34 behavioural (the animal is run and measured) and 18 consistency checks (parameter and data invariants). 41 pass. Ten are registered expected failures, each naming the gap it tracks. The connectome does not generate the locomotor rhythm, so real muscle drive carries no undulation, and the fixed-frequency oscillator cannot adapt gait to the medium (issue #10). The animal reverses spontaneously at the measured rates, searches locally after leaving food and turns with real 133-degree omega turns, but it does not yet chemotax: on honest plate geometry the biased walk cannot out-drift a salt-blind animal, which is an expected failure owned by issue #20. goa-1 also still loses to its constant reversing the speed its deeper, faster bends would otherwise gain, an oscillator-depth gap owned by issue #10. Muscle activation also leads curvature by 8 degrees where the animal holds about 45.

Check Model Published
Input resistance 4.0 GOhm 1.6 to 8 GOhm
Membrane time constant 6.0 ms 3 to 10 ms
AVAL-AVAR gap coupling 54 pS 56 pS
VA5 / VB6 resting potential -71.7 / -53.2 mV -71.7 / -53.2 mV
Crawling speed 0.204 mm/s 0.20 +/- 0.04 mm/s
Undulation amplitude 17.9% body length 19.3%
Undulation frequency 0.468 Hz 0.47 Hz commanded, recovered from the body
Omega turn reorientation 133 degrees about 140
Spontaneous reversals off food 2.3 /min ~2 /min, on food lower, goa-1 higher
Basal slowing on food 13.9% (cat-2 0.1%, tph-1 16.1%) slowing present, abolished without dopamine
Chemotaxis index, salt +0.50 (che-1 -0.83) positive for wild type, absent without ASE
Local search vs dispersal 1.8 vs 0.8 /min, cat-2 stays at 0.4 several-fold decay over ~30 min, dopamine-dependent
Embryogenesis 14.2 h 14.2 h
Hatch to adult 50.8 h 50.67 +/- 1.95 h
Adult lifespan mean 15.9 d, sd 3.3 d over a cohort 15.2 +/- 3.6 d
Self-fertile brood 300 ~327, sperm-limited
daf-2 lifespan 31.3 d (2x the animal's own draw) ~29.5 d

The other behavioural checks cover touch responses by body position, the mec-4/mec-10 dissociation, the unc-25/unc-47/unc-49 shrinker class, unc-13 paralysis, the opposing goa-1 and egl-30 phenotypes, tdc-1 omega-turn loss, and command-interneuron ablation. The consistency checks pin the daf-16 epistasis, che-1 modality gating, developmental timings, and the sperm-limited brood.

Every parameter the model is told is collected in one audited registry (worm params), tagged measured, published, tuned or scripted; the scripted tags are the ones the open issues exist to delete.

Independently, the 26 GABAergic neurons the pipeline derives from transmitter data match the known count exactly (6 DD + 13 VD + 4 RME + AVL + DVB + RIS).


Scope and limitations

Measured data: connectivity and synapse counts, transmitter identity, gene expression, receptive field extents, passive membrane properties, resting potentials, developmental timings, body sizes, brood size, lifespan.

Standard published models: graded-potential dynamics (Wicks 1996 / Kunert 2014), resistive force theory for low-Reynolds locomotion.

Approximations:

  • The locomotor rhythm is imposed, not emergent, and it is imposed at the end organ. No published model produces this rhythm from the connectome and no ventral cord motor neuron has ever been recorded during locomotion, so one scripted current carries the wave: per-muscle currents into the 95 real muscle cells, at the measured frequency and wavelength (Cronin et al. 2005), switching direction with the command state as B- and A-class activity does (Haspel et al. 2010; Kawano et al. 2011). Everything downstream is real: muscle calcium with measured kinetics, force, mechanics, so ablating muscle bends the animal and GABA loss produces the shrinker through genuine co-contraction (McIntire et al. 1993). Imposing the rhythm one level higher, as currents into the motor neurons, was built and measured out: the current leaks into the command interneurons through their measured gap junctions and destroys touch discrimination, with mec-4 reading as wild type on every detector tried. Imposing it one level lower, as prescribed body curvature, leaves the muscles decorative. The end organ is the smallest scripted surface that keeps every assay readable, and docs/emergent-cpg.md records the attempts to shrink it further.
  • Enhanced slowing is still a scalar. The serotonergic response of a food-deprived animal needs serotonin release to depend on feeding history, which the monoamine layer does not model yet, so it stays a labelled formula. Basal slowing no longer is: it was a scalar until the monoamine layer gave it a pathway (issue #11).
  • The peptidergic layer is fetched but not built. Bentley's 8,931 neuropeptide edges are pinned alongside the monoamine ones and unused; that is the second half of issue #13.
  • Initiative is generated, not emergent. Spontaneous reversals come from a Poisson generator at the measured rates injected into the real backward command cells, and klinokinesis scales that rate with the measured asymmetry as a stand-in for the ASE-to-command loop the graded network cannot yet close (issue #7). Both are labelled scripted. The decision machinery they feed is real, which is why che-1, tax-4 and goa-1 move these behaviours by mechanism.
  • Muscle spikes are not reached from synaptic input. Muscle carries the measured calcium action potential, but crossing its -10 mV threshold needs about 2.4 nS of extra excitatory conductance, close to the 2.26 nS implied by the measured 67.9 pA trigger current, and one junction spans only 1.83x from rest to saturation. Propagation along the body is therefore still subthreshold and graded rather than spike-mediated, which is why an imposed bend propagates at slope 0.364 rather than the measured 0.62. docs/emergent-cpg.md sets out what an emergent version requires. No published model produces C. elegans locomotion emergently from the connectome.
  • Synapse signs are derived per edge from the postsynaptic cell's measured receptor expression (CeNGEN): which ligand-gated channels a cell transcribes, and whether those are cation or anion channels, sets each synapse's sign. The receptor table itself is derived from the RefSeq product descriptions (scripts/build_receptors.py). Where expression cannot decide (metabotropic transmitters, cells outside CeNGEN, ties), a transmitter-level heuristic is the tagged fallback. A small table of documented exceptions overrides both where behaviour settles a sign that expression cannot: PLM onto the backward command interneurons is inhibitory, since tail touch drives forward escape and PLM ablation abolishes it, and acetylcholine gates chloride through the ACC and LGC families that CeNGEN does not resolve in those cells. Overrides are counted separately in the sign provenance.
  • The genome sequence is not load-bearing. The annotation drives gene lookup and knockouts, but the 100 Mb of sequence yields chromosome lengths and GC content. Mapping a gene to what its loss does is a curated table.
  • Escape is a state machine. Reversal and omega turn have separable motor pathways; the network decides when each fires.
  • The 24-segment body is a coarse-graining. The animal has 95 body-wall muscles in quadrants of 24/24/24/23, staggered into eight longitudinal rows rather than transverse rings, which Hall notes amounts to roughly twelve segments. Muscle index is mapped proportionally onto segments, preserving anterior-posterior order without claiming a ring. The 4x24 grid some simulators use is an idealisation, not anatomy.
  • Innervation is treated as uniform along the body, and is not. The anterior 16 muscles receive nerve-ring input only, the next 16 receive both ring and cord, and only the posterior 63 are on the cord alone (White et al. 1986). The head is a separate oscillator in the animal, and muscle arms reach only the nearest cord, which is the structural reason the body is restricted to dorsoventral waves.
  • The posterior body is the reconstruction's thinnest region, and it is where the wave has to travel. Muscles in body rows 17 to 24 average 6.3 presynaptic partners against about 10 published, while head and neck sit at 10.0 and 12.8, and sublateral input to posterior muscle is absent entirely. Cook et al. report a remaining gap "in a region of the posterior body where there are no high-power EM series from either sex", and state that gaps leaving cells without innervation are "unquestionably artefactual". A wiring-derived model cannot propagate a wave through a region the wiring is missing from, so part of the locomotion gap is a limit of the available data rather than of the model.
  • About 29% of neuromuscular input in the dataset was never EM-reconstructed. The sublateral motor neurons (SMB, SMD, SIA, SIB) were recorded by immunofluorescence and sampling rather than serial section, and White et al. reported almost no synapses on those processes. Muscle-muscle gap junctions are similarly incomplete, carrying almost no left-right coupling where White describes it through the muscle arms.
  • Not modelled: pharynx, gonad, intestine, embryonic lineage, hydrodynamics beyond RFT. One animal, so crowding is a scalar.

References

Connectome

Neural dynamics and electrophysiology

Transmitters and expression

Locomotion

Musculature and the neuromuscular junction

Mechanosensation and escape

Chemosensation and navigation

Genetics and phenotypes

Life cycle and ageing

Reference resources


Licence

MIT, code only. No datasets are redistributed; fetch_data.py pulls each from its publisher and they remain under their own terms. If you use this for research, cite the primary sources above rather than this repository.

About

Whole-organism C. elegans simulator built on the real WBcel235 genome and the Cook et al. 2019 connectome (2020 updated version) — 302 neurons, 95 muscles, gene knockouts, live browser viewer

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages