Connectome degree-preserving rewired-null control (Phase 6a) â degree-statistics, not wiring - #264
Conversation
Degree-preserving rewired-null control for the wild-type connectome â tests whether its 029 5th-of-6 standing is its specific C. elegans wiring or merely its degree statistics (Dhiman 2026). Config-option on the existing connectome brain (wiring: wild_type | rewired_degree_preserving + rewire_seed), a hand-rolled seeded degree-preserving double-edge-swap (chemical directed + gap undirected, no networkx dep), matched init/budget vs the 029 connectome cell, paired-seed Wilcoxon + BH-FDR verdict. Byte-identical when wiring: wild_type. Scope trimmed to the gating rewired-null; the learnable-gap-junction control (T7.controls.learnable_gj) is a tracked fast-follow. Authored + reviewed (/nematode-review-spec: matched-init RNG-independence fix applied); validate --strict + pre-commit green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- connectome/rewiring.py: seeded degree-preserving double-edge-swap (directed chemical + undirected gap), no networkx dep; preserves every neuron's in/out degree, rejects self-loops/duplicates, deterministic under seed. 12 tests. - ConnectomePPOBrain: `wiring` (wild_type | rewired_degree_preserving) + `rewire_seed` config fields; the transform runs at the load->topology seam on a DEDICATED RNG so the weight-init stream is unperturbed (matched init vs wild-type for the same seed). wild_type is byte-identical (guarded by a test reconstructing the mask from the loaded Cook adjacency). - TestWiringControl: wild-type == loaded connectome; rewired preserves degree but changes edges; gap stays symmetric; forward pass finite; seed controls the draw. - Rewired-null config: verbatim copy of the combined-C3 connectome cell + the one wiring field. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
scripts/analysis/connectome_structure_controls.py â paired wild-type vs rewired-null comparison on the C3 ranked-success metric, reusing the committed t7_continuous_ranking._plateau_tail metric + the paired-seed Wilcoxon / 80% bootstrap / BH-FDR layer. Pre-registered verdict: SPECIFIC-WIRING (wild-type > rewired at q<0.05) vs DEGREE-STATISTICS (CI spans 0), with the rewired-beats- wild-type edge case reported honestly. 6 tests. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Degree-preserving rewired-null control for the connectome's 029 5th-of-6 standing: is it the specific C. elegans wiring or just the degree statistics? Panel (wild-type vs degree-preserving rewired-null, n=8 paired seeds, 6000ep, matched init/budget): wild-type 52.78% vs rewired-null 56.06% â paired delta d=-3.28, CI[-8.56,+1.61] (spans 0), BH-FDR q=0.770 â indistinguishable (rewired nominally higher). The connectome's ranking is a DEGREE-STATISTICS result, not a wiring result: under PPO weight search the specific wiring confers no advantage over degree-matched alternatives (Beiran & Litwin-Kumar 2025 degeneracy). Does NOT say the wiring is functionless â its value is the evolved fixed weights. A single-seed smoke hinted "specific wiring" (57.2 vs 46.5) but reversed at n=8. Logbook 034 + committed supporting artefacts (controls.json + per-seed CSV + forensics), README row, tracker tick (T7.controls.rewired_null RESOLVED: DEGREE-STATISTICS; learnable_gj deferred as fast-follow), AGENTS.md _rewired_null variant doc, §5-§7 tasks ticked. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Change complete + evaluated (DEGREE-STATISTICS, Logbook 034). Archived to openspec/changes/archive/2026-07-05-add-connectome-structure-controls/ with all tasks ticked (§1â§8); the degree-preserving rewired-null wiring requirement is applied to openspec/specs/connectome-ppo-brain/ (heading spacing fixed post-archive). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Pre-push `pre-commit run -a` normalisation (magic trailing comma; no behaviour change). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Harness (scripts/analysis/connectome_structure_controls.py): - The reused Wilcoxon is one-sided (H1: wild > rewired), so the `rewired_beats` branch was unreachable â a significant rewired-WIN would be mislabeled "inconclusive". Detect it via the bootstrap CI (ci_hi < 0). + a regression test. - Warn when n < 5 paired seeds (the 1/2^n signed-rank floor makes q<0.05 â `specific_wiring` â unreachable; the n>=8 lesson from bit-memory 030); record `underpowered` in the summary. - Skip manifest lines whose seed token isn't an integer (no crash on a stray line). Rewiring (connectome/rewiring.py): - Guard against a non-simple input graph (parallel edges would silently collapse the weight dicts) with a clear ValueError. + a test. Tests: - Assert the matched-init invariant (food_gains/readout byte-identical between wild_type and rewired at the same seed â the control's load-bearing claim). - A rewired brain survives a PPO update (strict-mask holds on the rewired mask, not just wild-type). - Degree-preservation on a non-regular graph (the regular fixture hid in/out confusion); rewired-beats verdict reachability. None of these change the reported DEGREE-STATISTICS verdict (re-verified). Also: drop the AGENTS.md variant-suffix parenthetical for consistency, and drop the tmp/ path reference from the 034 supporting details. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ð WalkthroughWalkthroughAdds a degree-preserving double-edge-swap rewiring utility for connectomes, integrates it into ChangesRewired-Null Connectome Control
Estimated code review effort: 3 (Moderate) | ~30 minutes Possibly related PRs
Poem A rabbit rewired the worm's own wires, ðĨ Pre-merge checks | â 5â Passed checks (5 passed)
âĻ Finishing Touchesð Generate docstrings
ð§Š Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ð§đ Nitpick comments (3)
scripts/analysis/connectome_structure_controls.py (2)
32-33: ð Maintainability & Code Quality | ðĩ Trivial | ⥠Quick winImporting a private (
_-prefixed) helper across module boundaries.
_plateau_tailis name-mangled as private int7_continuous_ranking.py, yet it's imported and relied upon here as the load-bearing metric contract. This couples the two scripts to an internal implementation detail rather than a stable public API, so a future rename/refactor of_plateau_tailint7_continuous_ranking.pywill silently break this harness without any import-time signal beyond a linter warning.Consider exporting a public wrapper (e.g.,
plateau_tail) fromt7_continuous_ranking.pyfor cross-module reuse.ðĪ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scripts/analysis/connectome_structure_controls.py` around lines 32 - 33, The harness is importing the private helper _plateau_tail directly from t7_continuous_ranking, which couples connectome_structure_controls to an internal implementation detail. Update t7_continuous_ranking to expose a stable public wrapper such as plateau_tail, then switch the import in connectome_structure_controls to that public symbol and keep the existing metric usage unchanged. Ensure the cross-module contract references the public API only, while _plateau_tail remains internal if still needed.
52-67: ðïļ Data Integrity & Integration | ðĩ Trivial | ⥠Quick winMalformed manifest lines are silently dropped with no diagnostic.
Lines that don't match
len(parts) != 3 or not parts[1].isdigit()are skipped silently (Line 59-60), unlike the parseable-plateau failure path just below which logs aWARN. A typo'd arm/seed manifest entry (e.g., wrong token count, non-integer seed) would vanish from the analysis with no trace, which is harder to debug than the plateau-parse failures that do get logged. Also, a duplicate<arm> <seed>entry (Line 66) silently overwrites the prior value with no warning.ðĄ Proposed fix: warn on unparseable (non-comment) manifest lines
for line in manifest.read_text().splitlines(): parts = line.split() - if ( - len(parts) != 3 or not parts[1].isdigit() - ): # `<arm> <int seed> <out>`; skip anything else + if not parts or parts[0].startswith("#"): + continue + if len(parts) != 3 or not parts[1].isdigit(): + print(f" WARN unparseable manifest line, skipping: {line!r}") continue arm, seed, out_path = parts[0], int(parts[1]), Path(parts[2]) success = _success(REPO / out_path) if success is None: print(f" WARN {arm} seed {seed}: no parseable plateau in {out_path} - dropped") continue + if seed in arms.get(arm, {}): + print(f" WARN {arm} seed {seed}: duplicate manifest entry, overwriting") arms.setdefault(arm, {})[seed] = successðĪ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scripts/analysis/connectome_structure_controls.py` around lines 52 - 67, The load(manifest) parser in connectome_structure_controls.py is dropping malformed non-comment manifest lines and duplicate <arm> <seed> entries without any visibility. Update load() to emit a WARN for any line that fails the token-count/int-seed check instead of silently continuing, and add a warning when arms.setdefault(arm, {})[seed] would overwrite an existing seed entry so analysis issues are traceable. Keep the existing _success() warning path intact and use the load() loopâs existing arm/seed parsing to centralize the diagnostics.packages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.py (1)
8-9: ð Maintainability & Code Quality | ðĩ Trivial | ðĪ Low valueHardcoded
parents[5]traversal is brittle to future file moves.The fixed-depth
.resolve().parents[5]walk to locate the repo root (and hencescripts/analysis) will silently resolve to the wrong directory if this test file is ever relocated, without raising an error â it'd just fail to importconnectome_structure_controlsor (worse) find an unrelated directory. Low risk today, but worth a comment or a more robust anchor (e.g., searching upward forpyproject.toml) if this pattern spreads.ðĪ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.py` around lines 8 - 9, The path setup in the test module is brittle because _ANALYSIS_DIR relies on Path(__file__).resolve().parents[5], so update the import bootstrap to use a stable repo-root anchor or add an explicit comment documenting the fixed depth; in test_connectome_structure_controls, keep the sys.path insertion tied to a robust locator for scripts/analysis rather than a hardcoded parent index.
ðĪ Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@configs/scenarios/foraging_predator_thermal/connectomeppo_small_continuous2d_combined_klinotaxis_rewired_null.yml`:
- Line 1: Rename the scenario config so the variant suffix appears before the
sensing suffix, matching the documented
`{brain}_{size}[_{variant}]_{sensing}.yml` convention. Update the filename to
place `_rewired_null` before `_klinotaxis`, keeping it aligned with the sibling
`connectomeppo_small_continuous2d_combined_klinotaxis.yml` and the AGENTS.md
naming rule.
In `@packages/quantum-nematode/quantumnematode/connectome/rewiring.py`:
- Around line 149-154: The simple-graph validation in rewire_degree_preserving
only checks for duplicate/parallel edges, but it still allows chemical
self-loops through. Update the guard near the chem_edges/gap_edges validation to
also reject any ChemicalSynapse where pre == post, since the Cook loader can
preserve those fixtures unchanged. Keep the fix localized to
rewire_degree_preserving and ensure the ValueError is raised for any self-looped
chemical edge before rewiring proceeds.
---
Nitpick comments:
In
`@packages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.py`:
- Around line 8-9: The path setup in the test module is brittle because
_ANALYSIS_DIR relies on Path(__file__).resolve().parents[5], so update the
import bootstrap to use a stable repo-root anchor or add an explicit comment
documenting the fixed depth; in test_connectome_structure_controls, keep the
sys.path insertion tied to a robust locator for scripts/analysis rather than a
hardcoded parent index.
In `@scripts/analysis/connectome_structure_controls.py`:
- Around line 32-33: The harness is importing the private helper _plateau_tail
directly from t7_continuous_ranking, which couples connectome_structure_controls
to an internal implementation detail. Update t7_continuous_ranking to expose a
stable public wrapper such as plateau_tail, then switch the import in
connectome_structure_controls to that public symbol and keep the existing metric
usage unchanged. Ensure the cross-module contract references the public API
only, while _plateau_tail remains internal if still needed.
- Around line 52-67: The load(manifest) parser in
connectome_structure_controls.py is dropping malformed non-comment manifest
lines and duplicate <arm> <seed> entries without any visibility. Update load()
to emit a WARN for any line that fails the token-count/int-seed check instead of
silently continuing, and add a warning when arms.setdefault(arm, {})[seed] would
overwrite an existing seed entry so analysis issues are traceable. Keep the
existing _success() warning path intact and use the load() loopâs existing
arm/seed parsing to centralize the diagnostics.
ðŠ Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
âđïļ Review info
âïļ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 13e3b839-e330-4809-b128-aee53de44f3d
â Files ignored due to path filters (1)
docs/experiments/logbooks/supporting/034-connectome-structure-controls/success-per-seed.csvis excluded by!**/*.csv
ð Files selected for processing (19)
AGENTS.mdconfigs/scenarios/foraging_predator_thermal/connectomeppo_small_continuous2d_combined_klinotaxis_rewired_null.ymldocs/experiments/README.mddocs/experiments/logbooks/034-connectome-structure-controls.mddocs/experiments/logbooks/supporting/034-connectome-structure-controls/controls.jsondocs/experiments/logbooks/supporting/034-connectome-structure-controls/details.mdopenspec/changes/archive/2026-07-05-add-connectome-structure-controls/.openspec.yamlopenspec/changes/archive/2026-07-05-add-connectome-structure-controls/design.mdopenspec/changes/archive/2026-07-05-add-connectome-structure-controls/proposal.mdopenspec/changes/archive/2026-07-05-add-connectome-structure-controls/specs/connectome-ppo-brain/spec.mdopenspec/changes/archive/2026-07-05-add-connectome-structure-controls/tasks.mdopenspec/changes/phase6-tracking/tasks.mdopenspec/specs/connectome-ppo-brain/spec.mdpackages/quantum-nematode/quantumnematode/brain/arch/connectome_ppo.pypackages/quantum-nematode/quantumnematode/connectome/rewiring.pypackages/quantum-nematode/tests/quantumnematode_tests/analysis/test_connectome_structure_controls.pypackages/quantum-nematode/tests/quantumnematode_tests/brain/arch/test_connectome_ppo.pypackages/quantum-nematode/tests/quantumnematode_tests/connectome/test_rewiring.pyscripts/analysis/connectome_structure_controls.py
| @@ -0,0 +1,142 @@ | |||
| # Degree-preserving rewired-null control of the ConnectomePPO combined-C3 cell. | |||
There was a problem hiding this comment.
ð Maintainability & Code Quality | ð Major | ⥠Quick win
Filename places the new variant suffix after the sensing suffix.
Per AGENTS.md's own convention ({brain}_{size}[_{variant}]_{sensing}.yml, sensing suffixes listed last), _rewired_null is documented as a variant suffix but is appended here after the _klinotaxis sensing suffix, unlike the sibling connectomeppo_small_continuous2d_combined_klinotaxis.yml file this is meant to pair with. Consider connectomeppo_small_continuous2d_combined_rewired_null_klinotaxis.yml to match the documented ordering.
As per coding guidelines: configs/scenarios/**/*.yml: "Scenario configuration files must follow the naming convention {brain}_{size}[_{variant}]_{sensing}.yml."
ðĪ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@configs/scenarios/foraging_predator_thermal/connectomeppo_small_continuous2d_combined_klinotaxis_rewired_null.yml`
at line 1, Rename the scenario config so the variant suffix appears before the
sensing suffix, matching the documented
`{brain}_{size}[_{variant}]_{sensing}.yml` convention. Update the filename to
place `_rewired_null` before `_klinotaxis`, keeping it aligned with the sibling
`connectomeppo_small_continuous2d_combined_klinotaxis.yml` and the AGENTS.md
naming rule.
Source: Coding guidelines
| # The swap assumes a SIMPLE input graph (no parallel edges) - the weight dicts below key on the | ||
| # edge tuple and would silently collapse duplicates. The Cook loader dedups both edge types, so | ||
| # this is a guard against a hand-built/alternate-loader fixture, not a live path. | ||
| if len(set(chem_edges)) != len(chem_edges) or len(set(gap_edges)) != len(gap_edges): | ||
| msg = "rewire_degree_preserving requires a simple connectome (no duplicate/parallel edges)" | ||
| raise ValueError(msg) |
There was a problem hiding this comment.
ðïļ Data Integrity & Integration | ðĄ Minor | ⥠Quick win
ð§Đ Analysis chain
ð Script executed:
#!/bin/bash
# Confirm whether ChemicalSynapse forbids self-loops (pre == post) at construction.
rg -n -A 15 'class ChemicalSynapse' packages/quantum-nematode/quantumnematode/connectome/model.pyRepository: SyntheticBrains/nematode
Length of output: 706
ð Script executed:
#!/bin/bash
set -euo pipefail
echo "== model.py around ChemicalSynapse =="
sed -n '55,130p' packages/quantum-nematode/quantumnematode/connectome/model.py
echo
echo "== rewiring.py around the degree-preserving swap and output checks =="
sed -n '1,240p' packages/quantum-nematode/quantumnematode/connectome/rewiring.pyRepository: SyntheticBrains/nematode
Length of output: 10650
ð Script executed:
#!/bin/bash
set -euo pipefail
echo "== search for self-loop handling in connectome code =="
rg -n -A 3 -B 3 'self-loop|pre == post|a < b|duplicate|parallel' packages/quantum-nematode/quantumnematode/connectome
echo
echo "== locate parser/loader entry points =="
rg -n -A 5 -B 5 'ChemicalSynapse|GapJunction|Connectome' packages/quantum-nematode/quantumnematode/connectomeRepository: SyntheticBrains/nematode
Length of output: 45748
ð Script executed:
#!/bin/bash
set -euo pipefail
echo "== chemical edge parsing and any self-loop filtering in loader.py =="
sed -n '120,240p' packages/quantum-nematode/quantumnematode/connectome/loader.py
echo
echo "== direct search for chemical self-loop checks =="
rg -n 'pre == post|a == b|self-loop' packages/quantum-nematode/quantumnematode/connectome/loader.pyRepository: SyntheticBrains/nematode
Length of output: 4686
Reject chemical self-loops here. ChemicalSynapse accepts pre == post, and the Cook loader doesnât filter them, so a fixture with a pre-existing self-loop can still be returned unchanged and violate the simple-graph contract.
ðĪ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/quantum-nematode/quantumnematode/connectome/rewiring.py` around
lines 149 - 154, The simple-graph validation in rewire_degree_preserving only
checks for duplicate/parallel edges, but it still allows chemical self-loops
through. Update the guard near the chem_edges/gap_edges validation to also
reject any ChemicalSynapse where pre == post, since the Cook loader can preserve
those fixtures unchanged. Keep the fix localized to rewire_degree_preserving and
ensure the ValueError is raised for any self-looped chemical edge before
rewiring proceeds.
Codecov Reportâ Patch coverage is ðĒ Thoughts on this report? Let us know! |
Summary
The credibility control for the connectome half of the Phase-6a synthesis. The continuous-substrate ranking (Logbook 029) placed the wild-type C. elegans connectome 5th of 6 under PPO weight search. This change answers the obvious question: is that its specific wiring, or just its degree / sparsity statistics?
A degree-preserving rewired-null (Dhiman 2026) â rewire the connectome so every neuron keeps its exact in/out degree but which neurons connect is scrambled â as a config option on the existing connectome brain (
wiring: wild_type | rewired_degree_preserving+rewire_seed), byte-identical when wild-type, matched initialisation (dedicated RNG) + budget. Full write-up: Logbook 034.Result â DEGREE-STATISTICS
Panel: wild-type vs rewired-null, n=8 paired seeds, 6000ep, same recipe/budget as the 029 connectome cell.
Paired delta (wild â rewired): d = â3.28, CI[â8.56, +1.61] (spans 0), BH-FDR q = 0.770 â indistinguishable (rewired nominally higher).
The connectome's ranking is a degree-statistics result, not a wiring result. Under PPO weight search â which re-optimises the chemical weights freely on whatever topology it is given â the specific C. elegans wiring confers no advantage over degree-matched alternatives (the Beiran & Litwin-Kumar 2025 degeneracy prediction). It does not say the wiring is functionless â its value is presumably the evolved fixed weights + specific I/O routing, not a better substrate for gradient descent.
A single-seed smoke hinted "specific wiring" (57.2 vs 46.5) but reversed at n=8 â a clean caution that connectome results must not be read off one seed.
Mechanism
connectome/rewiring.pyâ a seeded degree-preserving double-edge-swap (directed configuration-model for chemical synapses, undirected for gap junctions; no networkx dependency). On the real connectome: 91% of chemical edges moved, degree exactly preserved, mixes cleanly.ConnectomePPOBraingains thewiring/rewire_seedfields; the transform runs at the loadâtopology seam on a dedicated RNG so the weight-init stream is unperturbed (matched init vs wild-type for the same seed). Byte-identical whenwiring: wild_type(guarded by a test).scripts/analysis/connectome_structure_controls.pyâ paired wild-vs-rewired comparison reusing the committed 029 ranked metric + the paired-seed Wilcoxon / bootstrap / BH-FDR layer.Self-review
Ran a multi-angle review of the branch (edge-swap correctness, seam+harness, tests/conventions). The algorithm and the matched-init seam verified correct; applied fixes for a one-sided-Wilcoxon verdict-branch reachability bug, two load-bearing test gaps (matched-init assertion, rewired-brain-trains), and cheap robustness guards. None changed the verdict.
Scope
Ships the gating rewired-null; the learnable-gap-junction control (
T7.controls.learnable_gj) is a tracked fast-follow.Gates
openspec validate --strictvalid; change archived (spec requirement applied); fullpytest -m "not nightly"â 4090 passed; fullpre-commit run -aclean.ðĪ Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation