elegans 1.0.0

C. elegans nervous system — 302 undifferentiated neurons develop into a functional worm brain through imaginal disc developmental phases
Documentation
# Elegans


**302 undifferentiated neurons develop into a functional C. elegans nervous system with zero hardcoded structure.**

Neurons don't get assigned roles — they *become* sensory, motor, or interneuron through developmental phases driven by body interaction. The worm starts as a blank pool of diverse neurons and, through genomic seeding, imaginal disc developmental programs, proximity wiring, and mastery learning, self-organizes into an organism that moves, senses chemical gradients, and navigates toward food.

![Elegans Visualizer](recording_001/frame_000010.png)

*Brain point cloud (302 neurons) floating above the 10-segment worm body. Green = sensory, red = motor, blue = interneuron. Bright/enlarged = recently fired.*

## Architecture


```
┌─────────────────────────────────────────────────────┐
│                    WormSim                           │
│                                                     │
│  ┌──────────┐   CouplingState    ┌──────────────┐   │
│  │ WormBody │◄──(fiber tracts)──►│ SpatialBrain │   │
│  │          │   65 sensory ch    │ (neuropool)  │   │
│  │ 10 segs  │   40 motor ch     │ 302 neurons  │   │
│  │ 4 muscles│                   │ ~2400 syn    │   │
│  │ chemosns │                   │              │   │
│  │ touch    │                   │ ┌──────────┐ │   │
│  │ proprio  │                   │ │ Cascade  │ │   │
│  │ metabol. │                   │ │ Tissue   │ │   │
│  └──────────┘                   │ │ Mastery  │ │   │
│                                 │ │ Migration│ │   │
│  ┌──────────────┐               │ │ Pruning  │ │   │
│  │ PhaseControl │               │ └──────────┘ │   │
│  │ Gen→Exp→Dif→ │               └──────────────┘   │
│  │ Crystallize  │                                   │
│  └──────────────┘               ┌──────────────┐   │
│                                 │ Imaginal     │   │
│                                 │ Discs (110)  │   │
│                                 └──────────────┘   │
└─────────────────────────────────────────────────────┘
```

### Modules


| Module | Role |
|--------|------|
| **body** | 3D worm body — 10 segments, 4 muscles each, spring-coupled chain with gravity, chemosensory, touch, proprioception, and metabolism |
| **coupling** | Fiber tracts bridging body and brain — spatial proximity assignment, no static wiring. 65 sensory + 40 motor channels |
| **disc** | 110 imaginal disc programs — latent developmental rules that transform undifferentiated neurons into typed roles |
| **phase** | Developmental phase controller — Genesis, Exposure, Differentiation, Crystallization |
| **sim** | Coupled simulation — tick loop orchestrating sense → inject → cascade → read → actuate → physics → plasticity → development |

## How It Works


### Genomic Seeding


All 302 neurons start undifferentiated — no sensory interface, no motor interface. But they're not identical. Genomic seeding creates a diverse initial population:

| Type | Ratio | Role |
|------|-------|------|
| Excitatory pyramidal | ~40% | Computational substrate |
| Inhibitory interneuron | ~25% | E/I balance from genesis |
| Relay | ~15% | Fast signal conduits |
| Gate | ~10% | Coincidence detectors |
| Oscillator | ~5% | Locomotion CPG seeds |
| Modulator | ~5% | Plasticity control |

Neurons are spatially distributed matching the real C. elegans body plan — head-biased density (nerve ring analog), moderate body, sparse tail. All nuclei properties (leak, metabolic rate, axon affinity, etc.) receive ±15% jitter for individual variation.

### Developmental Phases


Development proceeds through four phases (4500 frames total at 10ms/frame = 45 seconds of worm-time):

#### 1. Genesis (500 frames)

High plasticity (1.5x), high migration (2.0x). Neurons explore the space, form initial synaptic connections through proximity wiring, and begin to establish activity patterns. No disc pressure yet — the network self-organizes purely through spike dynamics.

#### 2. Exposure (2000 frames)

Normal plasticity, normal migration. The worm body is active — muscles fire, chemosensory detects the food gradient, touch sensors feel the ground. Imaginal discs begin accumulating spatial and activity-correlated pressure. Neurons near the head that respond to sensory input build disc commitment toward chemosensory roles. Neurons near muscles build motor commitment.

During exposure, the worm typically approaches the food source (distance 20 → ~3-4).

#### 3. Differentiation (1000 frames)

Gradual transformation: 5 neurons per round (spread across ~40 rounds to minimize disruption). Neurons that accumulated enough disc pressure are irreversibly transformed — their nuclei are rewritten to match the disc's target role:

- **Sensory neurons** get high leak (200) — fast membrane decay makes them input-driven transducers, not network-driven oscillators
- **Motor neurons** get moderate leak (70) — persistent activation for sustained muscle drive
- Coupling caches rebuild as neurons gain sensory/motor interfaces

Population caps prevent over-differentiation: max 30% sensory, 40% motor.

Valence gating is suspended during differentiation — energy changes reflect feeding momentum, not behavioral quality.

#### 4. Crystallization (1000 frames)

Structure freezes. Plasticity drops to 0.2x, migration nearly stops (0.1x). The circuit that emerged through development is preserved. Only minor synaptic tuning continues.

### 110 Imaginal Disc Programs


Discs are latent developmental rules — they don't execute until differentiation phase, but they accumulate evidence during exposure:

| Disc Type | Count | Placement | Purpose |
|-----------|-------|-----------|---------|
| Chemosensory | 4 | Head | Gradient detection (left, right, dorsal, concentration) |
| Touch | 40 | Per-segment (4 dirs) | Mechanoreception |
| Proprioceptive | 20 | Per-segment (2 axes) | Bend sensing |
| Motor | 40 | Per-segment (4 dirs) | Muscle control |
| Command interneuron | 4 | Nerve ring | Hub coordination |
| Oscillator | 2 | Anterior/posterior | Locomotion CPG |

Each disc has spatial influence (position + radius) and activity-correlation criteria. Neurons accumulate pressure from both proximity and correlated firing patterns. When a neuron crosses the disc's threshold during differentiation, it transforms.

### Coupling: Brain-Body Interface


The coupling system uses **fiber tracts** (from `fibertract-rs`) to bridge the body and brain:

- **Head bundle**: 4 chemosensory channels + 1 metabolic distress channel
- **10 segment bundles**: 4 touch + 2 proprioceptive + 4 motor channels each
- **Commissure**: 20 cross-lateral synapse pairs at the head (magnitude 40) — nerve ring analog enabling left↔right signaling for steering

Channel assignment is spatial — neurons near a segment's position get coupled to that segment's channels. Before differentiation, any nearby neuron can serve; after differentiation, typed neurons are preferred.

Head channels use **labeled-line identity** — a neuron's lateral position (left/right of midline) determines which chemosensory channel it reads. This emerges from spatial coupling, not hardcoded assignment.

Sensory injection scale: 3.0x (raw body values → neural current).

### Valence-Gated Consolidation


Energy changes modulate the mastery learning budget through EMA-smoothed valence:

- **Energy improving** (EMA delta > 0.00005): Budget × 2.0 — consolidate current patterns
- **Energy worsening** (EMA delta < -0.00005): Budget × 0.5 — loosen, allow exploration
- **Neutral**: Budget × 1.0

EMA smoothing (alpha=0.1, ~10-frame window) prevents noise from single-tick energy fluctuations. Raw per-tick deltas (~0.0004) are too small for threshold detection without smoothing.

Valence is **suspended during differentiation** — the circuit is under reconstruction and energy changes reflect feeding momentum, not behavioral quality.

### Phase-Gated Plasticity


The developmental phase multiplies into the mastery budget:

| Phase | Plasticity | Migration | Effect |
|-------|-----------|-----------|--------|
| Genesis | 1.5x | 2.0x | Rapid self-organization |
| Exposure | 1.0x | 1.0x | Normal learning from experience |
| Differentiation | 1.2x | 0.5x | Elevated plasticity during rewiring |
| Crystallization | 0.2x | 0.1x | Structure freeze |

## The Worm Body


A 3D chain of 10 spring-coupled segments:

- **4 muscles per segment**: dorsal, ventral, left, right
- **Spring coupling**: k=0.5, maintains segment spacing
- **Gravity**: 0.02/tick downward, ground plane at z=0
- **Propulsion**: 0.08 force per tick from muscle activation
- **Angular damping**: 0.85 (realistic inertia)

### Sensory Systems


| System | Channels | Description |
|--------|----------|-------------|
| Chemosensory | 4 | Left gradient, right gradient, dorsal gradient, approach strength |
| Metabolic | 1 | Distress signal (0 = fine, 1000 = starving) |
| Touch | 40 | 4 directions × 10 segments (dorsal, ventral, left, right) |
| Proprioception | 20 | 2 axes × 10 segments (dorsal-ventral bend, left-right bend) |

### Metabolism


Energy drains from existing (basal rate 0.0002/tick) and moving (0.000005 × activation/tick). Feeding restores energy proportional to food proximity (0.0008 × concentration/tick). Distress = 1.0 - energy, reaches the brain through the interoceptive tract.

## Causal Pathway


The probe test confirms **sensory→motor causation** emerges through development:

1. Develop the worm through all phases
2. Place food to the LEFT of the worm, run 500 ticks, measure motor asymmetry
3. Place food to the RIGHT, run 500 ticks, measure motor asymmetry
4. If asymmetry flips sign → sensory input is causally driving motor output

Result: asymmetry flips from **-79.58** (food left) to **+144.18** (food right). The worm's motor output is driven by its chemosensory input, not by spontaneous network oscillation. This pathway was not hardcoded — it emerged through development.

The key breakthrough: **high-leak sensory neurons** (disc target leak=200). Fast membrane decay means sensory neurons are input-driven — their firing reflects external stimulus, not recurrent network activity.

## 3D Visualizer


Real-time visualization using macroquad.

```bash
cargo run --example visualize --features visualize
```

### What You See


- **Worm body**: 10 colored spheres (blue = resting, red = active), connected by lines, yellow heading indicator on head
- **Food source**: Pulsing green sphere
- **Brain point cloud**: 302 neurons floating above the worm — green = sensory, red = motor, blue = interneuron. Recently-fired neurons brighten and enlarge
- **Brain bounding box**: Wireframe outline around the neuron volume
- **Ground grid**: Follows worm center of mass
- **HUD**: Phase, frame count, role counts, food distance, energy, distress, spike count, speed

### Controls


| Key | Action |
|-----|--------|
| Space | Pause / resume |
| Up / Down | Speed 1x → 64x |
| Left drag | Pan camera |
| Right drag | Orbit camera |
| Scroll | Zoom (smooth) |
| R | Reset camera |
| F | Toggle follow mode |
| V | Start / stop recording (PNG frames) |
| P | Save screenshot |

### Recording


Press **V** to start recording. Each frame is saved as a numbered PNG in `recording_NNN/`. Press **V** again to stop. Stitch into video with:

```bash
ffmpeg -framerate 30 -i recording_001/frame_%06d.png -c:v libx264 -pix_fmt yuv420p elegans.mp4
```

## Development Trajectory


Typical development report:

```
Frame  181/1800: Genesis          food_dist=16.3  energy=0.509
Frame  541/1800: Exposure         food_dist=13.0  energy=0.539
Frame  901/1800: Exposure         food_dist= 9.6  energy=0.570
Frame 1081/1800: Differentiation  food_dist= 4.2  energy=0.614
Frame 1261/1800: Differentiation  food_dist= 6.2  energy=0.667
Frame 1441/1800: Differentiation  food_dist= 8.4  energy=0.708
Frame 1621/1800: Crystallization  food_dist=10.5  energy=0.738
End:              Crystallization  food_dist=12.7  energy=0.761
```

The worm approaches food during exposure (20 → 4.2), shows moderate regression during differentiation (circuit reconstruction), then stabilizes during crystallization.

## Test Suite


53 tests covering all subsystems:

```bash
cargo test
```

| Area | Tests | Coverage |
|------|-------|----------|
| Body physics | 17 | Segments, muscles, springs, gravity, touch, chemosensory, metabolism |
| Coupling | 5 | Tract assignment, sensory mapping, motor reading |
| Discs | 6 | Spatial pressure, activity correlation, differentiation, irreversibility |
| Phases | 3 | Progression, multipliers, timing |
| Simulation | 6 | Creation, ticking, diagnostics, wiring, genomic diversity |
| Integration | 16 | Full development, chemotaxis, locomotion, touch withdrawal, causal probe |

## Dependencies


| Crate | Role |
|-------|------|
| **neuropool** | Spatial neuron point cloud, cascade execution, mastery learning, tissue physics, migration, pruning |
| **fibertract** | Long-range axon bundles, Weber adaptation, tract sensitization/myelination |
| **macroquad** | 3D visualization (optional, behind `visualize` feature) |
| **image** | PNG screenshot export (optional, behind `visualize` feature) |

## What Makes This Different


This is not a neural network. There are no weights, no layers, no backpropagation, no loss function.

- **Neurons are spatial**: They have 3D positions, somas, dendrites, and axons. They migrate through space based on activity correlations.
- **Signals are ternary**: Excitatory (+), inhibitory (-), or silent (0). Integer substrates, not floats.
- **Learning is mastery-based**: Discrete ternary pressure transitions gated by participation and neuromodulation. Not gradient descent.
- **Structure emerges**: Regions form from spatial clustering. Roles form from developmental pressure. Connectivity forms from proximity. Nothing is predefined.
- **Development is irreversible**: Once a neuron differentiates into a sensory or motor role, it cannot go back. Like real biology.

The 302-neuron C. elegans is the proof-of-concept that this paradigm works. The same developmental machinery — genomic seeding, imaginal discs, proximity wiring, mastery learning — scales to larger neuropools.

## License


MIT OR Apache-2.0