Reproducing Dvali et al. (2025) from dandiset 001075¶

Paper. Dvali S, Seguin C, Betzel R, Leifer AM (2025). Diverging network architecture of the C. elegans connectome and signaling network. doi:10.1103/6wgv-b9m6. The claims file was written from the full text supplied with the attempt (its body is the arXiv preprint 2412.14498v2, with Methods and Extended Data), and from the paper's code (FunconnNetworkAnalysis, commit 35e87ca).

Dandiset. DANDI:001075, version 0.240920.1434, the version the paper cites (Methods, The Networks; reference 88). The paper reuses the signal propagation atlas of Randi et al. (2023). One later version exists, 0.240930.1859. It holds the same 223 files, and its 110 segmentation files differ: they add target_pumpprobe_id, the ROI that each stimulation targeted, and split the green and red signals into a series with missing frames as NaN and an interpolated one. The cited version does not say which ROI was stimulated, so the stimulated-ROI identities, and only they, are read from 0.240930.1859 (listed under inputs in the record). The data check below shows the difference.

What the dandiset holds and what it does not. Per recording, the calcium signal of every segmented ROI, the NeuroPAL labels, and the stimulation times and targets, for 110 recordings of wild-type animals. It does not hold the signaling network itself, nor the q-values that define it, nor the control recordings without stimulation that Randi et al.'s code uses to compute the q-values (pumpprobe Funatlas.get_ctrl_distributions). Reading (a) of the claims file (recompute the q-values from the dandiset) therefore cannot be run, and the signaling network is taken under reading (b), from the wild-type atlas released with Randi et al. 2023 (worm-functional-connectivity, commit 81af01c), whose entries are NaN where q > 0.05. A link claim (atlas-dataset-link) tests that this atlas matches the dandiset's recordings. The atlas holds no q-values, so the networks at q < 0.01 and q <= 0.18 cannot be built.

Outside inputs. The anatomical network comes from the four EM datasets that Randi et al.'s code combines (White 1986 adult and L4, Witvliet 2021 datasets 7 and 8), as stored in pumpprobe at commit 1dbc5e0. Neuron classes and roles are the lists in the paper's code (compared with its source in the data check).

Software. The stochastic block model of the paper runs in graph-tool, which has no PyPI distribution and cannot be installed in the entry's locked environment; every claim on communities is blocked as not_runnable (PyPI holds no files for graph-tool; data check). The paper prints the first-level memberships of both networks (Tables 1 and 2), but they are the output of the model that cannot be run, so they are not typed in here as an input: the entry computes every result from the data. The rich club null uses a degree-preserving rewiring written here in place of graph-tool's random_rewire.

Random seeds. Each claim's generator is seeded with zlib.crc32(b"dvali-2025/<claim id>"); results that depend on random draws are also given under the seed plus 1000, 2000, 3000 and 4000.

Claim Data Status
atlas-dataset-link (link) with inputs tested
signaling-network-size dataset (atlas, reading b) tested
signaling-clustering-small-world dataset (atlas) tested
anatomy-network-properties elsewhere tested
triad-distribution with inputs tested
ed6-signaling-not-feedforward with labels tested
ed6-anatomy-feedforward elsewhere tested
fig4c-broadcaster-integrator with labels tested
ed9-sampling-not-confound with labels tested
fig5a-signaling-rich-club dataset (atlas) tested
fig5c-rich-clubs-disjoint with inputs tested
fig5b-degree-correlation with inputs tested
ed10-rich-club-cell-classes with labels tested
ed9e-degree-observations dataset tested
ave-most-connected-both with inputs tested
signaling-threshold-controls, bilateral-controls-signaling dataset blocked: q-values other than q < 0.05 not available
rich-club-controls with inputs blocked: q-values other than q < 0.05 not available; the one pair that can be built is shown
21 claims on the stochastic block model communities and what depends on them various blocked: graph-tool not installable
In [1]:
import collections
import hashlib
import inspect
import io
import resource
import time
import warnings
import zlib

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
from scipy import stats

import networks as nw

T0 = time.time()
KEY = "dvali-2025"
OFFSETS = [0, 1000, 2000, 3000, 4000]


def seed_of(claim_id, extra=0):
    """The claim's seed (protocol); `extra` is added for a second generator of the same claim."""
    return zlib.crc32(f"{KEY}/{claim_id}".encode()) + extra


warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 160)
pd.set_option("display.max_columns", 30)

Data check¶

The archive's file lists of the two published versions, and what differs between them.

In [2]:
from dandi.dandiapi import DandiAPIClient

client = DandiAPIClient()
versions = [v.identifier for v in client.get_dandiset(nw.DANDISET_ID).get_versions()]
print("versions on the archive:", versions)
files = {}
for v in (nw.DANDISET_VERSION, nw.STIM_ID_VERSION):
    files[v] = {a.path: a.size for a in client.get_dandiset(nw.DANDISET_ID, v).get_assets()}
v1, v2 = files[nw.DANDISET_VERSION], files[nw.STIM_ID_VERSION]
kinds = collections.Counter(p.split("desc-")[1] for p in v1)
print(f"{nw.DANDISET_VERSION}: {len(v1)} files, {sum(v1.values()) / 1e12:.2f} TB;", dict(kinds))
print(f"{nw.STIM_ID_VERSION}: {len(v2)} files; same paths: {set(v1) == set(v2)}")
changed = sorted(p for p in v1 if v1[p] != v2[p])
print("files whose size differs between versions:", len(changed),
      "of which segmentation files:", sum("segmentation" in p for p in changed))
sessions_im = {p.split("_desc")[0] for p in v1 if "desc-imaging" in p}
sessions_seg = {p.split("_desc")[0] for p in v1 if "desc-segmentation" in p}
print("recordings with raw imaging but no segmentation file:", sorted(sessions_im - sessions_seg))
versions on the archive: ['draft', '0.240920.1434', '0.240930.1859']
0.240920.1434: 223 files, 4.07 TB; {'segmentation_ophys+ogen.nwb': 110, 'imaging_ophys+ogen.nwb': 113}
0.240930.1859: 223 files; same paths: True
files whose size differs between versions: 110 of which segmentation files: 110
recordings with raw imaging but no segmentation file: ['sub-20/sub-20_ses-20210917-132736', 'sub-23/sub-23_ses-20211008-115929', 'sub-33/sub-33_ses-20220330-110253']

Reading a file with pynwb. The files declare the ndx-patterned-ogen and ndx-microscopy extensions in their cached specifications; the cell shows whether the installed pynwb builds them. The analysis reads the files with h5py in any case.

In [3]:
import pynwb

_, seg_assets = nw.list_segmentation_assets()
try:
    with pynwb.NWBHDF5IO(file=nw._open(seg_assets[0]), load_namespaces=True) as io_:
        io_.read()
    print("pynwb", pynwb.__version__, "reads", seg_assets[0].path)
except Exception as e:  # noqa: BLE001
    print("pynwb", pynwb.__version__, "cannot read", seg_assets[0].path)
    print(type(e).__name__, str(e)[-260:])
/home/runner/work/encore/encore/executed/dvali-2025/.venv/lib/python3.13/site-packages/hdmf/spec/namespace.py:630: UserWarning: Schema conflict(s) detected in namespace 'ndx-microscopy': 
 ndx-microscopy defines Microscope.model as an attribute (dtype: text) while the core schema defines it as a link to DeviceModel.
ndx-microscopy defines MicroscopyLightSource.model as an attribute (dtype: text) while the core schema defines it as a link to DeviceModel. 
This may cause compatibility issues. Please update the extension version if possible or install an older version of the core schema that is compatible.
  self._check_namespace_conflicts(extension_ns_name=ns_name,
/home/runner/work/encore/encore/executed/dvali-2025/.venv/lib/python3.13/site-packages/hdmf/spec/namespace.py:630: UserWarning: Schema conflict(s) detected in namespace 'ndx-patterned-ogen': 
 ndx-patterned-ogen defines SpatialLightModulator2D.model as an attribute (dtype: text) while the core schema defines it as a link to DeviceModel.
ndx-patterned-ogen defines SpatialLightModulator3D.model as an attribute (dtype: text) while the core schema defines it as a link to DeviceModel.
ndx-patterned-ogen defines LightSource.model as an attribute (dtype: text) while the core schema defines it as a link to DeviceModel. 
This may cause compatibility issues. Please update the extension version if possible or install an older version of the core schema that is compatible.
  self._check_namespace_conflicts(extension_ns_name=ns_name,
pynwb 4.2.0 cannot read sub-0/sub-0_ses-20210824-104000_desc-segmentation_ophys+ogen.nwb
ConstructError float64(850.0)}, 'groups': {}, 'datasets': {}, 'links': {}}}}}, "Could not construct PatternedOptogeneticStimulusSite object due to: CustomClassGenerator.set_init.<locals>.__init__: incorrect type for 'spatial_light_modulator' (got 'list', expected 'Device')")
/home/runner/work/encore/encore/executed/dvali-2025/.venv/lib/python3.13/site-packages/hdmf/build/objectmapper.py:1630: UserWarning: Device.model was detected as a string, but NWB 2.9 specifies Device.model as a link to a DeviceModel. Remapping "ORPHEUS amplifier and PHAROS laser" to a new DeviceModel.
  override = self.__get_override_carg(argname, builder, manager)

All 110 segmentation files, streamed (green signal, labels, ROI matching, stimulation table), with the stimulated-ROI ids and the NaN-marked green signal of the later version.

In [4]:
t = time.time()
sessions = nw.load_sessions(with_signal=True, workers=8)
print(f"loaded {len(sessions)} recordings in {time.time() - t:.0f} s; "
      f"peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
survey = pd.DataFrame([dict(
    path=s["path"], strain=s["strain"], genotype=s["genotype"], stage=s["stage"],
    start=s["start"], n_stim=len(s["stim_start"]), frames=s["signal_shape"][0],
    rois=s["signal_shape"][1], dt=float(np.median(np.diff(s["timestamps"]))),
    duration_s=float(s["timestamps"][-1] - s["timestamps"][0]),
    stim_interval_s=float(np.median(np.diff(s["stim_start"]))) if len(s["stim_start"]) > 1 else np.nan,
    stim_len_s=float(np.median(s["stim_stop"] - s["stim_start"])),
    rois_match_columns=bool(np.array_equal(s["signal_rois"], np.arange(s["signal_shape"][1]))),
    red_same_shape=s["red_shape"] == s["signal_shape"], red_same_clock=s["red_same_clock"],
) for s in sessions])
print(survey.groupby(["strain", "genotype"]).size())
print(survey.groupby("stage").size())
print(survey[["n_stim", "frames", "rois", "dt", "duration_s", "stim_interval_s", "stim_len_s"]]
      .describe().round(3))
print("signal columns are the ROIs in order in every file:", survey.rois_match_columns.all(),
      "; red signal has the green signal's shape in every file:", survey.red_same_shape.all(),
      "and its timestamps:", survey.red_same_clock.all())
print("total stimulations:", survey.n_stim.sum())
loaded 110 recordings in 242 s; peak memory 1.17 GB
strain  genotype
AML462  WT          108
none    WT            2
dtype: int64
stage
L4    63
YA    47
dtype: int64
        n_stim    frames     rois       dt  duration_s  stim_interval_s  stim_len_s
count  110.000   110.000  110.000  110.000     110.000          110.000       110.0
mean    51.036  3471.873  127.627    0.501    1735.579           34.605         0.5
std     22.057  1271.651   31.142    0.000     635.883           10.601         0.0
min      3.000   393.000   80.000    0.501     196.006           30.590         0.5
25%     42.250  3057.500  105.250    0.501    1528.266           30.790         0.5
50%     54.500  3799.500  125.000    0.501    1901.780           30.810         0.5
75%     65.000  4406.750  147.000    0.501    2202.905           31.660         0.5
max     92.000  5848.000  281.000    0.501    2924.531           75.110         0.5
signal columns are the ROIs in order in every file: True ; red signal has the green signal's shape in every file: True and its timestamps: True
total stimulations: 5614

Duplicated recordings: identical green signals, or identical start times.

In [5]:
digests = collections.defaultdict(list)
for s in sessions:
    digests[hashlib.sha1(np.ascontiguousarray(s["green"][:200]).tobytes()).hexdigest()].append(s["path"])
dups = [v for v in digests.values() if len(v) > 1]
print("recordings whose first 200 frames are identical to another's:", dups)
starts = survey.groupby("start").path.apply(list)
print("start times shared by more than one recording:", [v for v in starts if len(v) > 1])
# Same subject ids across files: each file is its own subject (sub-<n>).
print("distinct subjects:", survey.path.str.split("/").str[0].nunique())
recordings whose first 200 frames are identical to another's: []
start times shared by more than one recording: []
distinct subjects: 110

The green signal of the cited version against the later version. The later version's BaseGreenSignal keeps the frames that could not be measured as NaN.

In [6]:
rows = []
for s in sessions:
    base = s["later"].pop("base")
    fin = np.isfinite(base)
    rows.append(dict(path=s["path"], cited_nan=float(np.isnan(s["green"]).mean()),
                     later_nan=float(1 - fin.mean()),
                     equal_where_measured=bool(np.allclose(s["green"][fin], base[fin])),
                     same_shape=base.shape == s["green"].shape))
    s["missing"] = ~fin
vd = pd.DataFrame(rows)
print("same shape in every file:", vd.same_shape.all())
print("cited GreenSignal equals the later BaseGreenSignal wherever the latter is measured:",
      vd.equal_where_measured.all())
print("fraction of NaN in the cited GreenSignal: max", vd.cited_nan.max())
print("fraction of frames x ROIs that the later version marks as not measured "
      "(interpolated, unmarked, in the cited version):")
print(vd.later_nan.describe().round(3))
same shape in every file: True
cited GreenSignal equals the later BaseGreenSignal wherever the latter is measured: True
fraction of NaN in the cited GreenSignal: max 0.36363636363636365
fraction of frames x ROIs that the later version marks as not measured (interpolated, unmarked, in the cited version):
count    110.000
mean       0.420
std        0.113
min        0.174
25%        0.336
50%        0.420
75%        0.507
max        0.682
Name: later_nan, dtype: float64

Labels. NeuroPAL labels are matched to the 188 head neuron names of the atlas by exact name. Labels that name a bilateral class without its side, numbers and free text are counted apart.

In [7]:
names, scalar_atlas = nw.load_atlas()
N = len(names)
name_set = set(names)
idx = {n: i for i, n in enumerate(names)}
lab_kinds = collections.Counter()
dup_in_rec = 0
examples = collections.defaultdict(collections.Counter)
for s in sessions:
    labs = [x for x in s["roi_label"] if x]
    c = collections.Counter(labs)
    dup_in_rec += sum(v - 1 for k, v in c.items() if k in name_set and v > 1)
    for x in labs:
        if x in name_set:
            k = "head neuron name"
        elif any(x + side in name_set for side in ("L", "R")):
            k = "class without side"
        elif x.isdigit():
            k = "number"
        else:
            k = "other"
        lab_kinds[k] += 1
        examples[k][x] += 1
print("labels of ROIs in the activity recordings:", dict(lab_kinds))
for k in ("class without side", "number", "other"):
    print(f"  {k}: most common", examples[k].most_common(8))
print("ROIs whose head-neuron label repeats another ROI's in the same recording:", dup_in_rec)
print("atlas neurons:", N, "; all names in the paper's class lists:",
      set(names) == set(nw.SENSORY) | set(nw.INTER) | set(nw.MOTOR))
labels of ROIs in the activity recordings: {'class without side': 487, 'head neuron name': 6659, 'other': 272, 'number': 35}
  class without side: most common [('RIG', 51), ('RMDD', 30), ('IL1V', 26), ('CEPV', 25), ('SMDD', 21), ('SAAD', 19), ('IL2D', 18), ('OLQV', 16)]
  number: most common [('48', 3), ('41', 2), ('30', 2), ('21', 1), ('18', 1), ('9', 1), ('26', 1), ('32', 1)]
  other: most common [('target', 49), ('AMso', 34), ('AWCOFF', 21), ('AMSoL', 17), ('AMSoR', 15), ('AWCON', 14), ('SMB', 14), ('DB', 9)]
ROIs whose head-neuron label repeats another ROI's in the same recording: 1
atlas neurons: 188 ; all names in the paper's class lists: True

What the outside sources hold. Every attribute of the atlas pickle, and every file other than code in the three repositories at their pinned commits, to show whether any of them holds q-values or an atlas not thresholded at q < 0.05. The TSV of worm-functional-connectivity is an export of one scalar per pair (scripts/export_atlas_scalar.py). Also the number of files of graph-tool on PyPI, from which the registry installs packages.

In [8]:
print("atlas pickle attributes (type, shape):")
for k, v in nw.atlas_attributes().items():
    print(f"  {k}: {v}")
code_ext = (".py", ".pyc", ".cpp", ".hpp", ".tcc", ".h", ".o", ".so", ".sh", ".iml", ".xml")
for repo, commit in ((nw.WFC_REPO, nw.WFC_COMMIT), (nw.PUMPPROBE_REPO, nw.PUMPPROBE_COMMIT),
                     (nw.FNA_REPO, nw.FNA_COMMIT)):
    files_ = nw.repo_files(repo, commit)
    data_ = {k: v for k, v in files_.items() if not k.endswith(code_ext) and not k.startswith("build/")}
    print(f"{repo} at {commit[:7]}: {len(files_)} files, {len(data_)} not code (build/ left out):")
    for k, v in data_.items():
        print(f"  {k} ({v} bytes)")
tsv = pd.read_csv(io.BytesIO(nw._raw(nw.WFC_REPO, nw.WFC_COMMIT,
                                    "scripts/leifer_funconn_wildtype_2022-04-01.tsv")),
                  sep="\t", header=None, names=["from", "to", "value"])
print(f"worm-functional-connectivity TSV: {len(tsv)} rows, {tsv['from'].nunique()} neurons, "
      f"one value per pair, {tsv.value.nunique()} distinct values, range {tsv.value.min()} to "
      f"{tsv.value.max()}")
print("graph-tool distribution files on PyPI, all releases:", nw.pypi_files("graph-tool"))
atlas pickle attributes (type, shape):
  neu_ids: ('ndarray', (188,))
  ec: ('ndarray', (188, 188))
  scalar_atlas: ('ndarray', (188, 188))
  n_neu: ('int', None)
  strain: ('str', None)
  folder: ('str', None)
  fname: ('str', None)
leiferlab/worm-functional-connectivity at 81af01c: 26 files, 8 not code (build/ left out):
  .gitignore (1812 bytes)
  README.md (3195 bytes)
  atlas/mock_.pickle (2166370 bytes)
  atlas/unc-31.pickle (608632 bytes)
  atlas/wild-type.pickle (2082820 bytes)
  pyproject.toml (76 bytes)
  scripts/leifer_funconn_wildtype_2022-04-01.tsv (1046937 bytes)
  wormfunconn/aconnectome_ids.txt (2641 bytes)
leiferlab/pumpprobe at 1dbc5e0: 207 files, 55 not code (build/ left out):
  LICENSE (35149 bytes)
  README.md (4883 bytes)
  pumpprobe.egg-info/PKG-INFO (262 bytes)
  pumpprobe.egg-info/SOURCES.txt (1314 bytes)
  pumpprobe.egg-info/dependency_links.txt (1 bytes)
  pumpprobe.egg-info/top_level.txt (10 bytes)
  pumpprobe/GenesExpressing-daf-2-thrs2.csv (1905 bytes)
  pumpprobe/GenesExpressing-neuropeptide-receptors.csv (80763 bytes)
  pumpprobe/GenesExpressing-neuropeptides.csv (63665 bytes)
  pumpprobe/GenesExpressing-npr-11-thrs2.csv (652 bytes)
  pumpprobe/GenesExpressing-npr-4-thrs2.csv (1294 bytes)
  pumpprobe/GenesExpressing-pdfr-1-thrs2.csv (1999 bytes)
  pumpprobe/GenesExpressing-unc-7-unc-9-inx-_-eat-5-thrs2.csv (12761 bytes)
  pumpprobe/aconnectome.json (902866 bytes)
  pumpprobe/aconnectome_ids.txt (2641 bytes)
  pumpprobe/aconnectome_ids_ganglia.json (5636 bytes)
  pumpprobe/aconnectome_white_1986_A.csv (41889 bytes)
  pumpprobe/aconnectome_white_1986_L4.csv (39065 bytes)
  pumpprobe/aconnectome_white_1986_whole.csv (64492 bytes)
  pumpprobe/aconnectome_witvliet_2020_7.csv (55102 bytes)
  pumpprobe/aconnectome_witvliet_2020_8.csv (55153 bytes)
  pumpprobe/anatlas_neuron_positions.txt (18392 bytes)
  pumpprobe/esconnectome_monoamines_Bentley_2016.csv (66771 bytes)
  pumpprobe/esconnectome_neuropeptides_Bentley_2016.csv (202710 bytes)
  pumpprobe/sensoryintermotor_ids.json (2377 bytes)
  scripts/fconnectivity/figures/2Pspotcharacterization/off_target_xy_image.png (98192 bytes)
  scripts/fconnectivity/figures/RID/commands (240 bytes)
  scripts/fconnectivity/figures/RID/list.txt (908 bytes)
  scripts/fconnectivity/figures/gur-3/fpbase_spectra.csv (3875 bytes)
  scripts/fconnectivity/figures/paper/anatomy_derived_simulations.txt (124 bytes)
  scripts/fconnectivity/figures/paper/fig1_commands.txt (961 bytes)
  scripts/fconnectivity/figures/paper/fig2_commands.txt (1063 bytes)
  scripts/fconnectivity/figures/paper/fig3_commands.txt (147 bytes)
  scripts/fconnectivity/figures/paper/fig4_commands.txt (441 bytes)
  scripts/fconnectivity/figures/paper/fig5_commands.txt (1067 bytes)
  scripts/fconnectivity/figures/paper/fig6_commands.txt (712 bytes)
  scripts/fconnectivity/figures/paper/figS1_commands.txt (0 bytes)
  scripts/fconnectivity/figures/paper/figS2_commands.txt (1081 bytes)
  scripts/fconnectivity/figures/paper/figS3_commands.txt (348 bytes)
  scripts/fconnectivity/figures/paper/figS4_commands.txt (706 bytes)
  scripts/fconnectivity/figures/paper/figS5_commands.txt (502 bytes)
  scripts/fconnectivity/figures/paper/figS6_commands.txt (1157 bytes)
  scripts/fconnectivity/figures/paper/figS7_commands.txt (635 bytes)
  scripts/fconnectivity/figures/paper/figS8_commands.txt (1739 bytes)
  scripts/fconnectivity/figures/paper/figS9_commands.txt (1614 bytes)
  scripts/fconnectivity/figures/paper/generating_Numbers_for_paper_file.txt (144 bytes)
  scripts/fconnectivity/figures/paper/generating_atlases_for_apps.txt (104 bytes)
  scripts/fconnectivity/figures/paper/generating_cache_files.txt (590 bytes)
  scripts/fconnectivity/figures/paper/reminder_exporting_data.txt (656 bytes)
  scripts/fconnectivity/preliminary_scripts/external_data/GenesExpressing-daf-2-thrs2.csv (1905 bytes)
  scripts/fconnectivity/preliminary_scripts/external_data/GenesExpressing-npr-11-thrs2.csv (652 bytes)
  scripts/fconnectivity/preliminary_scripts/external_data/GenesExpressing-npr-4-thrs2.csv (1294 bytes)
  scripts/fconnectivity/preliminary_scripts/external_data/GenesExpressing-pdfr-1-thrs2.csv (1999 bytes)
  scripts/fconnectivity/preliminary_scripts/external_data/GenesExpressing-unc-7-unc-9-inx-*-eat-5-thrs2.xlsx (19221 bytes)
  scripts/fconnectivity/preliminary_scripts/external_data/GenesExpressing-unc-7-unc-9-inx-_-eat-5-thrs2.csv (12761 bytes)
SophieDvali/FunconnNetworkAnalysis at 35e87ca: 24 files, 1 not code (build/ left out):
  .idea/.gitignore (176 bytes)
worm-functional-connectivity TSV: 90000 rows, 300 neurons, one value per pair, 107 distinct values, range -53 to 914
graph-tool distribution files on PyPI, all releases: 0

The neuron lists of the helper against the lists written in the paper's code, parsed from its source at the pinned commit, and the code's swapping_edges (SIM_doubleedge.py), which nw.swapping_edges ports. Extended Data Figure 5 shows the class and role annotations as an image; its neuron names are not in the text of the paper, so the lists can be compared only with the code.

In [9]:
helper_lists = {"sensory": nw.SENSORY, "inter": nw.INTER, "motor": nw.MOTOR, "pharynx": nw.PHARYNX,
                "Amphid": nw.AMPHID}
for (fname, var), lst in nw.code_lists().items():
    h = helper_lists[var]
    print(f"{fname} {var}: {len(lst)} names; same as the helper's list: {lst == h}; "
          f"only in the code: {sorted(set(lst) - set(h))}; only in the helper: {sorted(set(h) - set(lst))}")
print("class lists disjoint:", not (set(nw.SENSORY) & set(nw.INTER) or set(nw.SENSORY) & set(nw.MOTOR)
                                    or set(nw.INTER) & set(nw.MOTOR)))
print("pharynx and amphid neurons among the atlas's 188:", len(set(nw.PHARYNX) & name_set),
      len(set(nw.AMPHID) & name_set))
print("--- swapping_edges in SIM_doubleedge.py:")
print(nw.code_function_source("SIM_doubleedge.py", "swapping_edges"))
print("--- the port in the helper:")
print(inspect.getsource(nw.swapping_edges))
SIM.py sensory: 70 names; same as the helper's list: True; only in the code: []; only in the helper: []
SIM.py inter: 72 names; same as the helper's list: True; only in the code: []; only in the helper: []
SIM.py motor: 46 names; same as the helper's list: True; only in the code: []; only in the helper: []
SIM_doubleedge.py sensory: 70 names; same as the helper's list: True; only in the code: []; only in the helper: []
SIM_doubleedge.py inter: 72 names; same as the helper's list: True; only in the code: []; only in the helper: []
SIM_doubleedge.py motor: 46 names; same as the helper's list: True; only in the code: []; only in the helper: []
richclub.py sensory: 70 names; same as the helper's list: True; only in the code: []; only in the helper: []
richclub.py inter: 72 names; same as the helper's list: True; only in the code: []; only in the helper: []
richclub.py motor: 46 names; same as the helper's list: True; only in the code: []; only in the helper: []
richclub.py pharynx: 20 names; same as the helper's list: True; only in the code: []; only in the helper: []
broadcaster_integrator.py Amphid: 24 names; same as the helper's list: True; only in the code: []; only in the helper: []
broadcaster_integrator.py pharynx: 20 names; same as the helper's list: True; only in the code: []; only in the helper: []
class lists disjoint: True
pharynx and amphid neurons among the atlas's 188: 20 24
--- swapping_edges in SIM_doubleedge.py:
def swapping_edges(G, nswap=1, max_tries=2000, seed=None):
    n = 0
    swapcount = 0
    keys, degrees = zip(*G.degree())  # keys, degree
    cdf = nx.utils.cumulative_distribution(degrees)  # cdf of degree
    discrete_sequence = nx.utils.discrete_sequence
    while swapcount < nswap:
        #        if random.random() < 0.5: continue # trick to avoid periodicities?
        # pick two random edges without creating edge list
        # choose source node indices from discrete distribution
        (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed)
        random.seed(seed)
        if ui == xi:
            continue  # same source, skip
        u = keys[ui]  # convert index to label
        x = keys[xi]
        # choose target uniformly from neighbors
        if list(G[u]) and list(G[x]):
           v = random.choice(list(G[u]))
           y = random.choice(list(G[x]))
        else:
           continue

        if v == y:
            continue  # same target, skip
        if (y not in G[u]) and (v not in G[x]):  # don't create parallel edges
            G.add_edge(u, y)
            G.add_edge(x, v)
            G.remove_edge(u, v)
            G.remove_edge(x, y)
            swapcount += 1
        if n >= max_tries:
            #e = (
            #    f"Maximum number of swap attempts ({n}) exceeded "
            #    f"before desired swaps achieved ({nswap})."
            #)
            print("Maximum number of swap attempts exceeded before desired swaps achieved.)")
            print(str(swapcount)+" swaps done")
            #raise nx.NetworkXAlgorithmError(e)
            return G
        n += 1
    return G
--- the port in the helper:
def swapping_edges(a: np.ndarray, rng: np.random.Generator, nswap: int = 2000,
                   max_tries: int = 4000) -> tuple[np.ndarray, int]:
    """Port of `swapping_edges` in SIM_doubleedge.py: x->y and a->b become x->b and a->y.

    Sources are drawn with probability proportional to total degree, targets uniformly among
    each source's successors; a swap that would create a parallel edge is skipped. As in the
    code, self-loops are not prevented, and draws that end in `continue` there (the same
    source twice, a source without successors, the same target) do not count towards
    `max_tries`; the code stops once its counter reaches `max_tries`. The code calls it with
    nswap=2000, max_tries=4000 for the signaling network and nswap=6000, max_tries=9000 for
    the anatomical one (SIM_doubleedge.py lines 237 and 493). Returns the swapped adjacency
    and the number of swaps made.
    """
    succ = [np.nonzero(a[i])[0].tolist() for i in range(a.shape[0])]
    succ_set = [set(x) for x in succ]
    deg = total_degree(a).astype(float)
    p = deg / deg.sum()
    swaps = 0
    n = 0
    chunk = 4096
    pairs = rng.choice(len(deg), size=(chunk, 2), p=p)
    picks = rng.random((chunk, 2))
    j = 0
    while swaps < nswap:
        if j == chunk:
            pairs = rng.choice(len(deg), size=(chunk, 2), p=p)
            picks = rng.random((chunk, 2))
            j = 0
        ui, xi = pairs[j]
        pv, py = picks[j]
        j += 1
        if ui == xi or not succ[ui] or not succ[xi]:
            continue
        vi = int(pv * len(succ[ui]))
        yi = int(py * len(succ[xi]))
        v, y = succ[ui][vi], succ[xi][yi]
        if v == y:
            continue
        if y not in succ_set[ui] and v not in succ_set[xi]:
            succ[ui][vi], succ[xi][yi] = y, v
            succ_set[ui].discard(v)
            succ_set[ui].add(y)
            succ_set[xi].discard(y)
            succ_set[xi].add(v)
            swaps += 1
        if n >= max_tries:
            break
        n += 1
    out = np.zeros_like(a)
    for i, t in enumerate(succ):
        out[i, t] = 1
    return out, swaps

Stimulated ROIs (from the later version), and the clock. If the stimulation times share the clock of the signals, the targeted ROI responds after the stimulation onset and not 15 s later (half-way between stimulations, which come every 30 s). A shift of the times that does not change the response would mean the times are on another clock.

In [10]:
n_ids = n_lab = n_head = 0
own = {0.0: [], 15.0: [], -15.0: []}
per_session = []
for s in sessions:
    ids = s["later"]["ids"]
    assert np.allclose(s["later"]["start"], s["stim_start"])
    labs = nw.stimulated_labels(s)
    n_ids += int(np.isfinite(ids).sum())
    n_lab += sum(1 for x in labs if x)
    n_head += sum(1 for x in labs if x in name_set)
    r = {}
    for sh in own:
        R = nw.responses(s, shift_s=sh)
        vals = [R[k, int(i)] for k, i in enumerate(ids) if np.isfinite(i)]
        own[sh] += vals
        r[sh] = np.nanmedian(vals) if len(vals) else np.nan
    per_session.append(r)
print(f"stimulations {survey.n_stim.sum()}; with a targeted ROI id {n_ids}; "
      f"the ROI has a label {n_lab}; the label is a head neuron name {n_head}")
for sh, v in own.items():
    print(f"targeted ROI, dF/F over 30 s after onset shifted by {sh:+.0f} s: median "
          f"{np.nanmedian(v):.3f}, n = {np.isfinite(v).sum()}")
ps = pd.DataFrame(per_session)
ok = ps[[0.0, 15.0]].dropna()
print(f"recordings where the targeted ROIs respond more at the true onset than 15 s later: "
      f"{(ok[0.0] > ok[15.0]).sum()} of {len(ok)}; "
      f"recordings with no targeted ROI id: {ps[0.0].isna().sum()}")
w = stats.wilcoxon(np.array(own[0.0]), np.array(own[15.0]), nan_policy="omit")
print(f"paired Wilcoxon, true onset against +15 s: p = {w.pvalue:.2g}")
stimulations 5614; with a targeted ROI id 2815; the ROI has a label 2090; the label is a head neuron name 1813
targeted ROI, dF/F over 30 s after onset shifted by +0 s: median 0.204, n = 2812
targeted ROI, dF/F over 30 s after onset shifted by +15 s: median -0.092, n = 2812
targeted ROI, dF/F over 30 s after onset shifted by -15 s: median 0.110, n = 2807
recordings where the targeted ROIs respond more at the true onset than 15 s later: 108 of 108; recordings with no targeted ROI id: 2
paired Wilcoxon, true onset against +15 s: p = 0

Checks of the description against the data. The archive lists 113 recordings with raw imaging and 110 with segmentation files; the three without (sub-20, sub-23, sub-33) cannot be used. All 110 are wild type (genotype WT); 108 give the strain AML462 and two (sub-24, sub-25) give "none". The volume rate is one per 0.501 s in every file, stimulations come every 30.8 s (median) and last 0.5 s, as the stimulation table's description says (every 30 s, 500 ms). No recording is deposited twice. The stimulation times share the clock of the signals: the targeted ROI responds after the true onset (median dF/F 0.204) and not 15 s later (-0.092), in 108 of the 108 recordings with targeted ROI ids. Two things in the files differ from what they say. The cited version's GreenSignal is described as the measured fluorescence, but the later version shows that 17% to 68% of its values per file (mean 42%) are frames that were not measured and were filled by interpolation, with nothing in the cited files to mark them. And the cited version does not say which ROI each stimulation targeted; the later version does, for 2815 of the 5614 stimulations. Of the labels of activity ROIs, 6659 are head neuron names, 487 name a bilateral class without its side, and 307 are numbers or other text ("target", "AMso", "AWCON"), with no description of what they mean. pynwb 4.2.0 cannot build the files. Of the outside sources, the atlas pickle holds the names, the fitted kernels (ec) and the scalar atlas thresholded at q < 0.05, and neither its repository nor pumpprobe nor the paper's code holds a q-value matrix or an unthresholded atlas (the TSV is a scalar export of 300 neurons). The class and role lists of the helper are the same as those written in the paper's code.

atlas-dataset-link¶

The signaling network of the released atlas (Randi et al. 2023, wild type, q < 0.05) can be matched to the dandiset's recordings: its neurons are named as the dandiset's labels, its edges are pairs the recordings measured, and its response amplitudes agree with the responses in the recordings.

Records are matched by neuron name. For each stimulation whose targeted ROI carries a head neuron label (neuron j), every other labeled head-neuron ROI i of the same recording is an occurrence of the pair (j to i), and its response is the mean dF/F over the 30 s after onset against the 10 s before. The atlas value is scalar_atlas[i, j].

In [11]:
A = nw.signaling_adjacency(scalar_atlas)          # A[j, i]: stimulated j to responding i
occ = np.zeros((N, N), int)                       # occ[i, j]: i observed when j stimulated
resp_sum = np.zeros((N, N))
resp_n = np.zeros((N, N), int)
stim_count = np.zeros(N, int)
obs_count = np.zeros(N, int)                      # recordings with an activity ROI labeled i
obs_np = np.zeros(N, int)                         # recordings with a NeuroPAL ROI labeled i
for s in sessions:
    heads = [(c, idx[l]) for c, l in enumerate(s["roi_label"]) if l in name_set]
    for a in {a for _, a in heads}:
        obs_count[a] += 1
    for a in {idx[l] for l in s["np_labels"] if l in name_set}:
        obs_np[a] += 1
    R = nw.responses(s)
    for k, (lab, roi) in enumerate(zip(nw.stimulated_labels(s), s["later"]["ids"])):
        if lab not in name_set:
            continue
        j = idx[lab]
        stim_count[j] += 1
        seen = set()
        for c, a in heads:
            if c == int(roi) or a == j or a in seen:
                continue
            seen.add(a)
            occ[a, j] += 1
            if np.isfinite(R[k, c]):
                resp_sum[a, j] += R[k, c]
                resp_n[a, j] += 1
mean_resp = np.where(resp_n > 0, resp_sum / np.maximum(resp_n, 1), np.nan)
edge = A.T.astype(bool)                           # edge[i, j], the atlas orientation
print("atlas neurons named as dandiset labels:", sum(n in {l for s in sessions for l in s['roi_label']}
                                                    for n in names), "of", N)
print(f"atlas edges {edge.sum()}; with at least one occurrence in the dandiset: "
      f"{(occ[edge] > 0).sum()} ({(occ[edge] > 0).mean():.3f})")
print(f"same check with the atlas transposed (edges read as responding to stimulated): "
      f"{(occ[edge.T] > 0).mean():.3f}")
print("occurrences per atlas edge: median", np.median(occ[edge]), "range", occ[edge].min(),
      "to", occ[edge].max())
obs_pairs = (occ > 0) & ~np.eye(N, dtype=bool)
print("pairs the dandiset measured at least once:", obs_pairs.sum(), "; of them atlas edges:",
      (obs_pairs & edge).sum())
m = edge & np.isfinite(mean_resp)
rho = stats.spearmanr(scalar_atlas[m], mean_resp[m])
print(f"atlas amplitude against the dandiset's mean dF/F over {m.sum()} atlas edges: "
      f"Spearman rho = {rho.statistic:.3f}, p = {rho.pvalue:.2g}")
ne = obs_pairs & ~edge & np.isfinite(mean_resp)
mw = stats.mannwhitneyu(np.abs(mean_resp[m]), np.abs(mean_resp[ne]), alternative="greater")
print(f"|mean dF/F|: atlas edges median {np.median(np.abs(mean_resp[m])):.3f} (n = {m.sum()}), "
      f"measured non-edges median {np.median(np.abs(mean_resp[ne])):.3f} (n = {ne.sum()}); "
      f"Mann-Whitney (edges greater) p = {mw.pvalue:.2g}")
# Orientation: out-degree should follow the number of stimulations, in-degree the observations.
outdeg, indeg = A.sum(1), A.sum(0)
for lab_, x, y in (("out-degree vs stimulations", outdeg, stim_count),
                   ("in-degree vs stimulations", indeg, stim_count),
                   ("in-degree vs observations", indeg, obs_count),
                   ("out-degree vs observations", outdeg, obs_count)):
    r_ = stats.spearmanr(x, y)
    print(f"{lab_}: Spearman {r_.statistic:.3f}")
asym = (edge & ~edge.T & (occ > 0) & (occ.T > 0) & np.isfinite(mean_resp)
        & np.isfinite(mean_resp.T))
fr = (np.abs(mean_resp[asym]) > np.abs(mean_resp.T[asym])).mean()
print(f"atlas edges j to i without the reverse edge, both directions measured ({asym.sum()} "
      f"pairs): |response of i to j| exceeds |response of j to i| in {fr:.3f}")
print("neurons never stimulated with a label in the dandiset:", (stim_count == 0).sum(),
      "; their atlas out-degree total:", outdeg[stim_count == 0].sum())
atlas neurons named as dandiset labels: 184 of 188
atlas edges 1154; with at least one occurrence in the dandiset: 1020 (0.884)
same check with the atlas transposed (edges read as responding to stimulated): 0.870
occurrences per atlas edge: median 6.0 range 0 to 62
pairs the dandiset measured at least once: 22761 ; of them atlas edges: 1020
atlas amplitude against the dandiset's mean dF/F over 1020 atlas edges: Spearman rho = 0.524, p = 3.7e-73
|mean dF/F|: atlas edges median 0.074 (n = 1020), measured non-edges median 0.042 (n = 21738); Mann-Whitney (edges greater) p = 1.7e-45
out-degree vs stimulations: Spearman 0.634
in-degree vs stimulations: Spearman 0.608
in-degree vs observations: Spearman 0.604
out-degree vs observations: Spearman 0.592
atlas edges j to i without the reverse edge, both directions measured (697 pairs): |response of i to j| exceeds |response of j to i| in 0.626
neurons never stimulated with a label in the dandiset: 23 ; their atlas out-degree total: 46
In [12]:
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
ax[0].scatter(scalar_atlas[m], mean_resp[m], s=6)
ax[0].set_xlabel("atlas amplitude")
ax[0].set_ylabel("dandiset mean dF/F (0 to 30 s)")
ax[0].set_xlim(-1, 3)
ax[0].set_ylim(-1, 3)
ax[1].hist([np.abs(mean_resp[m]), np.abs(mean_resp[ne])], bins=np.linspace(0, 2, 41),
           density=True, label=["atlas edges", "measured non-edges"])
ax[1].set_xlabel("|mean dF/F|")
ax[1].legend()
plt.tight_layout()
plt.show()
print("points outside the left axes:", int(((scalar_atlas[m] < -1) | (scalar_atlas[m] > 3)
                                         | (mean_resp[m] < -1) | (mean_resp[m] > 3)).sum()),
      "; values above 2 outside the right histogram:",
      int((np.abs(mean_resp[m]) > 2).sum() + (np.abs(mean_resp[ne]) > 2).sum()))
No description has been provided for this image
points outside the left axes: 4 ; values above 2 outside the right histogram: 39

Result: partially reproduced. The amplitude tests hold: over the 1020 atlas edges the dandiset measured, the atlas amplitude ranks with the recordings' mean dF/F (Spearman rho 0.524), and atlas edges respond more than measured non-edges (median |dF/F| 0.074 against 0.042). The coverage tests fail: 184 of the 188 atlas neurons are among the activity ROIs' labels, and 1020 of the 1154 atlas edges (0.884) have an occurrence, below the 95% asked. The dandiset gives a targeted ROI for 2815 of its 5614 stimulations, 1813 of them a head neuron label, and 23 neurons never appear as a labeled target although the atlas gives them 46 out-edges; the atlas rests on stimulation identities that the dandiset does not hold in full. Asymmetric edges support the stimulated-to-responding orientation (0.626 respond more in the atlas direction); the degree correlations barely separate the two orientations.

signaling-network-size¶

The binarized signaling network of the 188 head neurons, with an edge for each pair whose q-value is below 0.05, has 1151 edges and a density of 0.033.

Reading (a), q-values recomputed from the dandiset, cannot be run: Randi et al.'s q-values test each pair's responses against a null distribution from control recordings without stimulation (pumpprobe Funatlas.get_ctrl_distributions, kstest against ctrl_dff and ctrl_sd), and those recordings are not in the dandiset (all 110 recordings have stimulations, see the data check). Reading (b) uses the released atlas.

In [13]:
n_edges = int(A.sum())
dens = nw.density(A)
print(f"reading (b): {N} neurons, {n_edges} edges (expected 1151 +/- 115), density {dens:.4f} "
      f"(expected 0.033 +/- 0.0033)")
print("self-edges dropped:", int(np.isfinite(np.diag(scalar_atlas)).sum()))
print("reading (a): not run, the control recordings are not in the dandiset")
reading (b): 188 neurons, 1154 edges (expected 1151 +/- 115), density 0.0328 (expected 0.033 +/- 0.0033)
self-edges dropped: 188
reading (a): not run, the control recordings are not in the dandiset

Result: reproduced under reading (b). The atlas has 1154 edges among the 188 head neurons, density 0.0328, both within tolerance; 3 edges more than the paper's 1151.

signaling-clustering-small-world¶

The signaling network has an average clustering coefficient of 0.13 and is small world, with a small-world coefficient of 4.76.

As in motifs.py: 100 directed Erdos-Renyi graphs at density 0.033.

In [14]:
cid = "signaling-clustering-small-world"
sw_runs = {}
for off in OFFSETS:
    sw_runs[off] = nw.small_world(A, 0.033, np.random.default_rng(seed_of(cid) + off))
sw = pd.DataFrame(sw_runs).T
sw.index.name = "seed offset"
print(sw.round(4))
print(f"claim's seed: C = {sw.loc[0, 'C']:.4f} (expected 0.13 +/- 0.013), sigma = "
      f"{sw.loc[0, 'sigma']:.3f} (expected 4.76 +/- 0.48); sigma over five seeds "
      f"{sw.sigma.min():.3f} to {sw.sigma.max():.3f}")
                  C      L    C_ER    L_ER   sigma
seed offset                                       
0            0.1347  2.648  0.0334  3.0372  4.6241
1000         0.1347  2.648  0.0329  3.0476  4.7155
2000         0.1347  2.648  0.0331  3.0497  4.6881
3000         0.1347  2.648  0.0329  3.0455  4.7084
4000         0.1347  2.648  0.0330  3.0424  4.6918
claim's seed: C = 0.1347 (expected 0.13 +/- 0.013), sigma = 4.624 (expected 4.76 +/- 0.48); sigma over five seeds 4.624 to 4.715

Result: reproduced. The clustering coefficient is 0.135 and sigma about 4.6, above 1 and within tolerance under all five seeds.

anatomy-network-properties (elsewhere)¶

The binarized anatomical network has 3250 edges, a density of 0.092, an average clustering coefficient of 0.3 and a small-world coefficient of 2.52.

The four EM datasets are not named in the paper. The main reading uses the four sources of Randi et al.'s code (White 1986 whole adult, White 1986 L4, Witvliet 2021 datasets 7 and 8), with gap junctions in both directions. Variants: White 1986 adult N2U (white_1986_A) in place of the whole-animal White adult, and gap junctions only in the direction listed.

In [15]:
cid = "anatomy-network-properties"
anat_src = nw.load_anatomy(names)
B = nw.anatomy_adjacency(anat_src, "any")
rows = {}
for off in OFFSETS:
    rows[off] = nw.small_world(B, 0.092, np.random.default_rng(seed_of(cid) + off))
swa = pd.DataFrame(rows).T
swa.index.name = "seed offset"
print(f"main reading: {int(B.sum())} edges (expected 3250 +/- 325), density {nw.density(B):.4f} "
      f"(0.092 +/- 0.0092)")
print(swa.round(4))
variants = {
    "White A (N2U) for White whole": nw.load_anatomy(
        names, ["aconnectome_white_1986_A.csv"] + nw.ANATOMY_SOURCES[1:]),
    "gap junctions one direction": nw.load_anatomy(names, symmetrize_gaps=False),
}
for k, src_ in variants.items():
    Bv = nw.anatomy_adjacency(src_, "any")
    swv = nw.small_world(Bv, 0.092, np.random.default_rng(seed_of(cid)))
    print(f"variant {k}: {int(Bv.sum())} edges, density {nw.density(Bv):.4f}, "
          f"C {swv['C']:.4f}, sigma {swv['sigma']:.3f}")
main reading: 3223 edges (expected 3250 +/- 325), density 0.0917 (0.092 +/- 0.0092)
                  C       L    C_ER    L_ER   sigma
seed offset                                        
0            0.3063  2.7525  0.0922  2.0840  2.5152
1000         0.3063  2.7525  0.0922  2.0839  2.5137
2000         0.3063  2.7525  0.0917  2.0851  2.5298
3000         0.3063  2.7525  0.0924  2.0828  2.5085
4000         0.3063  2.7525  0.0922  2.0844  2.5144
variant White A (N2U) for White whole: 2893 edges, density 0.0823, C 0.2330, sigma 2.934
variant gap junctions one direction: 2960 edges, density 0.0842, C 0.2773, sigma 2.212

Result: reproduced, resting on the choice of the four EM datasets. With the sources of Randi et al.'s code the network has 3223 edges, density 0.092, clustering 0.306 and sigma about 2.5, all within tolerance. The paper does not name its four datasets; under the variants the outcome changes: with the White N2U adult in place of the whole-animal White adult, all four values fall outside tolerance (2893 edges, density 0.0823 below 0.0828, clustering 0.233, sigma 2.93), and with gap junctions in one direction sigma (2.21) does.

triad-distribution¶

The signaling and anatomical networks differ in their distribution of the 13 triad motifs, each compared with Erdos-Renyi graphs of matched density.

Counts of the 13 connected triad types (networkx triadic_census, the same counts as triads_by_type) in each network and averaged over five Erdos-Renyi graphs at each density (Extended Data Figure 1 legend; motifs_ER.py). The chi-square test of the 13 x 2 table is the claims file's choice.

In [16]:
cid = "triad-distribution"
tri = pd.DataFrame({"signaling": nw.triad_counts(A), "anatomy": nw.triad_counts(B)})
rng = np.random.default_rng(seed_of(cid))
for lab_, p in (("ER 0.033", 0.033), ("ER 0.092", 0.092)):
    ers = [nw.triad_counts(nx.to_numpy_array(nx.erdos_renyi_graph(N, p, directed=True,
                                                                     seed=int(rng.integers(2**31)))))
           for _ in range(5)]
    tri[lab_ + " mean of 5"] = pd.DataFrame(ers).mean().round(1)
tri["signaling / ER"] = (tri["signaling"] / tri["ER 0.033 mean of 5"]).round(2)
tri["anatomy / ER"] = (tri["anatomy"] / tri["ER 0.092 mean of 5"]).round(2)
print(tri)
chi = stats.chi2_contingency(tri[["signaling", "anatomy"]].to_numpy())
print(f"chi-square on the proportions of the 13 types: chi2 = {chi.statistic:.1f}, "
      f"dof = {chi.dof}, p = {chi.pvalue:.3g}")
for lab_, src_ in variants.items():
    tv = pd.Series(nw.triad_counts(nw.anatomy_adjacency(src_, "any")))
    cv = stats.chi2_contingency(np.c_[tri["signaling"].to_numpy(), tv.to_numpy()])
    print(f"variant {lab_}: chi2 = {cv.statistic:.1f}, p = {cv.pvalue:.3g}")
prop = tri[["signaling", "anatomy"]] / tri[["signaling", "anatomy"]].sum()
print("proportions:")
print(prop.round(3))
      signaling  anatomy  ER 0.033 mean of 5  ER 0.092 mean of 5  signaling / ER  anatomy / ER
021D       3058     5606              3090.4             19142.0            0.99          0.29
021U       2671     7195              3132.0             19070.4            0.85          0.38
021C       3990     6751              6274.8             38196.0            0.64          0.18
111D       1384    11056               232.8              4129.0            5.95          2.68
111U       1652    10231               239.6              4178.2            6.89          2.45
030T        508     1697               216.8              3905.8            2.34          0.43
030C         60       48                75.8              1302.8            0.79          0.04
201         234     6239                 4.2               218.6           55.71         28.54
120D        157     1388                 3.4               226.0           46.18          6.14
120U        159     1485                 4.8               203.2           33.12          7.31
120C        150      596                10.0               433.4           15.00          1.38
210         173     2020                 0.0                44.6             inf         45.29
300          49      826                 0.0                 1.2             inf        688.33
chi-square on the proportions of the 13 types: chi2 = 6008.6, dof = 12, p = 0
variant White A (N2U) for White whole: chi2 = 5846.0, p = 0
variant gap junctions one direction: chi2 = 2194.0, p = 0
proportions:
      signaling  anatomy
021D      0.215    0.102
021U      0.188    0.130
021C      0.280    0.122
111D      0.097    0.201
111U      0.116    0.186
030T      0.036    0.031
030C      0.004    0.001
201       0.016    0.113
120D      0.011    0.025
120U      0.011    0.027
120C      0.011    0.011
210       0.012    0.037
300       0.003    0.015

Result: reproduced. The proportions of the 13 triad types differ between the two networks (chi2 = 6008.6 on 12 degrees of freedom, p printed as 0), also under both anatomical variants. Relative to Erdos-Renyi graphs of matched density, the signaling network keeps the open two-edge triads near chance (021D 0.99, 021U 0.85 times the ER count) while anatomy has fewer than chance (0.29, 0.38), and anatomy has 688 times the ER count of fully connected triads (300).

ed6-signaling-not-feedforward¶

The signaling network is not appreciably feed-forward along the sensory to inter- to motor neuron path compared with shuffle controls.

For each leg, log(N forward / N backward) against (b) 1000 shuffles of the class labels keeping class sizes (SIM.py) and (c) 1000 networks rewired by the edge swap of SIM_doubleedge.py (2000 swaps in at most 4000 counted attempts, as its line 237 calls it), by a two-sided t-test of the observed value against the null values. Classes are the code's lists. The code's other measure, the log ratio of the fractions of each class's out-edges, is a variant.

In [17]:
cls = np.array(["S" if n in nw.SENSORY else "I" if n in nw.INTER else "M" for n in names])
print("class sizes:", collections.Counter(cls))


def feedforward_test(adj, claim_id, n_null=1000, offset=0, nswap=2000, max_tries=4000):
    obs = nw.feedforward_measures(nw.class_flow(adj, cls))
    rng_b = np.random.default_rng(seed_of(claim_id) + offset)
    rng_c = np.random.default_rng(seed_of(claim_id, 1) + offset)
    null_b, null_c, n_swaps = [], [], []
    for _ in range(n_null):
        null_b.append(nw.feedforward_measures(nw.class_flow(adj, rng_b.permutation(cls))))
        sw, n_sw = nw.swapping_edges(adj, rng_c, nswap, max_tries)
        n_swaps.append(n_sw)
        null_c.append(nw.feedforward_measures(nw.class_flow(sw, cls)))
    rows = []
    for ctrl, null in (("label shuffle", pd.DataFrame(null_b)), ("edge swap", pd.DataFrame(null_c))):
        for meas in ("count", "frac"):
            for leg in ("SI", "IM", "SM"):
                k = f"{meas}_{leg}"
                v = null[k].replace([np.inf, -np.inf], np.nan).dropna()
                t_ = stats.ttest_ind(obs[k], v.to_numpy(), alternative="two-sided")
                rows.append(dict(control=ctrl, measure=meas, leg=leg, observed=obs[k],
                                 null_mean=v.mean(), null_sd=v.std(), n_null=len(v),
                                 z=(obs[k] - v.mean()) / v.std(), p=t_.pvalue,
                                 above=bool(t_.pvalue < 0.05 and obs[k] > v.mean())))
    return pd.DataFrame(rows), nw.class_flow(adj, cls), np.array(n_swaps)


def swap_summary(n_swaps, nswap):
    return (f"swaps per edge-swap null network: min {n_swaps.min()}, median {np.median(n_swaps):.0f}, "
            f"max {n_swaps.max()}; {int((n_swaps < nswap).sum())} of {len(n_swaps)} stopped at max_tries "
            f"before {nswap}")
class sizes: Counter({np.str_('I'): 72, np.str_('S'): 70, np.str_('M'): 46})
In [18]:
cid = "ed6-signaling-not-feedforward"
t = time.time()
ff_sig, flow_sig, nsw_sig = feedforward_test(A, cid)
print("edge counts between classes (row source, column target):")
print(pd.DataFrame([[flow_sig[s + u] for u in "SIM"] for s in "SIM"], index=list("SIM"),
                   columns=list("SIM")))
print(ff_sig.round(4).to_string())
print(swap_summary(nsw_sig, 2000), f"(the network has {int(A.sum())} edges)")
main = ff_sig[ff_sig.measure == "count"]
print("legs significantly above the null (count measure):",
      main[main.above][["control", "leg"]].values.tolist())
print(f"({time.time() - t:.0f} s)")
seed_rows = []
for off in OFFSETS[1:]:
    r_, _, nsw_ = feedforward_test(A, cid, offset=off)
    rc = r_[r_.measure == "count"]
    rf = r_[r_.measure == "frac"]
    seed_rows.append(dict(offset=off, count_legs_above=int(rc.above.sum()),
                          count_max_p=rc.p.max(), count_min_p=rc.p.min(),
                          frac_legs_above=int(rf.above.sum()), frac_min_p=rf.p.min(),
                          min_swaps=nsw_.min()))
print("other seeds (count and fraction measures):")
print(pd.DataFrame(seed_rows).round(6).to_string(index=False))
edge counts between classes (row source, column target):
     S    I    M
S  237  100   84
I  154  141  102
M  122  111  103
          control measure leg  observed  null_mean  null_sd  n_null       z       p  above
0   label shuffle   count  SI   -0.4318    -0.0059   0.1631    1000 -2.6105  0.0092  False
1   label shuffle   count  IM   -0.0846    -0.0032   0.1944    1000 -0.4183  0.6759  False
2   label shuffle   count  SM   -0.3732    -0.0024   0.1932    1000 -1.9196  0.0553  False
3   label shuffle    frac  SI   -0.4905     0.0179   0.1601    1000 -3.1745  0.0016  False
4   label shuffle    frac  IM   -0.2514    -0.4452   0.1837    1000  1.0548  0.2920  False
5   label shuffle    frac  SM   -0.5987    -0.4206   0.1950    1000 -0.9136  0.3614  False
6       edge swap   count  SI   -0.4318    -0.3237   0.0578    1000 -1.8685  0.0621  False
7       edge swap   count  IM   -0.0846    -0.0343   0.0833    1000 -0.6028  0.5470  False
8       edge swap   count  SM   -0.3732    -0.3505   0.0696    1000 -0.3269  0.7439  False
9       edge swap    frac  SI   -0.4905    -0.3824   0.0578    1000 -1.8685  0.0621  False
10      edge swap    frac  IM   -0.2514    -0.2011   0.0833    1000 -0.6028  0.5470  False
11      edge swap    frac  SM   -0.5987    -0.5760   0.0696    1000 -0.3269  0.7439  False
swaps per edge-swap null network: min 2000, median 2000, max 2000; 0 of 1000 stopped at max_tries before 2000 (the network has 1154 edges)
legs significantly above the null (count measure): []
(6 s)
other seeds (count and fraction measures):
 offset  count_legs_above  count_max_p  count_min_p  frac_legs_above  frac_min_p  min_swaps
   1000                 0     0.704359     0.006304                0    0.001325       2000
   2000                 0     0.698290     0.010917                0    0.001993       2000
   3000                 0     0.691065     0.014828                0    0.001111       2000
   4000                 0     0.702450     0.010581                0    0.001224       2000

Result: reproduced. No leg is significantly above either null for the count measure (label shuffle p = 0.0092, 0.68, 0.055; edge swap p = 0.062, 0.55, 0.74), nor for the code's fraction measure; under each of the four other seeds no leg is above for either measure (count measure smallest p 0.0063 to 0.0148, fraction measure 0.0011 to 0.0020, all for values below the null). Every edge-swap null network received its 2000 swaps. The observed values are all negative: the sensory to inter leg is significantly below the label-shuffle null (z = -2.61), more backward than forward.

ed6-anatomy-feedforward (elsewhere)¶

Anatomical synaptic edges are enriched in a feed-forward direction from sensory to inter- to motor neurons.

The claims file gives no criterion for this claim; the paper's test is the one of ed6-signaling-not-feedforward (Extended Data Figure 6 b, c; SIM.py and SIM_doubleedge.py run both networks the same way), applied to the anatomical network. The edge swap makes 6000 swaps in at most 9000 counted attempts, as SIM_doubleedge.py (line 493) calls it for the anatomical network.

In [19]:
cid = "ed6-anatomy-feedforward"
ff_an, flow_an, nsw_an = feedforward_test(B, cid, nswap=6000, max_tries=9000)
print(pd.DataFrame([[flow_an[s + u] for u in "SIM"] for s in "SIM"], index=list("SIM"),
                   columns=list("SIM")))
print(ff_an.round(4).to_string())
print(swap_summary(nsw_an, 6000), f"(the network has {int(B.sum())} edges)")
seed_rows = []
for off in OFFSETS[1:]:
    r_, _, nsw_ = feedforward_test(B, cid, offset=off, nswap=6000, max_tries=9000)
    rc = r_[r_.measure == "count"]
    seed_rows.append(dict(offset=off, legs_above=int(rc.above.sum()),
                          legs_above_list=rc[rc.above].apply(lambda x: f"{x.control}:{x.leg}", axis=1).tolist(),
                          min_swaps=nsw_.min()))
print("other seeds (count measure):")
print(pd.DataFrame(seed_rows).to_string())
for lab_, src_ in variants.items():
    r_, _, nsw_ = feedforward_test(nw.anatomy_adjacency(src_, "any"), cid, nswap=6000, max_tries=9000)
    rc = r_[r_.measure == "count"]
    print(f"variant {lab_}: legs above the null:",
          rc[rc.above].apply(lambda x: f"{x.control}:{x.leg}", axis=1).tolist())
    print("   ", rc[["control", "leg", "z", "p"]].round(4).values.tolist())
    print("   ", swap_summary(nsw_, 6000))
     S    I    M
S  440  600  255
I  354  662  333
M   69  252  258
          control measure leg  observed  null_mean  null_sd  n_null        z       p  above
0   label shuffle   count  SI    0.5276    -0.0009   0.1106    1000   4.7770  0.0000   True
1   label shuffle   count  IM    0.2787    -0.0035   0.1227    1000   2.2994  0.0218   True
2   label shuffle   count  SM    1.3072     0.0005   0.1292    1000  10.1165  0.0000   True
3   label shuffle    frac  SI    0.5685     0.0237   0.1081    1000   5.0389  0.0000   True
4   label shuffle    frac  IM   -0.5671    -0.4515   0.1238    1000  -0.9336  0.3510  False
5   label shuffle    frac  SM    0.5022    -0.4228   0.1281    1000   7.2219  0.0000   True
6       edge swap   count  SI    0.5276     0.5143   0.0294    1000   0.4532  0.6507  False
7       edge swap   count  IM    0.2787     0.2538   0.0414    1000   0.6024  0.5473  False
8       edge swap   count  SM    1.3072     0.8060   0.0603    1000   8.3076  0.0000   True
9       edge swap    frac  SI    0.5685     0.5552   0.0294    1000   0.4532  0.6507  False
10      edge swap    frac  IM   -0.5671    -0.5920   0.0414    1000   0.6024  0.5473  False
11      edge swap    frac  SM    0.5022     0.0010   0.0603    1000   8.3076  0.0000   True
swaps per edge-swap null network: min 6000, median 6000, max 6000; 0 of 1000 stopped at max_tries before 6000 (the network has 3223 edges)
other seeds (count measure):
   offset  legs_above                                                       legs_above_list  min_swaps
0    1000           4  [label shuffle:SI, label shuffle:IM, label shuffle:SM, edge swap:SM]       6000
1    2000           4  [label shuffle:SI, label shuffle:IM, label shuffle:SM, edge swap:SM]       6000
2    3000           4  [label shuffle:SI, label shuffle:IM, label shuffle:SM, edge swap:SM]       6000
3    4000           4  [label shuffle:SI, label shuffle:IM, label shuffle:SM, edge swap:SM]       6000
variant White A (N2U) for White whole: legs above the null: ['label shuffle:SI', 'label shuffle:SM', 'edge swap:SM']
    [['label shuffle', 'SI', 4.5438, 0.0], ['label shuffle', 'IM', 1.4753, 0.1407], ['label shuffle', 'SM', 8.9907, 0.0], ['edge swap', 'SI', -0.2693, 0.7878], ['edge swap', 'IM', -0.8673, 0.3862], ['edge swap', 'SM', 6.7519, 0.0]]
    swaps per edge-swap null network: min 6000, median 6000, max 6000; 0 of 1000 stopped at max_tries before 6000
variant gap junctions one direction: legs above the null: ['label shuffle:SI', 'label shuffle:IM', 'label shuffle:SM', 'edge swap:SM']
    [['label shuffle', 'SI', 4.3592, 0.0], ['label shuffle', 'IM', 2.7059, 0.007], ['label shuffle', 'SM', 9.5801, 0.0], ['edge swap', 'SI', 0.549, 0.5833], ['edge swap', 'IM', 0.7497, 0.4538], ['edge swap', 'SM', 7.2957, 0.0]]
    swaps per edge-swap null network: min 6000, median 6000, max 6000; 0 of 1000 stopped at max_tries before 6000

Result: partially reproduced. Against shuffled class labels all three legs are significantly feed-forward (z = 4.78, 2.30 and 10.12). Against the edge-swap control, with 6000 swaps per null network as the code makes for the anatomical network, only the sensory to motor leg is (z = 8.31); sensory to inter (z = 0.45, p = 0.65) and inter to motor (z = 0.60, p = 0.55) are not. The same legs come out under all five seeds and with gap junctions in one direction; with the White N2U adult the inter to motor leg is not above the label shuffle either (z = 1.48, p = 0.14). The criterion, every leg above both nulls for reproduced and some for partial, is the author's, as the claims file gives none.

fig4c-broadcaster-integrator¶

In the signaling network pharyngeal neurons act as broadcasters, with more outgoing than incoming edges, and amphid sensory neurons have more incoming than outgoing edges, each compared with shuffled role assignments.

As in broadcaster_integrator.py: edges into each group from outside over edges out of it to outside, against 1000 random disjoint pairs of groups of 20 and 24 neurons; one-sided t-tests (pharynx lower than the null, amphid higher).

In [20]:
cid = "fig4c-broadcaster-integrator"
ph = np.isin(names, nw.PHARYNX)
am = np.isin(names, nw.AMPHID)
print("group sizes in the atlas:", ph.sum(), am.sum())


def broadcaster(adj, offset=0, n_null=1000):
    rng_ = np.random.default_rng(seed_of(cid) + offset)
    ip, op = nw.boundary_ratio(adj, ph)
    ia, oa = nw.boundary_ratio(adj, am)
    null_p, null_a = [], []
    for _ in range(n_null):
        perm = rng_.permutation(N)
        gp = np.zeros(N, bool)
        gp[perm[:ph.sum()]] = True
        ga = np.zeros(N, bool)
        ga[perm[ph.sum():ph.sum() + am.sum()]] = True
        i_, o_ = nw.boundary_ratio(adj, gp)
        null_p.append(i_ / o_ if o_ else np.nan)
        i_, o_ = nw.boundary_ratio(adj, ga)
        null_a.append(i_ / o_ if o_ else np.nan)
    null_p, null_a = np.array(null_p), np.array(null_a)
    pp_ = stats.ttest_ind(ip / op, null_p[np.isfinite(null_p)], alternative="less").pvalue
    pa_ = stats.ttest_ind(ia / oa, null_a[np.isfinite(null_a)], alternative="greater").pvalue
    return dict(ph_in=ip, ph_out=op, ph_ratio=ip / op, ph_null_mean=np.nanmean(null_p),
                ph_null_sd=np.nanstd(null_p), ph_p=pp_, am_in=ia, am_out=oa, am_ratio=ia / oa,
                am_null_mean=np.nanmean(null_a), am_null_sd=np.nanstd(null_a), am_p=pa_,
                null_dropped=int((~np.isfinite(null_p)).sum() + (~np.isfinite(null_a)).sum()))


bi = pd.DataFrame({off: broadcaster(A, off) for off in OFFSETS}).T
bi.index.name = "seed offset"
print(bi.T.to_string())
group sizes in the atlas: 20 24
seed offset         0           1000        2000        3000        4000
ph_in          40.000000   40.000000   40.000000   40.000000   40.000000
ph_out         60.000000   60.000000   60.000000   60.000000   60.000000
ph_ratio        0.666667    0.666667    0.666667    0.666667    0.666667
ph_null_mean    1.016740    1.026561    1.029654    1.043002    1.021130
ph_null_sd      0.240476    0.230902    0.230832    0.229875    0.231083
ph_p            0.073089    0.059884    0.058256    0.051130    0.062871
am_in         160.000000  160.000000  160.000000  160.000000  160.000000
am_out        100.000000  100.000000  100.000000  100.000000  100.000000
am_ratio        1.600000    1.600000    1.600000    1.600000    1.600000
am_null_mean    1.030452    1.030169    1.019777    1.021507    1.023465
am_null_sd      0.218056    0.223020    0.205982    0.208315    0.210015
am_p            0.004604    0.005421    0.002494    0.002818    0.003103
null_dropped    0.000000    0.000000    0.000000    0.000000    0.000000

Result: partially reproduced. Amphid sensory neurons have more incoming than outgoing boundary edges (160 against 100, ratio 1.60 against a null mean of 1.03, p = 0.0046). Pharyngeal neurons have more outgoing than incoming boundary edges (60 against 40, ratio 0.67 against a null mean of 1.02), but the one-sided t-test gives p = 0.073, above 0.05; under the other four seeds p is 0.051 to 0.063, so the outcome does not depend on the seed.

ed9-sampling-not-confound¶

Pharyngeal neurons were not stimulated more often than other neurons (Kolmogorov-Smirnov p = 0.9), and amphid neurons were not observed more often (p = 0.38).

Per neuron, the number of stimulations is the number of stimulation events whose targeted ROI carries its label (targeted ROI ids from version 0.240930.1859), and the number of observations the number of recordings in which an activity ROI carries its label (as pumpprobe get_times_i_observed counts them). Two-sample KS test of the group against all other head neurons (broadcaster_integrator.py). Variant: observations counted from the NeuroPAL labels.

In [21]:
ks_p = stats.ks_2samp(stim_count[~ph], stim_count[ph])
ks_a = stats.ks_2samp(obs_count[~am], obs_count[am])
ks_av = stats.ks_2samp(obs_np[~am], obs_np[am])
print(f"stimulations: pharynx median {np.median(stim_count[ph])} (range {stim_count[ph].min()} to "
      f"{stim_count[ph].max()}), others median {np.median(stim_count[~ph])}; KS D = "
      f"{ks_p.statistic:.3f}, p = {ks_p.pvalue:.3g}")
print(f"observations: amphid median {np.median(obs_count[am])} (range {obs_count[am].min()} to "
      f"{obs_count[am].max()}), others median {np.median(obs_count[~am])}; KS D = "
      f"{ks_a.statistic:.3f}, p = {ks_a.pvalue:.3g}")
print(f"variant, NeuroPAL observations: amphid median {np.median(obs_np[am])}, others "
      f"{np.median(obs_np[~am])}; KS p = {ks_av.pvalue:.3g}")
print("total stimulations counted:", stim_count.sum(), "; neurons with none:", (stim_count == 0).sum())
for g, nm in ((ph, "pharynx"), (am, "amphid")):
    print(f"{nm} neurons with no stimulation: {(stim_count[g] == 0).sum()} of {g.sum()}")
stimulations: pharynx median 6.5 (range 0 to 26), others median 6.5; KS D = 0.093, p = 0.994
observations: amphid median 27.5 (range 0 to 89), others median 32.0; KS D = 0.171, p = 0.518
variant, NeuroPAL observations: amphid median 49.0, others 46.0; KS p = 0.673
total stimulations counted: 1813 ; neurons with none: 23
pharynx neurons with no stimulation: 2 of 20
amphid neurons with no stimulation: 2 of 24

Result: reproduced. Pharyngeal neurons were not stimulated more often than the others (median 6.5 against 6.5, KS p = 0.994), and amphid neurons were not observed more often (median 27.5 against 32.0, KS p = 0.518; with the NeuroPAL count p = 0.673). The stimulation counts rest on the 1813 stimulations whose targeted ROI the later version identifies with a head neuron, a subset of the stimulations behind the atlas: 23 neurons (2 pharyngeal, 2 amphid) have no counted stimulation, yet the atlas gives them 46 out-edges.

fig5a-signaling-rich-club¶

The signaling network has a dual rich club, with 16 neurons of degree 25 or more and a more exclusive tier of five neurons of degree 40 or more, at local maxima of the normalized rich club coefficient.

Degree is in-degree plus out-degree; phi(k) over nodes of degree > k (richclub.py), normalized by its mean over 1000 degree-preserving rewired networks (Methods); the first 100 (legend) and 500 (code) of the same draws are variants. The rewiring stands in for graph-tool random_rewire(g, "configuration") (see the helper). Tiers (a) degree > 25 and > 40, (b) degree >= 25 and >= 40. A local maximum is a k whose normalized value is at least that of both neighbours and above at least one value within two steps (plateaus of equal values count once, at their first k).

In [22]:
deg = nw.total_degree(A)
degB = nw.total_degree(B)


def rich_club(adj, claim_id, n_null=1000, offset=0):
    rng_ = np.random.default_rng(seed_of(claim_id) + offset)
    phi = nw.rich_club_phi(adj)
    null = np.array([nw.rich_club_phi(nw.rewire_configuration(adj, rng_), len(phi))
                     for _ in range(n_null)])
    return phi, null


def local_maxima(x):
    out = []
    for k in range(1, len(x) - 1):
        if not np.isfinite(x[k]) or x[k] == x[k - 1]:
            continue
        nb = x[max(0, k - 2):k + 3]
        if x[k] >= np.nanmax([x[k - 1], x[k + 1]]) and np.nanmin(nb) < x[k]:
            # walk over a plateau to its end before comparing with the next distinct value
            e = k
            while e + 1 < len(x) and x[e + 1] == x[k]:
                e += 1
            if e + 1 >= len(x) or not np.isfinite(x[e + 1]) or x[e + 1] < x[k]:
                out.append(k)
    return out
In [23]:
cid = "fig5a-signaling-rich-club"
t = time.time()
phi, null = rich_club(A, cid)
print(f"1000 rewired networks in {time.time() - t:.0f} s")
ks = np.arange(len(phi))
table = pd.DataFrame({"k": ks, "N_k": [(deg > k).sum() for k in ks], "phi": phi})
for n_ in (1000, 500, 100):
    table[f"norm_{n_}"] = phi / np.nanmean(null[:n_], axis=0)
table["null_mean"] = np.nanmean(null, axis=0)
table["null_sd"] = np.nanstd(null, axis=0)
table["above_1sd"] = table.phi > table.null_mean + table.null_sd
print(table.round(3).to_string(index=False))
for n_ in (1000, 500, 100):
    print(f"local maxima of the normalized coefficient ({n_} nulls):",
          local_maxima(table[f"norm_{n_}"].to_numpy()))
defined = table[(table.k >= 3) & table.phi.notna() & table.null_mean.notna()]
print("phi minus the null mean, in null SDs, k = 3 to 6:",
      ((table.phi - table.null_mean) / table.null_sd).iloc[3:7].round(2).tolist(),
      "; phi minus null mean at k = 4:", f"{table.phi[4] - table.null_mean[4]:.2e}")
print("k >= 3 with phi above null mean + 1 SD:", int(defined.above_1sd.sum()), "of", len(defined),
      "; first k where it fails:", defined[~defined.above_1sd].k.tolist()[:5])
tier = {}
for rd, op in (("a", np.greater), ("b", np.greater_equal)):
    t1 = sorted(np.array(names)[op(deg, 25)])
    t2 = sorted(np.array(names)[op(deg, 40)])
    tier[rd] = (t1, t2)
    print(f"reading ({rd}): first tier {len(t1)} (expected 16 +/- 1.6), second tier {len(t2)} "
          f"(expected 5 +/- 0.5)")
    print("   ", t1)
    print("    second tier:", t2)
print("reading (a) first tier equals the code's list:", set(tier["a"][0]) == set(nw.CODE_RICH_CLUB))
rows = []
for off in OFFSETS[1:]:
    ph_, nu_ = rich_club(A, cid, offset=off)
    nm = ph_ / np.nanmean(nu_, axis=0)
    mx = local_maxima(nm)
    ab = ph_ > np.nanmean(nu_, axis=0) + np.nanstd(nu_, axis=0)
    ok_k = [k for k in range(3, len(ph_)) if np.isfinite(ph_[k]) and np.isfinite(np.nanmean(nu_[:, k]))]
    rows.append(dict(offset=off, maxima=mx, near25=any(abs(k - 25) <= 2 for k in mx),
                     near40=any(abs(k - 40) <= 2 for k in mx),
                     all_above_1sd=bool(all(ab[k] for k in ok_k))))
print(pd.DataFrame(rows).to_string(index=False))
1000 rewired networks in 2 s
 k  N_k   phi  norm_1000  norm_500  norm_100  null_mean  null_sd  above_1sd
 0  178 0.037      1.000     1.000     1.000      0.037    0.000      False
 1  170 0.040      1.000     1.000     1.000      0.040    0.000      False
 2  163 0.043      1.000     1.000     1.000      0.043    0.000      False
 3  150 0.049      1.001     1.001     1.001      0.049    0.000       True
 4  146 0.051      1.001     1.001     1.001      0.051    0.000      False
 5  132 0.059      1.004     1.004     1.004      0.058    0.000       True
 6  126 0.063      1.009     1.009     1.009      0.062    0.000       True
 7  116 0.070      1.022     1.022     1.022      0.069    0.000       True
 8  105 0.079      1.032     1.032     1.033      0.077    0.000       True
 9   98 0.085      1.035     1.035     1.035      0.082    0.000       True
10   87 0.096      1.040     1.040     1.040      0.093    0.001       True
11   81 0.103      1.042     1.041     1.042      0.099    0.001       True
12   75 0.113      1.059     1.059     1.060      0.106    0.001       True
13   67 0.125      1.068     1.068     1.069      0.117    0.002       True
14   61 0.137      1.090     1.090     1.092      0.126    0.002       True
15   57 0.145      1.092     1.092     1.093      0.133    0.002       True
16   51 0.160      1.113     1.114     1.116      0.143    0.003       True
17   46 0.175      1.140     1.141     1.142      0.154    0.004       True
18   42 0.191      1.168     1.169     1.170      0.164    0.004       True
19   37 0.216      1.219     1.218     1.218      0.177    0.006       True
20   31 0.247      1.254     1.251     1.252      0.197    0.008       True
21   28 0.267      1.274     1.272     1.275      0.210    0.010       True
22   25 0.293      1.309     1.307     1.312      0.224    0.012       True
23   23 0.312      1.332     1.331     1.335      0.234    0.013       True
24   22 0.318      1.320     1.320     1.326      0.241    0.014       True
25   16 0.383      1.354     1.354     1.355      0.283    0.023       True
26   15 0.390      1.332     1.333     1.329      0.293    0.025       True
27   13 0.404      1.287     1.290     1.287      0.314    0.032       True
28   13 0.404      1.287     1.290     1.287      0.314    0.032       True
29   11 0.436      1.291     1.290     1.288      0.338    0.040       True
30   11 0.436      1.291     1.290     1.288      0.338    0.040       True
31   10 0.444      1.266     1.266     1.260      0.351    0.045       True
32   10 0.444      1.266     1.266     1.260      0.351    0.045       True
33   10 0.444      1.266     1.266     1.260      0.351    0.045       True
34    8 0.482      1.275     1.274     1.269      0.378    0.056       True
35    7 0.548      1.369     1.368     1.384      0.400    0.069       True
36    7 0.548      1.369     1.368     1.384      0.400    0.069       True
37    7 0.548      1.369     1.368     1.384      0.400    0.069       True
38    7 0.548      1.369     1.368     1.384      0.400    0.069       True
39    7 0.548      1.369     1.368     1.384      0.400    0.069       True
40    5 0.800      1.822     1.816     1.867      0.439    0.102       True
41    5 0.800      1.822     1.816     1.867      0.439    0.102       True
42    4 0.833      1.836     1.830     1.873      0.454    0.131       True
43    4 0.833      1.836     1.830     1.873      0.454    0.131       True
44    4 0.833      1.836     1.830     1.873      0.454    0.131       True
45    4 0.833      1.836     1.830     1.873      0.454    0.131       True
46    3 0.667      1.502     1.483     1.538      0.444    0.185       True
47    3 0.667      1.502     1.483     1.538      0.444    0.185       True
48    2 1.000      1.890     1.887     2.000      0.529    0.356       True
49    2 1.000      1.890     1.887     2.000      0.529    0.356       True
50    2 1.000      1.890     1.887     2.000      0.529    0.356       True
51    1   NaN        NaN       NaN       NaN        NaN      NaN      False
local maxima of the normalized coefficient (1000 nulls): [3, 23, 25, 29, 42, 48]
local maxima of the normalized coefficient (500 nulls): [3, 23, 25, 29, 42, 48]
local maxima of the normalized coefficient (100 nulls): [1, 3, 23, 25, 29, 42, 48]
phi minus the null mean, in null SDs, k = 3 to 6: [1.55, 0.88, 1.95, 3.66] ; phi minus null mean at k = 4: 4.19e-05
k >= 3 with phi above null mean + 1 SD: 47 of 48 ; first k where it fails: [4]
reading (a): first tier 16 (expected 16 +/- 1.6), second tier 5 (expected 5 +/- 0.5)
    [np.str_('ASHL'), np.str_('AVDL'), np.str_('AVEL'), np.str_('AVER'), np.str_('AVJL'), np.str_('AVJR'), np.str_('AWBL'), np.str_('AWBR'), np.str_('M3L'), np.str_('M3R'), np.str_('OLLR'), np.str_('OLQDR'), np.str_('RMDDL'), np.str_('RMDDR'), np.str_('RMDVL'), np.str_('RMDVR')]
    second tier: [np.str_('AVEL'), np.str_('AVER'), np.str_('AWBL'), np.str_('AWBR'), np.str_('RMDVR')]
reading (b): first tier 22 (expected 16 +/- 1.6), second tier 7 (expected 5 +/- 0.5)
    [np.str_('ASEL'), np.str_('ASER'), np.str_('ASHL'), np.str_('AVDL'), np.str_('AVEL'), np.str_('AVER'), np.str_('AVJL'), np.str_('AVJR'), np.str_('AWBL'), np.str_('AWBR'), np.str_('IL1DL'), np.str_('M3L'), np.str_('M3R'), np.str_('OLLL'), np.str_('OLLR'), np.str_('OLQDR'), np.str_('RMDDL'), np.str_('RMDDR'), np.str_('RMDVL'), np.str_('RMDVR'), np.str_('URXL'), np.str_('URXR')]
    second tier: [np.str_('AVEL'), np.str_('AVER'), np.str_('AWBL'), np.str_('AWBR'), np.str_('M3L'), np.str_('RMDDR'), np.str_('RMDVR')]
reading (a) first tier equals the code's list: True
 offset                  maxima  near25  near40  all_above_1sd
   1000 [3, 23, 25, 29, 40, 48]    True    True          False
   2000 [3, 23, 25, 29, 42, 48]    True    True          False
   3000 [3, 23, 25, 29, 42, 48]    True    True          False
   4000 [3, 23, 25, 29, 42, 48]    True    True          False
In [24]:
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(ks, phi, ".-", label="phi")
ax.errorbar(ks, table.null_mean, yerr=table.null_sd, fmt=".-", label="rewired mean +/- SD")
ax.plot(ks, table.norm_1000, ".-", label="phi normalized")
ax.axhline(1, color="k", lw=0.5)
ax.set_xlabel("k")
ax.legend()
plt.show()
print("plotted k from 0 to", ks.max(), "; phi range", np.nanmin(phi).round(3), "to",
      np.nanmax(phi).round(3), "; normalized range", np.nanmin(table.norm_1000).round(3), "to",
      np.nanmax(table.norm_1000).round(3))
No description has been provided for this image
plotted k from 0 to 51 ; phi range 0.037 to 1.0 ; normalized range 1.0 to 1.89

Result: partially reproduced. Under reading (a) (degree > 25 and > 40, the legend and the code) the tiers hold 16 and 5 neurons, the first tier is exactly the code's list, and the normalized coefficient has local maxima at k = 25 and k = 42, within two of 40. The maxima are k = 3, 23, 25, 29, 42 and 48 with 500 or 1000 rewired networks, and with 100 also k = 1; under all five seeds they include 25 and 40 or 42. The coefficient exceeds the null mean by more than one null SD at 47 of the 48 values of k from 3 on, but not at k = 4 (0.88 SD), so the last condition of the criterion fails at one k, under every seed. Reading (b) (25 or more, 40 or more, as the Results word it) gives 22 and 7 neurons, outside tolerance. The null comes from a rewiring written in place of graph-tool's.

fig5c-rich-clubs-disjoint¶

The signaling and anatomical rich clubs are nearly disjoint; only AVEL and AVER are in both.

The anatomical rich club is degree > 62 in the anatomical network (richclub.py).

In [25]:
anat_rc = sorted(np.array(names)[degB > 62])
print(f"anatomical rich club (degree > 62): {len(anat_rc)} neurons (Extended Data Figure 12a gives 15):", anat_rc)
for rd in ("a", "b"):
    print(f"intersection with the signaling first tier, reading ({rd}):",
          sorted(set(tier[rd][0]) & set(anat_rc)))
near = [(names[i], int(degB[i])) for i in np.argsort(-degB) if 55 <= degB[i] <= 70]
print("anatomical degrees near the threshold:", near)
for lab_, src_ in variants.items():
    dv = nw.total_degree(nw.anatomy_adjacency(src_, "any"))
    rc_v = sorted(np.array(names)[dv > 62])
    print(f"variant {lab_}: {len(rc_v)} neurons, intersection with reading (a):",
          sorted(set(tier['a'][0]) & set(rc_v)))
anatomical rich club (degree > 62): 14 neurons (Extended Data Figure 12a gives 15): [np.str_('AIBL'), np.str_('AIBR'), np.str_('AVAL'), np.str_('AVAR'), np.str_('AVBL'), np.str_('AVBR'), np.str_('AVEL'), np.str_('AVER'), np.str_('RIBL'), np.str_('RIBR'), np.str_('RIH'), np.str_('RIML'), np.str_('RIMR'), np.str_('RIS')]
intersection with the signaling first tier, reading (a): [np.str_('AVEL'), np.str_('AVER')]
intersection with the signaling first tier, reading (b): [np.str_('AVEL'), np.str_('AVER')]
anatomical degrees near the threshold: [('AVAL', 70), ('AVAR', 68), ('RIS', 66), ('AVBR', 63), ('AVBL', 63), ('RIMR', 63), ('RIAR', 62), ('RIAL', 61), ('RIGL', 61), ('AIZL', 59), ('RICR', 59), ('RICL', 59), ('RMGL', 59), ('AIZR', 58), ('RMDL', 57), ('RMGR', 56), ('ADEL', 55)]
variant White A (N2U) for White whole: 10 neurons, intersection with reading (a): [np.str_('AVEL'), np.str_('AVER')]
variant gap junctions one direction: 8 neurons, intersection with reading (a): [np.str_('AVEL'), np.str_('AVER')]

Result: reproduced. The anatomical rich club (degree > 62) has 14 neurons, one fewer than the 15 of the legend of Extended Data Figure 12a, and its intersection with the signaling first tier is exactly AVEL and AVER, under both readings of the tiers and under both anatomical variants (10 and 8 neurons).

rich-club-controls (with inputs), the part that can be run¶

The near disjointness of the rich clubs persists under the conservative and enforced-density controls, and every signaling rich club neuron at q <= 0.18 was in the original signaling rich club.

Of the three pairs of control networks, only one can be built here: the original signaling network against the anatomical network with an average of at least 1.25 contacts over the four sources (Methods, Network Thresholding Controls; Extended Data Figure 12). The other two need the signaling network at q < 0.01 and at q <= 0.18, which cannot be built (see the data check). The conservative anatomical network (at least three contacts in one source) is shown for its density only.

Rich club thresholds, as the claims file reads them: (a) the original thresholds, degree > 25 for signaling and > 62 for anatomy; (b) each network's own threshold at a local maximum of its normalized coefficient (1000 rewired networks, as in fig5a-signaling-rich-club). The paper picks its maxima "by eye" (richclub.py). For (b) the notebook takes, among the local maxima that leave at least 10 neurons, the one with the largest normalized coefficient; this is an assumption, checked by showing that it gives back 25 and 62 on the original networks. All local maxima are printed so that other choices can be seen. The legend of Extended Data Figure 12a (9 of the 15 original anatomical rich club neurons kept, 4 new) is shown for comparison.

In [26]:
cid = "rich-club-controls"


def club_threshold(adj, offset=0, n_null=1000, min_size=10):
    phi_, null_ = rich_club(adj, cid, n_null=n_null, offset=offset)
    norm_ = phi_ / np.nanmean(null_, axis=0)
    d_ = nw.total_degree(adj)
    cand = [(k, round(float(norm_[k]), 3), int((d_ > k).sum())) for k in local_maxima(norm_)]
    big = [c for c in cand if c[2] >= min_size]
    return max(big, key=lambda c: c[1])[0], cand


B125 = nw.anatomy_adjacency(anat_src, "avg125")
print(f"anatomy, average >= 1.25 contacts: {int(B125.sum())} edges, density {nw.density(B125):.4f} "
      f"(paper 0.033); maximum degree {nw.total_degree(B125).max()}")
for mode in ("three_type", "three_total"):
    Bc = nw.anatomy_adjacency(anat_src, mode)
    print(f"anatomy, conservative ({mode}): {int(Bc.sum())} edges, density {nw.density(Bc):.4f} "
          f"(paper 0.028); its pair needs the signaling network at q < 0.01, not run")
k_sig, cand_sig = club_threshold(A)
k_an, cand_an = club_threshold(B)
print("rule (b) on the original signaling network, local maxima (k, normalized, N_k):", cand_sig,
      "; chosen k:", k_sig)
print("rule (b) on the original anatomical network, local maxima (k, normalized, N_k):", cand_an,
      "; chosen k:", k_an)
sig_club = {"a": set(np.array(names)[deg > 25]), "b": set(np.array(names)[deg > k_sig])}
d125 = nw.total_degree(B125)
rows = []
for off in OFFSETS:
    k125, cand125 = club_threshold(B125, offset=off)
    if off == 0:
        print("1.25-contact anatomy, local maxima (k, normalized, N_k):", cand125)
    for rd, k_ in (("a", 62), ("b", k125)):
        if rd == "a" and off:
            continue
        club = set(np.array(names)[d125 > k_])
        rows.append(dict(seed_offset=off, reading=rd, k=k_, size=len(club),
                         overlap_with_signaling=sorted(club & sig_club[rd]),
                         kept_of_original=f"{len(club & set(anat_rc))} of {len(anat_rc)}",
                         new=sorted(club - set(anat_rc))))
rc_tab = pd.DataFrame(rows)
print(rc_tab.to_string(index=False))
print("1.25-contact anatomical rich club under (b), claim's seed:",
      sorted(np.array(names)[d125 > rc_tab.query("reading == 'b'").k.iloc[0]]))
for lab_, src_ in variants.items():
    Bv = nw.anatomy_adjacency(src_, "avg125")
    kv, _ = club_threshold(Bv)
    dv = nw.total_degree(Bv)
    print(f"variant {lab_}: {int(Bv.sum())} edges, density {nw.density(Bv):.4f}; (a) {int((dv > 62).sum())} "
          f"neurons; (b) k = {kv}, {int((dv > kv).sum())} neurons, overlap with signaling "
          f"{sorted(set(np.array(names)[dv > kv]) & sig_club['b'])}")
anatomy, average >= 1.25 contacts: 1161 edges, density 0.0330 (paper 0.033); maximum degree 39
anatomy, conservative (three_type): 1014 edges, density 0.0288 (paper 0.028); its pair needs the signaling network at q < 0.01, not run
anatomy, conservative (three_total): 1077 edges, density 0.0306 (paper 0.028); its pair needs the signaling network at q < 0.01, not run
rule (b) on the original signaling network, local maxima (k, normalized, N_k): [(3, 1.001, 150), (23, 1.331, 23), (25, 1.358, 16), (42, 1.842, 4), (48, 1.944, 2)] ; chosen k: 25
rule (b) on the original anatomical network, local maxima (k, normalized, N_k): [(18, 1.031, 145), (25, 1.067, 120), (28, 1.069, 111), (33, 1.079, 93), (37, 1.096, 76), (41, 1.088, 61), (45, 1.102, 43), (49, 1.157, 33), (57, 1.225, 22), (62, 1.581, 14), (71, 1.675, 7), (78, 1.634, 4)] ; chosen k: 62
1.25-contact anatomy, local maxima (k, normalized, N_k): [(2, 1.002, 154), (16, 1.16, 51), (19, 1.188, 39), (21, 1.204, 35), (28, 1.395, 13), (33, 1.184, 7), (36, 1.127, 4)]
 seed_offset reading  k  size overlap_with_signaling kept_of_original                            new
           0       a 62     0                     []          0 of 14                             []
           0       b 28    13           [AVEL, AVER]          8 of 14 [AIZR, RIAL, RIAR, RIGL, RIGR]
        1000       b 28    13           [AVEL, AVER]          8 of 14 [AIZR, RIAL, RIAR, RIGL, RIGR]
        2000       b 28    13           [AVEL, AVER]          8 of 14 [AIZR, RIAL, RIAR, RIGL, RIGR]
        3000       b 28    13           [AVEL, AVER]          8 of 14 [AIZR, RIAL, RIAR, RIGL, RIGR]
        4000       b 28    13           [AVEL, AVER]          8 of 14 [AIZR, RIAL, RIAR, RIGL, RIGR]
1.25-contact anatomical rich club under (b), claim's seed: [np.str_('AIZR'), np.str_('AVAL'), np.str_('AVAR'), np.str_('AVEL'), np.str_('AVER'), np.str_('RIAL'), np.str_('RIAR'), np.str_('RIBL'), np.str_('RIBR'), np.str_('RIGL'), np.str_('RIGR'), np.str_('RIML'), np.str_('RIMR')]
variant White A (N2U) for White whole: 1120 edges, density 0.0319; (a) 0 neurons; (b) k = 25, 17 neurons, overlap with signaling [np.str_('AVER')]
variant gap junctions one direction: 975 edges, density 0.0277; (a) 0 neurons; (b) k = 25, 10 neurons, overlap with signaling [np.str_('AVEL'), np.str_('AVER')]

Result: blocked (data missing); the one pair that can be run holds. The claim needs three pairs of control networks and the signaling rich club at q <= 0.18; two of the pairs and that network need q-values the sources do not hold, so the claim stays blocked. The pair that can be built, the original signaling network against the anatomical network with an average of at least 1.25 contacts (1161 edges, density 0.0330 against the paper's 0.033), keeps the rich clubs apart under both readings. Under (a) no neuron of that sparser network has degree above 62 (its largest degree is 39), so the overlap is empty. Under (b) the rule gives k = 28 under all five seeds, a club of 13 neurons whose overlap with the signaling rich club (k = 25, which the rule also gives) is AVEL and AVER only. It keeps 8 of the 14 neurons of the original anatomical rich club and adds 5 (AIZR, RIAL, RIAR, RIGL, RIGR), where the legend of Extended Data Figure 12a gives 9 of 15 and 4 new. With the White N2U adult the 1.25-contact club under (b) shares only AVER, and with gap junctions in one direction AVEL and AVER. The rule for (b) is an assumption; it gives back the paper's thresholds 25 and 62 on the original networks.

fig5b-degree-correlation¶

Signaling and anatomical degree are weakly correlated across neurons (Pearson r = 0.22); the highest-degree anatomical neurons tend to have lower signaling degree.

In [27]:
lr = stats.linregress(degB, deg)
print(f"Pearson r = {lr.rvalue:.4f} (expected 0.22 +/- 0.022), p = {lr.pvalue:.2g}, slope "
      f"{lr.slope:.3f}, n = {N}")
for lab_, src_ in variants.items():
    dv = nw.total_degree(nw.anatomy_adjacency(src_, "any"))
    print(f"variant {lab_}: r = {stats.pearsonr(dv, deg).statistic:.4f}")
top = degB > 62
print(f"signaling degree of the anatomical rich club: median {np.median(deg[top])}, "
      f"others median {np.median(deg[~top])}")
fig, ax = plt.subplots(figsize=(5, 4))
ax.scatter(degB[~top], deg[~top], s=8, label="other")
ax.scatter(degB[top], deg[top], s=12, c="r", label="anatomical degree > 62")
ax.set_xlabel("anatomical degree")
ax.set_ylabel("signaling degree")
ax.legend()
plt.show()
print("anatomical degree range", degB.min(), "to", degB.max(), "; signaling", deg.min(), "to", deg.max())
Pearson r = 0.2186 (expected 0.22 +/- 0.022), p = 0.0026, slope 0.126, n = 188
variant White A (N2U) for White whole: r = 0.1694
variant gap junctions one direction: r = 0.2061
signaling degree of the anatomical rich club: median 9.5, others median 10.0
No description has been provided for this image
anatomical degree range 6 to 92 ; signaling 0 to 52

Result: reproduced, resting on the choice of the four EM datasets. Pearson r = 0.2186 (p = 0.0026) between signaling and anatomical degree, within tolerance. With the White N2U adult in place of the whole-animal White adult r = 0.169, outside tolerance; with gap junctions in one direction r = 0.206, inside. The anatomical rich club has a median signaling degree of 9.5 against 10.0 for the other neurons; the second half of the statement is not judged.

ed10-rich-club-cell-classes¶

Signaling rich club neurons are spread fairly equally among sensory, inter- and motor neurons, unlike the anatomical rich club, which is mostly interneurons.

In [28]:
for rd in ("a", "b"):
    c = collections.Counter(cls[[idx[n] for n in tier[rd][0]]])
    print(f"signaling first tier, reading ({rd}), {len(tier[rd][0])} neurons:",
          {k: c.get(k, 0) for k in "SIM"}, "; largest share", round(max(c.values()) / len(tier[rd][0]), 3))
c = collections.Counter(cls[[idx[n] for n in anat_rc]])
print(f"anatomical rich club, {len(anat_rc)} neurons:", {k: c.get(k, 0) for k in "SIM"},
      "; interneuron share", round(c.get("I", 0) / len(anat_rc), 3))
for lab_, src_ in variants.items():
    dv = nw.total_degree(nw.anatomy_adjacency(src_, "any"))
    rc_v = np.array(names)[dv > 62]
    cv = collections.Counter(cls[[idx[n] for n in rc_v]])
    print(f"variant {lab_}: {len(rc_v)} neurons, interneuron share {cv.get('I', 0) / len(rc_v):.3f}")
signaling first tier, reading (a), 16 neurons: {'S': 5, 'I': 5, 'M': 6} ; largest share 0.375
signaling first tier, reading (b), 22 neurons: {'S': 11, 'I': 5, 'M': 6} ; largest share 0.5
anatomical rich club, 14 neurons: {'S': 0, 'I': 12, 'M': 2} ; interneuron share 0.857
variant White A (N2U) for White whole: 10 neurons, interneuron share 0.800
variant gap junctions one direction: 8 neurons, interneuron share 0.875

Result: reproduced. The signaling first tier holds 5 sensory, 5 inter- and 6 motor neurons (largest share 0.375; under reading (b) 11, 5 and 6, largest share 0.5, not more than half). The anatomical rich club is 12 interneurons of 14 (0.857), and 0.800 and 0.875 under the two anatomical variants.

ed9e-degree-observations¶

Signaling degree is correlated with the number of times a neuron was observed (Pearson r = 0.71), but rich club members have degrees well above what that correlation predicts.

As in degree.py: a least-squares line of total degree on the number of observations, the residuals, a Gaussian fit to them; a rich club neuron is "well in excess" when its degree is more than one fitted SD above the line (the claims file's choice). Observations as in ed9-sampling-not-confound; the NeuroPAL count is a variant.

In [29]:
for lab_, obs in (("activity ROIs (main)", obs_count), ("NeuroPAL labels (variant)", obs_np)):
    a_, b_ = np.polyfit(obs, deg, 1)
    r_ = stats.pearsonr(obs, deg)
    errors = a_ * obs + b_ - deg
    mu, sd = stats.norm.fit(errors)
    resid = deg - (a_ * obs + b_)
    rc_idx = [idx[n] for n in tier["a"][0]]
    above = resid[rc_idx] > sd
    print(f"{lab_}: r = {r_.statistic:.4f} (expected 0.71 +/- 0.071), p = {r_.pvalue:.2g}; "
          f"fitted SD {sd:.2f}; rich club neurons (reading a) more than 1 SD above the line: "
          f"{above.sum()} of {len(rc_idx)}")
    if lab_.startswith("activity"):
        print(pd.DataFrame({"neuron": tier["a"][0], "observations": obs[rc_idx],
                            "degree": deg[rc_idx], "residual": resid[rc_idx].round(2),
                            "residual/SD": (resid[rc_idx] / sd).round(2)}).to_string(index=False))
        rc_b = [idx[n] for n in tier["b"][0]]
        print(f"reading (b), {len(rc_b)} neurons: more than 1 SD above: {(resid[rc_b] > sd).sum()}")
print("observation counts: range", obs_count.min(), "to", obs_count.max(), "; median",
      np.median(obs_count))
fig, ax = plt.subplots(figsize=(5, 4))
ax.scatter(obs_count, deg, s=8)
ax.scatter(obs_count[[idx[n] for n in tier["a"][0]]], deg[[idx[n] for n in tier["a"][0]]], s=12,
           c="r", label="signaling rich club (degree > 25)")
ax.set_xlabel("recordings in which the neuron was observed")
ax.set_ylabel("signaling degree")
ax.legend()
plt.show()
activity ROIs (main): r = 0.7021 (expected 0.71 +/- 0.071), p = 3.1e-29; fitted SD 7.34; rich club neurons (reading a) more than 1 SD above the line: 10 of 16
neuron  observations  degree  residual  residual/SD
  ASHL            56      34     16.13         2.20
  AVDL            86      27      0.97         0.13
  AVEL            88      51     24.42         3.33
  AVER            89      46     19.15         2.61
  AVJL            97      31      1.98         0.27
  AVJR            89      35      8.15         1.11
  AWBL            89      52     25.15         3.43
  AWBR            81      42     17.33         2.36
   M3L            99      40     10.43         1.42
   M3R           100      34      4.16         0.57
  OLLR            70      29      7.32         1.00
 OLQDR            59      27      8.31         1.13
 RMDDL            74      29      6.23         0.85
 RMDDR            76      40     16.69         2.27
 RMDVL           101      26     -4.11        -0.56
 RMDVR           100      48     18.16         2.47
reading (b), 22 neurons: more than 1 SD above: 13
NeuroPAL labels (variant): r = 0.6620 (expected 0.71 +/- 0.071), p = 4.4e-25; fitted SD 7.72; rich club neurons (reading a) more than 1 SD above the line: 11 of 16
observation counts: range 0 to 101 ; median 30.5
No description has been provided for this image

Result: partially reproduced. Degree and observations correlate with r = 0.702 (expected 0.71). Of the 16 rich club neurons, 10 lie more than one fitted SD (7.34) above the line; AVDL, AVJL, M3R, RMDDL and RMDVL are within one SD and OLLR is at 1.00 SD. With the NeuroPAL count of observations r = 0.662 and 11 of 16.

ave-most-connected-both¶

The most connected member of the signaling rich club is also the most connected member of the connectome, the bilateral pair AVEL and AVER.

Readings (a) the neuron of highest degree in each network is AVEL or AVER; (b) the class AVE has the highest summed degree of its left and right neurons among bilateral classes.

In [30]:
def ranks(d):
    order = np.argsort(-d, kind="stable")
    return pd.DataFrame({"neuron": np.array(names)[order][:6], "degree": d[order][:6]})


print("signaling, top neurons:")
print(ranks(deg).to_string(index=False))
print("anatomy, top neurons:")
print(ranks(degB).to_string(index=False))
for nm, d in (("signaling", deg), ("anatomy", degB)):
    r_ = {n: int((d > d[idx[n]]).sum()) + 1 for n in ("AVEL", "AVER")}
    print(f"{nm}: rank of AVEL {r_['AVEL']}, AVER {r_['AVER']}")
pairs_ = {n[:-1]: (n, n[:-1] + "R") for n in names if n.endswith("L") and n[:-1] + "R" in name_set}
for nm, d in (("signaling", deg), ("anatomy", degB)):
    sums = pd.Series({k: d[idx[l]] + d[idx[r]] for k, (l, r) in pairs_.items()}).sort_values(ascending=False)
    print(f"{nm}, bilateral classes by summed degree:", sums.head(5).to_dict())
for lab_, src_ in variants.items():
    dv = nw.total_degree(nw.anatomy_adjacency(src_, "any"))
    sums = pd.Series({k: dv[idx[l]] + dv[idx[r]] for k, (l, r) in pairs_.items()}).sort_values(ascending=False)
    print(f"variant {lab_}: top neuron {names[int(np.argmax(dv))]} ({dv.max()}); top classes",
          sums.head(3).to_dict())
signaling, top neurons:
neuron  degree
  AWBL      52
  AVEL      51
 RMDVR      48
  AVER      46
  AWBR      42
   M3L      40
anatomy, top neurons:
neuron  degree
  AVEL      92
  AIBR      84
  RIBL      84
  AIBL      82
  AVER      78
  RIBR      73
signaling: rank of AVEL 2, AVER 4
anatomy: rank of AVEL 1, AVER 5
signaling, bilateral classes by summed degree: {'AVE': 97, 'AWB': 94, 'M3': 74, 'RMDV': 74, 'RMDD': 69}
anatomy, bilateral classes by summed degree: {'AVE': 170, 'AIB': 166, 'RIB': 157, 'AVA': 138, 'RIM': 136}
variant White A (N2U) for White whole: top neuron RIBL (84); top classes {'AIB': 162, 'RIB': 157, 'AVE': 146}
variant gap junctions one direction: top neuron AVEL (82); top classes {'AIB': 152, 'AVE': 147, 'RIB': 133}

Result: reproduced under reading (b), resting on the choice of the four EM datasets. AVEL has the highest anatomical degree (92), but the highest signaling degree is AWBL's (52, AVEL 51), so reading (a) fails. Summed over the bilateral pair, AVE is first in both networks (97 against 94 for AWB; 170 against 166 for AIB). Under both anatomical variants AIB, not AVE, is the first class in the connectome.

Summary¶

A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.

Claim Outcome
atlas-dataset-link (link) partially reproduced: amplitudes agree, 88% of atlas edges measured in the dandiset
signaling-network-size reproduced (reading b, the atlas): 1154 edges, density 0.0328
signaling-clustering-small-world reproduced: C 0.135, sigma 4.62
anatomy-network-properties (elsewhere) reproduced, assumed (four EM datasets): 3223 edges, density 0.092, C 0.306, sigma 2.52
triad-distribution reproduced: chi-square p printed as 0
ed6-signaling-not-feedforward reproduced: no leg above either null
ed6-anatomy-feedforward (elsewhere) partially reproduced: all legs above the label shuffle, only sensory to motor above the edge swap
fig4c-broadcaster-integrator partially reproduced: amphid holds (p = 0.0046); pharynx out > in, p = 0.073
ed9-sampling-not-confound reproduced: KS p = 0.994 and 0.518
fig5a-signaling-rich-club partially reproduced: 16 and 5 neurons, maxima at 25 and 42; one-SD rule fails at k = 4
fig5c-rich-clubs-disjoint reproduced: AVEL and AVER only
fig5b-degree-correlation reproduced, assumed: r = 0.219
ed10-rich-club-cell-classes reproduced: 5, 5, 6; anatomy 12 of 14 interneurons
ed9e-degree-observations partially reproduced: r = 0.702; 10 of 16 more than one SD above
ave-most-connected-both reproduced under reading (b), assumed: AVE first by class in both
signaling-threshold-controls, bilateral-controls-signaling blocked, data missing: no q-values other than q < 0.05
rich-club-controls blocked, data missing; the one pair that can be built (1.25-contact anatomy) shares only AVEL and AVER
signaling-six-communities, table1-signaling-membership, anatomy-twenty-communities, more-communities-anatomy-controls, bilateral-same-community-signaling, bilateral-anatomy-stronger, pharynx-community-overlap, seven-enriched-pairings, forced-same-number-ars, pharynx-overlap-controls, fig3b-signaling-cell-type-enrichment, fig3c-signaling-role-enrichment, fig3de-anatomy-enrichment, fig4-community-motif-fractions, fig4d-pharynx-amphid-core, fig4d-anatomy-pharynx-amphid-assortative, fig5d-community-vi-hubs, fig5e-rich-club-core, anatomy-community-motif-fractions, community-vi-most-self-connected, pharynx-less-isolated-signaling blocked, not runnable: graph-tool (stochastic block model) cannot be installed

How the analysis differs from the paper's. The signaling network is the released atlas of Randi et al. (2023), not a network computed from the dandiset, because the q-values need control recordings the dandiset does not hold; it has 1154 edges where the paper has 1151. The atlas holds only the q < 0.05 network, so the threshold controls cannot be built. The anatomical network uses the four EM datasets of Randi et al.'s code, which the paper does not name; other choices change several values. The stochastic block model could not be run, and the paper's printed memberships are not used in its place. The rich club null uses a rewiring written here in place of graph-tool's. The stimulated-ROI identities come from the later version of the dandiset.

What was found about the dataset. The cited version does not say which ROI each stimulation targeted (the later version adds it, for about half of the stimulations), and its green signal holds unmarked interpolated values for 42% of frames and ROIs on average. The control recordings without stimulation that the atlas's q-values rest on are not deposited, and the dandiset's labeled stimulations cover 88% of the atlas's edges. Three recordings have raw imaging but no segmentation. Labels include sideless class names, numbers and free text without a description. pynwb 4.2.0 cannot build the files. The stimulation times share the signals' clock, and no recording is deposited twice.

In [31]:
print(f"notebook runtime {(time.time() - T0) / 60:.1f} min; peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
notebook runtime 7.7 min; peak memory 1.18 GB