Reproducing Okuno et al. (2025) from dandiset 000727¶

Paper. Okuno T, Woodward A, Okano H, Hata J (2025). Functional connectivity, structural connectivity, and inter-individual variability in Drosophila melanogaster. eLife reviewed preprint 107990 version 1, doi:10.7554/elife.107990.1. The claims file was written from the publisher's HTML of version 1 (main text, Methods, figure legends and the legends of the Extended Data figures); no PDF was available.

Dandiset. DANDI:000727, version 0.240106.0043, the version the paper's Methods and Data availability cite. It is also the only published version; the draft lists the same 18 assets with the same total size.

What the dandiset holds. The whole-brain two-photon imaging of Brezovec et al. that the paper reuses: 9 flies, one NWB file each, with the raw GCaMP6f and tdTomato volumes (256 x 128 x 49 voxels, 3384 volumes at 1.88 Hz), anatomical stacks, a green series already registered to the FDA space by Brezovec et al. (high-pass filtered and z-scored), and FicTrac walking data at 50 Hz.

Outside inputs (the claims file says the paper relies on them; both are pinned):

  • the paper's code, github.com/takuto-okuno-riken/flywalk at commit 4b92add: the resized FDA template, brain mask, the hemibrain neuropil atlas (114 ROIs), the JFRC2010 atlas, the FlyEM cf0.8 SC of the 114 ROIs and the walking regressors it computed (data/behavior.mat);
  • the paper's Zenodo record 10.5281/zenodo.15532272 (version of 2025-05-28, the one the code's README cites; the later version 18151010 postdates the preprint): FlyWire sc140 SC of the hemibrain ROIs, the selected-synapse SC matrices, the 99 null SC matrices of each permutation test, per-ROI transmitter and post-synapse counts.

The SCKm and DistKm ROI atlases (k-means parcellations) are in neither, so every claim on them is blocked. The analysis streams each fly's raw green series once for FC and once for the GLM.

Claim Data Status
fig1-poltcomp-optimal with inputs blocked: SCKm and DistKm atlases not published
fig2b-distkm-smoothing-optimum with inputs blocked: DistKm atlases not published
figs2-1b-sckm-smoothing with inputs blocked: SCKm atlases not published
fig2c-smoothing-plus-poltcomp with inputs blocked: atlases not published
figs2-1d-highpass-degrades with inputs blocked: DistKm atlases not published
fig2d-log-decline, fig2d-fly-values, fig2d-ten-thousand-rois with inputs blocked: atlases not published
discussion-twenty-rois with inputs blocked: atlases not published
fig3d-confidence-threshold with inputs blocked: FlyEM SC at 0.5, 0.6, 0.7, 0.9 not published
fig3d-flyem-vs-flywire with inputs tested
fig3e-flyem-higher-most-regions with inputs tested
fig3g-transmitter-correlation with inputs tested
fig4e-unsegregated-higher with inputs tested
fig4f-segregated-lower with inputs tested (reading a)
fig4i-reciprocal-higher with inputs tested
figs4-1-flyem-permutation with inputs blocked: FlyEM selected and null SC not published
fig5b-walking-activation with inputs tested
fig5b-walking-suppression with inputs tested
fig3a-postsynapse-counts, fig3c-regional-detection, figs3-1a-regional-count-similarity, fig3f-output-transmitters elsewhere tested on the paper's per-ROI tables
fig4b-ppssi-distribution elsewhere tested in connectome_okuno_2025.ipynb
fig4h, fig5-wagn, figs4-1ij, fig4a, fig4c elsewhere tested in connectome_okuno_2025.ipynb (fig4a, fig4c: FlyWire half only)
figs3-2cd-apl-similarity elsewhere blocked
In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "4")
os.environ["ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS"] = "1"  # with a set seed, makes ANTs registration repeatable
import time, resource, warnings
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import ants
import flyfc

warnings.filterwarnings("ignore", category=RuntimeWarning)
T_START = time.time()
print("dandiset", flyfc.DANDISET, "version", flyfc.VERSION)
print("code commit", flyfc.CODE_COMMIT, "zenodo record", flyfc.ZENODO_RECORD)
dandiset 000727 version 0.240106.0043
code commit 4b92add4a44f641ab6add809ff6b0e0d6110b50c zenodo record 15532272

Data check¶

The files, their metadata, and what the analysis reads from them. ANTs registration draws random samples. antspy 0.6.3 ignores the random_seed argument of ants.registration (it falls into **kwargs), so the earlier runs of this attempt were unseeded and their registrations, and every number resting on them, changed from run to run. The seed is now set through ants.config and ITK runs on one thread; the orientation cell below registers one mean image twice with the same seed to show that the result repeats. A registration with another seed (11) is a different local optimum, and how far it moves the voxels and the results is shown for every fly (cell after the reduction). No other random numbers are drawn.

In [2]:
assets = flyfc.list_assets()
print(len(assets), "NWB files")
meta = []
for a in assets:
    h5 = flyfc.open_nwb(a["s3"])
    g = h5[flyfc.GREEN]
    st = h5["acquisition/TwoPhotonSeriesFunctionalGreen/starting_time"]
    gs = h5["general/optophysiology/ImagingPlaneGCaMP6fFunctional/grid_spacing"][()]
    spd = h5["processing/behavior/FicTrac/SpatialSeriesMovementSpeed"]
    proc = h5["processing/ophys/TwoPhotonSeriesFunctionalGreenProcessed/data"]
    row = dict(subject=a["subject"], size_gb=round(a["size"] / 1e9, 1), green=g.shape, dtype=str(g.dtype),
               rate=round(float(st.attrs["rate"]), 6), spacing_um=tuple(np.round(gs * 1e6, 3)),
               speed_n=spd["data"].shape[0], speed_rate=float(spd["starting_time"].attrs["rate"]),
               speed_desc=spd.attrs["description"], processed=proc.shape,
               sex=h5["general/subject/sex"][()].decode(),
               genotype=h5["general/subject/genotype"][()].decode())
    meta.append(row)
    h5.close()
for r in meta:
    print(r["subject"], r["size_gb"], "GB green", r["green"], r["dtype"], "rate", r["rate"], "Hz spacing", r["spacing_um"],
          "um | speed", r["speed_n"], "samples at", r["speed_rate"], "Hz | processed", r["processed"], "|", r["sex"])
print("genotypes:", sorted({r["genotype"] for r in meta}))
print("speed description:", meta[0]["speed_desc"])
print("imaging duration (s):", sorted({round(r["green"][0] / r["rate"], 1) for r in meta}),
      "behaviour duration (s):", sorted({r["speed_n"] / r["speed_rate"] for r in meta}))
9 NWB files
fly-087 69.0 GB green (3384, 256, 128, 49) uint16 rate 1.879714 Hz spacing (np.float64(2.611), np.float64(2.611), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
fly-089 66.6 GB green (3384, 256, 128, 49) uint16 rate 1.879715 Hz spacing (np.float64(2.554), np.float64(2.67), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
fly-094 67.2 GB green (3384, 256, 128, 49) uint16 rate 1.879714 Hz spacing (np.float64(2.611), np.float64(2.611), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
fly-097 66.9 GB green (3384, 256, 128, 49) uint16 rate 1.879714 Hz spacing (np.float64(2.549), np.float64(2.675), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
fly-098 67.2 GB green (3384, 256, 128, 49) uint16 rate 1.879714 Hz spacing (np.float64(2.549), np.float64(2.675), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
fly-099 68.2 GB green (3384, 256, 128, 49) uint16 rate 1.879714 Hz spacing (np.float64(2.549), np.float64(2.675), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
fly-100 67.7 GB green (3384, 256, 128, 49) uint16 rate 1.879714 Hz spacing (np.float64(2.578), np.float64(2.646), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
fly-101 67.8 GB green (3384, 256, 128, 49) uint16 rate 1.879714 Hz spacing (np.float64(2.578), np.float64(2.646), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
fly-105 67.3 GB green (3384, 256, 128, 49) uint16 rate 1.879714 Hz spacing (np.float64(2.611), np.float64(2.611), np.float64(5.0)) um | speed 90000 samples at 50.0 Hz | processed (3384, 314, 146, 91) | F
genotypes: ['w+/w+;UAS-myr::tdTomato/UAS-GCaMP6f;nSyb-Gal4/+']
speed description: Instantaneous running speed of the animal in radians per frame.
imaging duration (s): [1800.3] behaviour duration (s): [1800.0]

Orientation and registration. The template and the masks come from the paper's code. The native mean image of the first fly is shown beside the template, and the correlation with the template after an affine registration is printed for each of the eight axis flips. The first fly's mean image is registered twice with seed 1 to show that a seeded registration repeats.

In [3]:
tm, tz = flyfc.code_nifti("template/thresholded_FDACal.nii.gz")
tmpl = ants.from_numpy(tm, spacing=tuple(float(v) / 1000 for v in tz))
brain, _ = flyfc.code_nifti("template/thresholded_FDACal_mask.nii.gz")
brain = brain > 0
masks = flyfc.hemiroi_masks()
names = flyfc.hemiroi_names()
print("template", tm.shape, "voxel (um)", tuple(round(float(v), 3) for v in tz), "brain-mask voxels", int(brain.sum()))
print("hemibrain ROIs", len(masks), "voxels per ROI", min(int(m.sum()) for m in masks), "to", max(int(m.sum()) for m in masks))

h5 = flyfc.open_nwb(assets[0]["s3"])
rd0 = flyfc.ChunkReader(assets[0]["s3"], h5)
T0 = rd0.shape[0]; ct = rd0.chunks[0]
mean0 = rd0.mean_image({0, ct * ((T0 // ct) // 2), ct * ((T0 - 1) // ct)})
vox0 = flyfc.spacing_mm(h5)
h5.close()
flips = flyfc.choose_flip(mean0, tmpl, vox0)
for k, v in flips.items():
    print("flip", k, "affine correlation with template", round(v, 3))
fig, ax = plt.subplots(2, 4, figsize=(15, 5))
for i, z in enumerate([6, 18, 30, 42]):
    ax[0, i].imshow(mean0[:, :, z].T, cmap="gray"); ax[0, i].set_title(f"{assets[0]['subject']} native z={z}")
    ax[1, i].imshow(tm[:, :, z].T, cmap="gray"); ax[1, i].set_title(f"template z={z}")
plt.tight_layout(); plt.show()
print("native mean image range", mean0.min().round(1), mean0.max().round(1), "| template range", tm.min(), tm.max().round(3))
# repeatability: the same mean image registered twice with seed 1
c_a, cc_a, _ = flyfc.register(mean0, tmpl, (1, 1, 1), vox0, seed=1)
c_b, cc_b, _ = flyfc.register(mean0, tmpl, (1, 1, 1), vox0, seed=1)
ok_ = ~np.isnan(c_a).any(1) & ~np.isnan(c_b).any(1)
print("two registrations with seed 1: largest coordinate difference", float(np.abs(c_a[ok_] - c_b[ok_]).max()),
      "native voxels | same field of view:", bool((np.isnan(c_a).any(1) == np.isnan(c_b).any(1)).all()), "| SyN correlation", round(cc_a["syn"], 4), round(cc_b["syn"], 4))
template (256, 128, 49) voxel (um) (2.452, 2.28, 3.715) brain-mask voxels 488801
hemibrain ROIs 114 voxels per ROI 6 to 17314
flip (1, 1, 1) affine correlation with template 0.44
flip (1, 1, -1) affine correlation with template -0.241
flip (1, -1, 1) affine correlation with template 0.195
flip (1, -1, -1) affine correlation with template 0.34
flip (-1, 1, 1) affine correlation with template 0.439
flip (-1, 1, -1) affine correlation with template 0.482
flip (-1, -1, 1) affine correlation with template 0.316
flip (-1, -1, -1) affine correlation with template 0.558
No description has been provided for this image
native mean image range 194.5 6346.8 | template range 0.0 1.005
two registrations with seed 1: largest coordinate difference 0.0 native voxels | same field of view: True | SyN correlation 0.8231 0.8231

In both images the slices near z = 6 hold two small dorsal-anterior structures near the midline and the slices near z = 42 hold the optic lobes, and the dorsoventral axis runs the same way, so no flip is applied along y or z. Left and right cannot be told apart from the image, and the affine correlations printed above are not a reliable guide: antspy's default affine stage favours flips along y and z, which the images rule out. No flip is assumed; the main FC-SC results are shown with left and right ROIs swapped, and the orientation is checked against the paper's own per-region FC-SC values (fig3e section) and its deposited GLM map (GLM section). The two checks disagree.

Reduce each fly. Each fly's raw green series is streamed once (about 7 GB per fly) and reduced to the 114 ROI mean series and the 1000 highest-SD voxels (flyfc.process_fly), and the middle 20 slices of the tdTomato series are read for the motion estimate.

In [4]:
flies = []
for a in assets:
    f = flyfc.process_fly(a, tmpl, masks, repeats=(11,))
    f.pop("warped"); f.pop("mean")
    flies.append(f)
    print(f["subject"], "read", round(f["mb_read"]), "MB in", round(f["t_total"]), "s | correlation with template",
          {k: round(v, 3) for k, v in f["cc"].items()}, "| voxel (um)", tuple(round(v * 1000, 3) for v in f["vox"]), "| ROIs not fully in the field of view",
          int((f["cover"] < 0.999).sum()), "min coverage", round(float(np.nanmin(f["cover"])), 3), flush=True)
print("peak memory (GB)", round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6, 2), "| elapsed (min)", round((time.time() - T_START) / 60, 1))
fly-087 read 11658 MB in 198 s | correlation with template {'affine_meansquares': 0.672, 'affine_mattes': 0.735, 'syn': 0.823, 'repeat_displacement_um_median': 23.453, 'repeat_displacement_um_p95': 55.524} | voxel (um) (2.611, 2.611, 5.0) | ROIs not fully in the field of view 0 min coverage 1.0
fly-089 read 10503 MB in 198 s | correlation with template {'affine_meansquares': 0.677, 'affine_mattes': 0.438, 'syn': 0.803, 'repeat_displacement_um_median': 43.635, 'repeat_displacement_um_p95': 92.73} | voxel (um) (2.554, 2.67, 5.0) | ROIs not fully in the field of view 0 min coverage 1.0
fly-094 read 11066 MB in 193 s | correlation with template {'affine_meansquares': 0.659, 'affine_mattes': 0.028, 'syn': 0.755, 'repeat_displacement_um_median': 3.719, 'repeat_displacement_um_p95': 8.494} | voxel (um) (2.611, 2.611, 5.0) | ROIs not fully in the field of view 0 min coverage 1.0
fly-097 read 10680 MB in 199 s | correlation with template {'affine_meansquares': 0.575, 'affine_mattes': 0.434, 'syn': 0.713, 'repeat_displacement_um_median': 32.709, 'repeat_displacement_um_p95': 67.04} | voxel (um) (2.549, 2.675, 5.0) | ROIs not fully in the field of view 0 min coverage 1.0
fly-098 read 10588 MB in 202 s | correlation with template {'affine_meansquares': 0.631, 'affine_mattes': 0.7, 'syn': 0.768, 'repeat_displacement_um_median': 20.391, 'repeat_displacement_um_p95': 44.139} | voxel (um) (2.549, 2.675, 5.0) | ROIs not fully in the field of view 0 min coverage 1.0
fly-099 read 10605 MB in 196 s | correlation with template {'affine_meansquares': 0.635, 'affine_mattes': -0.185, 'syn': 0.739, 'repeat_displacement_um_median': 2.547, 'repeat_displacement_um_p95': 5.758} | voxel (um) (2.549, 2.675, 5.0) | ROIs not fully in the field of view 0 min coverage 1.0
fly-100 read 10140 MB in 195 s | correlation with template {'affine_meansquares': 0.627, 'affine_mattes': 0.317, 'syn': 0.696, 'repeat_displacement_um_median': 19.805, 'repeat_displacement_um_p95': 69.667} | voxel (um) (2.578, 2.646, 5.0) | ROIs not fully in the field of view 9 min coverage 0.553
fly-101 read 10484 MB in 194 s | correlation with template {'affine_meansquares': 0.647, 'affine_mattes': 0.427, 'syn': 0.73, 'repeat_displacement_um_median': 7.323, 'repeat_displacement_um_p95': 11.347} | voxel (um) (2.578, 2.646, 5.0) | ROIs not fully in the field of view 0 min coverage 1.0
fly-105 read 9698 MB in 187 s | correlation with template {'affine_meansquares': 0.576, 'affine_mattes': 0.442, 'syn': 0.621, 'repeat_displacement_um_median': 3.101, 'repeat_displacement_um_p95': 6.636} | voxel (um) (2.611, 2.611, 5.0) | ROIs not fully in the field of view 2 min coverage 0.988
peak memory (GB) 4.23 | elapsed (min) 32.3
In [5]:
# Which ROIs lose coverage, and in which fly
for f in flies:
    low = np.nonzero(f["cover"] < 0.999)[0]
    if low.size:
        print(f["subject"], ", ".join(f"{names[i]} {f['cover'][i]:.2f}" for i in low))
sub_order = [f["subject"] for f in flies]
print("flies in name order:", sub_order)
print("code's subject list [1 2 3 4 5 6 8 9] leaves out the 7th:", sub_order[6])
sel8 = [i - 1 for i in flyfc.SUBJECT_IDS]
fly-100 CRE(R) 1.00, AL(L) 0.55, AL(R) 0.68, CRE(L) 0.98, SAD 0.95, gL(R) 0.96, bL(L) 0.99, AMMC 0.92, gL(L) 0.90
fly-105 AL(L) 0.99, AL(R) 1.00
flies in name order: ['fly-087', 'fly-089', 'fly-094', 'fly-097', 'fly-098', 'fly-099', 'fly-100', 'fly-101', 'fly-105']
code's subject list [1 2 3 4 5 6 8 9] leaves out the 7th: fly-100
In [6]:
# Registration repeatability: a second registration of the same mean image with another seed
for f in flies:
    rr = [np.corrcoef(f["R"][k], f["R_repeats"][0][k])[0, 1] for k in range(114) if f["R"][k].std() > 0 and f["R_repeats"][0][k].std() > 0]
    print(f["subject"], "second registration: native-voxel displacement median", round(f["cc"]["repeat_displacement_um_median"], 2),
          "um, 95th percentile", round(f["cc"]["repeat_displacement_um_p95"], 2), "um | ROI series r between the two: median", round(float(np.median(rr)), 4), "min", round(float(np.min(rr)), 3))
fly-087 second registration: native-voxel displacement median 23.45 um, 95th percentile 55.52 um | ROI series r between the two: median 0.58 min -0.156
fly-089 second registration: native-voxel displacement median 43.64 um, 95th percentile 92.73 um | ROI series r between the two: median 0.18 min -0.264
fly-094 second registration: native-voxel displacement median 3.72 um, 95th percentile 8.49 um | ROI series r between the two: median 0.939 min 0.225
fly-097 second registration: native-voxel displacement median 32.71 um, 95th percentile 67.04 um | ROI series r between the two: median 0.5659 min -0.129
fly-098 second registration: native-voxel displacement median 20.39 um, 95th percentile 44.14 um | ROI series r between the two: median 0.7219 min 0.051
fly-099 second registration: native-voxel displacement median 2.55 um, 95th percentile 5.76 um | ROI series r between the two: median 0.9628 min 0.372
fly-100 second registration: native-voxel displacement median 19.81 um, 95th percentile 69.67 um | ROI series r between the two: median 0.4931 min -0.015
fly-101 second registration: native-voxel displacement median 7.32 um, 95th percentile 11.35 um | ROI series r between the two: median 0.8897 min 0.175
fly-105 second registration: native-voxel displacement median 3.1 um, 95th percentile 6.64 um | ROI series r between the two: median 0.982 min 0.7

Subject order and the behaviour clock. The paper's code holds the per-volume speed and the walking regressor it computed for its nine flies (data/behavior.mat). Computing them from the dandiset's FicTrac speed, with the code's offset of 104.654892 ms, and comparing fly by fly checks both the subject order and the alignment of the behaviour to the volumes.

In [7]:
reg, mscal, th_speed, b_speed = flyfc.walking_regressors([f["speed"] for f in flies])
reg_bin, _, _, _ = flyfc.walking_regressors([f["speed"] for f in flies], binary=True)
beh = flyfc.load_mat(flyfc.code_file("data/behavior.mat"))
M = np.asarray(beh["MScal"], float); M2 = np.asarray(beh["MBcal2"], float)
print("code's MScal", M.shape, "| th (mean SD of speed)", round(th_speed, 5), "b (mean 10th percentile)", round(b_speed, 5))
C = np.array([[np.corrcoef(mscal[i], M[j])[0, 1] for j in range(9)] for i in range(9)])
for i, f in enumerate(flies):
    print(f["subject"], "best-matching code fly", int(np.argmax(C[i])) + 1, "r", round(C[i].max(), 6),
          "| max |speed diff|", f"{np.abs(mscal[i] - M[i]).max():.2e}", "| regressor max |diff|", f"{np.abs(reg[i] - M2[i]).max():.2e}")
print("speed range", round(min(f["speed"].min() for f in flies), 4), "to", round(max(f["speed"].max() for f in flies), 4), "(radians per frame, as the file states)")
print("fraction of volumes at or above b + th (binary walking):", np.round((mscal >= b_speed + th_speed).mean(1), 3))
code's MScal (9, 3384) | th (mean SD of speed) 0.01545 b (mean 10th percentile) 0.00179
fly-087 best-matching code fly 1 r 1.0 | max |speed diff| 1.58e-08 | regressor max |diff| 6.66e-06
fly-089 best-matching code fly 2 r 1.0 | max |speed diff| 7.67e-09 | regressor max |diff| 6.74e-06
fly-094 best-matching code fly 3 r 1.0 | max |speed diff| 1.19e-08 | regressor max |diff| 6.46e-06
fly-097 best-matching code fly 4 r 1.0 | max |speed diff| 8.88e-09 | regressor max |diff| 7.13e-06
fly-098 best-matching code fly 5 r 1.0 | max |speed diff| 1.08e-08 | regressor max |diff| 6.68e-06
fly-099 best-matching code fly 6 r 1.0 | max |speed diff| 1.13e-08 | regressor max |diff| 6.48e-06
fly-100 best-matching code fly 7 r 1.0 | max |speed diff| 1.12e-08 | regressor max |diff| 6.01e-06
fly-101 best-matching code fly 8 r 1.0 | max |speed diff| 1.04e-08 | regressor max |diff| 6.41e-06
fly-105 best-matching code fly 9 r 1.0 | max |speed diff| 9.66e-09 | regressor max |diff| 7.05e-06
speed range 0.0 to 0.1807 (radians per frame, as the file states)
fraction of volumes at or above b + th (binary walking): [0.562 0.299 0.208 0.176 0.363 0.329 0.604 0.503 0.15 ]

The behaviour clock is checked against the imaging with a contrast: the brain-wide mean of the ROI series, after removing the 7 polynomial terms, against the walking regressor, at shifts of the regressor by -60 to 60 volumes. If the two streams share the clock, the correlation peaks near shift 0 (the regressor is already convolved with the calcium response).

In [8]:
shifts = np.arange(-60, 61, 2)
ids_all = np.arange(114)
for i, f in enumerate(flies):
    g = flyfc.residualize(f["R"][ids_all].mean(0)[:, None], flyfc.poly_regressors(f["T"]))[:, 0]
    cc = [np.corrcoef(np.roll(reg[i], s)[70:-70], g[70:-70])[0, 1] for s in shifts]
    k = int(np.argmax(cc))
    print(f["subject"], "peak r", round(cc[k], 3), "at shift", int(shifts[k]), "volumes | r at 0:", round(cc[30], 3),
          "| median |r| at shifts beyond 30:", round(float(np.median(np.abs(np.array(cc)[np.abs(shifts) > 30]))), 3))
fly-087 peak r 0.527 at shift 0 volumes | r at 0: 0.527 | median |r| at shifts beyond 30: 0.033
fly-089 peak r 0.492 at shift 2 volumes | r at 0: 0.404 | median |r| at shifts beyond 30: 0.059
fly-094 peak r 0.789 at shift 0 volumes | r at 0: 0.789 | median |r| at shifts beyond 30: 0.028
fly-097 peak r 0.576 at shift 0 volumes | r at 0: 0.576 | median |r| at shifts beyond 30: 0.034
fly-098 peak r 0.498 at shift 0 volumes | r at 0: 0.498 | median |r| at shifts beyond 30: 0.055
fly-099 peak r 0.513 at shift 0 volumes | r at 0: 0.513 | median |r| at shifts beyond 30: 0.04
fly-100 peak r 0.547 at shift 0 volumes | r at 0: 0.547 | median |r| at shifts beyond 30: 0.037
fly-101 peak r 0.483 at shift 0 volumes | r at 0: 0.483 | median |r| at shifts beyond 30: 0.061
fly-105 peak r 0.548 at shift 0 volumes | r at 0: 0.548 | median |r| at shifts beyond 30: 0.121

Motion. The paper corrects motion and slice timing with SPM12 before registration (Methods, Preprocessing; claims file M1); this attempt does neither. To show whether the raw series moves, each volume's sum over the middle 20 slices (z = 15 to 34) of the structural tdTomato channel is aligned to the mean over volumes by cross-correlation, giving a rigid in-plane shift per volume (flyfc.inplane_shift; it cannot see motion along z). The same from the green channel's sum over all slices is printed beside it. The shift is compared with the voxel size and with walking, and fig3d is recomputed with the two tdTomato shift series added to the nuisance regressors (fig3d section).

In [9]:
for i, f in enumerate(flies):
    for lab_, sh in [("tdTomato", f["shift"]), ("green", f["shift_green"])]:
        d = sh - np.median(sh, 0)
        mag = np.sqrt((d ** 2).sum(1))
        step = np.sqrt((np.diff(sh, axis=0) ** 2).sum(1))
        print(f["subject"], f"{lab_:8s} in-plane shift from the median (um): median", round(float(np.median(mag)), 2), "95th percentile", round(float(np.percentile(mag, 95)), 2),
              "max", round(float(mag.max()), 2), "| x SD", round(float(d[:, 0].std()), 2), "y SD", round(float(d[:, 1].std()), 2),
              "| volume-to-volume step 99th percentile", round(float(np.percentile(step, 99)), 2), "| r of shift size with walking speed", round(float(np.corrcoef(mag, mscal[i])[0, 1]), 3))
    print(f["subject"], "r between the tdTomato and green shift series: x", round(float(np.corrcoef(f["shift"][:, 0], f["shift_green"][:, 0])[0, 1]), 3),
          "y", round(float(np.corrcoef(f["shift"][:, 1], f["shift_green"][:, 1])[0, 1]), 3))
print("voxel size in plane about 2.6 um")
fly-087 tdTomato in-plane shift from the median (um): median 0.77 95th percentile 5.16 max 6.61 | x SD 0.78 y SD 1.98 | volume-to-volume step 99th percentile 1.55 | r of shift size with walking speed 0.154
fly-087 green    in-plane shift from the median (um): median 0.62 95th percentile 3.85 max 5.22 | x SD 0.83 y SD 1.55 | volume-to-volume step 99th percentile 1.78 | r of shift size with walking speed -0.01
fly-087 r between the tdTomato and green shift series: x 0.952 y 0.926
fly-089 tdTomato in-plane shift from the median (um): median 0.89 95th percentile 3.7 max 5.7 | x SD 0.87 y SD 1.29 | volume-to-volume step 99th percentile 3.18 | r of shift size with walking speed 0.015
fly-089 green    in-plane shift from the median (um): median 1.12 95th percentile 3.77 max 7.94 | x SD 1.1 y SD 1.47 | volume-to-volume step 99th percentile 4.75 | r of shift size with walking speed 0.018
fly-089 r between the tdTomato and green shift series: x 0.964 y 0.887
fly-094 tdTomato in-plane shift from the median (um): median 0.6 95th percentile 2.77 max 5.02 | x SD 1.0 y SD 0.52 | volume-to-volume step 99th percentile 1.02 | r of shift size with walking speed 0.003
fly-094 green    in-plane shift from the median (um): median 0.57 95th percentile 2.24 max 3.99 | x SD 0.92 y SD 0.38 | volume-to-volume step 99th percentile 0.8 | r of shift size with walking speed 0.031
fly-094 r between the tdTomato and green shift series: x 0.978 y 0.874
fly-097 tdTomato in-plane shift from the median (um): median 0.95 95th percentile 3.51 max 4.76 | x SD 0.59 y SD 1.6 | volume-to-volume step 99th percentile 0.82 | r of shift size with walking speed -0.067
fly-097 green    in-plane shift from the median (um): median 1.01 95th percentile 3.37 max 5.59 | x SD 0.59 y SD 1.59 | volume-to-volume step 99th percentile 0.86 | r of shift size with walking speed -0.13
fly-097 r between the tdTomato and green shift series: x 0.761 y 0.96
fly-098 tdTomato in-plane shift from the median (um): median 0.93 95th percentile 2.86 max 5.47 | x SD 0.78 y SD 1.24 | volume-to-volume step 99th percentile 3.75 | r of shift size with walking speed -0.119
fly-098 green    in-plane shift from the median (um): median 0.95 95th percentile 3.74 max 6.37 | x SD 0.63 y SD 1.61 | volume-to-volume step 99th percentile 4.75 | r of shift size with walking speed -0.148
fly-098 r between the tdTomato and green shift series: x 0.92 y 0.977
fly-099 tdTomato in-plane shift from the median (um): median 0.78 95th percentile 3.84 max 7.24 | x SD 1.39 y SD 0.79 | volume-to-volume step 99th percentile 2.25 | r of shift size with walking speed -0.303
fly-099 green    in-plane shift from the median (um): median 0.79 95th percentile 3.63 max 6.39 | x SD 1.35 y SD 0.63 | volume-to-volume step 99th percentile 2.26 | r of shift size with walking speed -0.307
fly-099 r between the tdTomato and green shift series: x 0.995 y 0.959
fly-100 tdTomato in-plane shift from the median (um): median 1.32 95th percentile 4.21 max 6.29 | x SD 1.0 y SD 1.8 | volume-to-volume step 99th percentile 5.29 | r of shift size with walking speed -0.138
fly-100 green    in-plane shift from the median (um): median 1.09 95th percentile 4.49 max 8.43 | x SD 0.84 y SD 1.8 | volume-to-volume step 99th percentile 5.51 | r of shift size with walking speed -0.166
fly-100 r between the tdTomato and green shift series: x 0.955 y 0.955
fly-101 tdTomato in-plane shift from the median (um): median 0.89 95th percentile 2.78 max 7.01 | x SD 0.73 y SD 1.09 | volume-to-volume step 99th percentile 3.53 | r of shift size with walking speed -0.151
fly-101 green    in-plane shift from the median (um): median 0.73 95th percentile 2.92 max 7.29 | x SD 0.71 y SD 1.05 | volume-to-volume step 99th percentile 3.64 | r of shift size with walking speed -0.138
fly-101 r between the tdTomato and green shift series: x 0.979 y 0.97
fly-105 tdTomato in-plane shift from the median (um): median 3.19 95th percentile 6.13 max 9.36 | x SD 1.88 y SD 3.05 | volume-to-volume step 99th percentile 1.9 | r of shift size with walking speed 0.109
fly-105 green    in-plane shift from the median (um): median 1.81 95th percentile 6.2 max 8.17 | x SD 1.48 y SD 2.65 | volume-to-volume step 99th percentile 2.16 | r of shift size with walking speed 0.177
fly-105 r between the tdTomato and green shift series: x 0.98 y 0.955
voxel size in plane about 2.6 um

Duplicates. Recordings deposited twice would give identical speed traces or mean images.

In [10]:
sp = np.array([f["speed"] for f in flies])
csp = np.corrcoef(sp)
np.fill_diagonal(csp, np.nan)
print("largest speed-trace correlation between two flies:", round(np.nanmax(csp), 3))
roi = np.array([f["R"].mean(1) for f in flies])
cr = np.corrcoef(roi); np.fill_diagonal(cr, np.nan)
print("largest correlation of mean ROI intensity profiles between two flies:", round(np.nanmax(cr), 3))
print("identical speed traces:", [(i, j) for i in range(9) for j in range(i + 1, 9) if np.array_equal(sp[i], sp[j])])
largest speed-trace correlation between two flies: 0.11
largest correlation of mean ROI intensity profiles between two flies: 0.794
identical speed traces: []

FC and the paper's SC¶

FC per fly is the Pearson correlation of the 114 ROI series, Fisher-z transformed and averaged over the code's eight flies (M3). Poly-tCompCor is the 7 polynomial terms and 6 tCompCor components; tCompCor is taken from the 1000 native voxels with the highest temporal SD (an assumption: the code takes them among template voxels, after warping). SC is the second ("Traced") layer of each connect list (M4).

In [11]:
em_nc, em_sc, em_ids52 = flyfc.load_sc(flyfc.code_file("results/sc/hemiroi_connectlist.mat"))
fw_nc, fw_sc, ids = flyfc.load_sc(flyfc.zenodo_member("results/sc/hemiroi_fw0sr140_connectlist.mat"))
print("FlyEM SC", em_nc.shape, "| FlyWire SC", fw_nc.shape, "| primary ROIs", len(ids))
print("primary ROIs:", ", ".join(names[i] for i in ids))
print("FlyEM neuron SC over primary ROIs: total", int(em_nc[np.ix_(ids, ids)].sum()), "zeros", int((em_nc[np.ix_(ids, ids)] == 0).sum()))
print("FlyWire neuron SC over primary ROIs: total", int(fw_nc[np.ix_(ids, ids)].sum()), "zeros", int((fw_nc[np.ix_(ids, ids)] == 0).sum()))
series = {n: [flyfc.roi_series(f, n) for f in flies] for n in ["", "poltcomp"]}
mFz = {(n, s): flyfc.mean_zfc([series[n][i] for i in S]) for n in series for s, S in [("8", sel8), ("9", range(9))]}
F = mFz[("poltcomp", "8")]
# the same from the second registration of every fly (registration repeatability)
F_rep = flyfc.mean_zfc([flyfc.roi_series(dict(flies[i], R=flies[i]["R_repeats"][0]), "poltcomp") for i in sel8])
off = ~np.eye(len(ids), dtype=bool)
print("mean z-FC (Poly-tCompCor, 8 flies) over primary ROI pairs: range", round(F[np.ix_(ids, ids)][off].min(), 3), "to", round(F[np.ix_(ids, ids)][off].max(), 3),
      "| diagonal set to", round(F[ids[0], ids[0]], 3))
for f, s in zip(flies, series["poltcomp"]):
    print(f["subject"], "ROI series SD range", round(s.std(0)[ids].min(), 2), "to", round(s.std(0)[ids].max(), 2))
FlyEM SC (114, 114) | FlyWire SC (114, 114) | primary ROIs 63
primary ROIs: AB(R), AL(R), aL(R), a'L(R), AME(R), AOTU(R), ATL(R), AVLP(R), bL(R), b'L(R), BU(R), CA(R), CAN(R), CRE(R), EB, EPA(R), FB, FLA(R), gL(R), GNG, GOR(R), IB, ICL(R), IPS(R), LAL(R), LH(R), LO(R), LOP(R), ME(R), NO, PB, PED(R), PLP(R), PRW, PVLP(R), SAD, SCL(R), SIP(R), SLP(R), SMP(R), SPS(R), VES(R), WED(R), AB(L), AL(L), aL(L), a'L(L), ATL(L), bL(L), b'L(L), BU(L), CA(L), CRE(L), EPA(L), gL(L), GOR(L), ICL(L), LAL(L), SCL(L), SIP(L), SMP(L), SPS(L), VES(L)
FlyEM neuron SC over primary ROIs: total 910674 zeros 444
FlyWire neuron SC over primary ROIs: total 880704 zeros 457
mean z-FC (Poly-tCompCor, 8 flies) over primary ROI pairs: range -0.014 to 0.855 | diagonal set to 1.448
fly-087 ROI series SD range 24.32 to 351.41
fly-089 ROI series SD range 14.32 to 269.34
fly-094 ROI series SD range 13.71 to 250.23
fly-097 ROI series SD range 6.8 to 142.47
fly-098 ROI series SD range 7.93 to 155.13
fly-099 ROI series SD range 6.02 to 184.4
fly-100 ROI series SD range 6.85 to 107.58
fly-101 ROI series SD range 8.56 to 140.74
fly-105 ROI series SD range 4.88 to 91.62

fig3d-flyem-vs-flywire¶

Against the same FC, FlyEM gives a higher matrix-level FC-SC correlation than FlyWire (0.73 against 0.68).

63 hemibrain primary ROIs, no smoothing, Poly-tCompCor, SC (neuron), FlyEM cf0.8 and FlyWire sc140. Reproduced when both values are within tolerance (0.657 to 0.803; 0.612 to 0.748) and FlyEM is higher.

In [12]:
lr = {}
for i, n in enumerate(names):
    if "(L)" in n:
        j = names.index(n.replace("(L)", "(R)")) if n.replace("(L)", "(R)") in names else i
    elif "(R)" in n:
        j = names.index(n.replace("(R)", "(L)")) if n.replace("(R)", "(L)") in names else i
    else:
        j = i
    lr[i] = j
perm = np.array([lr[i] for i in range(114)])
print("ROIs with a left-right partner:", int((perm != np.arange(114)).sum()))
ref = flyfc.load_mat(flyfc.zenodo_member("results/auc/poltcomparhemiroi_fw0sr140-fcauc.mat"))
print("paper's own output for this setting (Zenodo auc file, FlyWire): R(7) =", round(float(np.ravel(ref["R"])[6]), 4), "R(9) =", round(float(np.ravel(ref["R"])[8]), 4))
rows = []
for (n, s), Fm in mFz.items():
    for lab, Fx in [("as registered", Fm), ("left-right swapped", Fm[np.ix_(perm, perm)])]:
        rows.append((n or "none", s, lab, flyfc.fcsc_r(em_nc, Fx, ids), flyfc.fcsc_r(fw_nc, Fx, ids),
                     flyfc.fcsc_r(em_sc, Fx, ids), flyfc.fcsc_r(fw_sc, Fx, ids)))
print(f"{'nuisance':9s} {'flies':5s} {'orientation':20s} {'EM neuron':>9s} {'FW neuron':>9s} {'EM syn':>7s} {'FW syn':>7s}")
for r in rows:
    print(f"{r[0]:9s} {r[1]:5s} {r[2]:20s} {r[3]:9.4f} {r[4]:9.4f} {r[5]:7.4f} {r[6]:7.4f}")
signed = [np.corrcoef(flyfc.log_sc(S[np.ix_(ids, ids)]).ravel(), F[np.ix_(ids, ids)].ravel())[0, 1] for S in (em_nc, fw_nc)]
print("signed FC variant (O3), Poly-tCompCor, 8 flies: FlyEM", round(signed[0], 4), "FlyWire", round(signed[1], 4))
r_em, r_fw = rows[4][3], rows[4][4]
print(f"MAIN: FlyEM r = {r_em:.4f} (tolerance 0.657 to 0.803, within: {0.657 <= r_em <= 0.803}); "
      f"FlyWire r = {r_fw:.4f} (0.612 to 0.748, within: {0.612 <= r_fw <= 0.748}); FlyEM higher: {r_em > r_fw}")
# per fly
for i, f in enumerate(flies):
    Fi = flyfc.mean_zfc([series["poltcomp"][i]])
    print(f["subject"], "single-fly FC: FlyEM", round(flyfc.fcsc_r(em_nc, Fi, ids), 4), "FlyWire", round(flyfc.fcsc_r(fw_nc, Fi, ids), 4))
F_mot = flyfc.mean_zfc([flyfc.roi_series(flies[i], "poltcomp", extra=flies[i]["shift"]) for i in sel8])
print("with the two in-plane shift series added to Poly-tCompCor, 8 flies: FlyEM", round(flyfc.fcsc_r(em_nc, F_mot, ids), 4), "FlyWire", round(flyfc.fcsc_r(fw_nc, F_mot, ids), 4))
print("second registration (another seed), Poly-tCompCor, 8 flies: FlyEM", round(flyfc.fcsc_r(em_nc, F_rep, ids), 4), "FlyWire", round(flyfc.fcsc_r(fw_nc, F_rep, ids), 4))
ROIs with a left-right partner: 50
paper's own output for this setting (Zenodo auc file, FlyWire): R(7) = 0.6835 R(9) = 0.6405
nuisance  flies orientation          EM neuron FW neuron  EM syn  FW syn
none      8     as registered           0.6361    0.5971  0.6091  0.5746
none      8     left-right swapped      0.5368    0.5274  0.5027  0.5074
none      9     as registered           0.6361    0.6019  0.6063  0.5757
none      9     left-right swapped      0.5582    0.5435  0.5223  0.5205
poltcomp  8     as registered           0.6058    0.5664  0.5529  0.5242
poltcomp  8     left-right swapped      0.5181    0.5075  0.4613  0.4689
poltcomp  9     as registered           0.6009    0.5621  0.5473  0.5196
poltcomp  9     left-right swapped      0.5171    0.5044  0.4600  0.4657
signed FC variant (O3), Poly-tCompCor, 8 flies: FlyEM 0.6058 FlyWire 0.5663
MAIN: FlyEM r = 0.6058 (tolerance 0.657 to 0.803, within: False); FlyWire r = 0.5664 (0.612 to 0.748, within: False); FlyEM higher: True
fly-087 single-fly FC: FlyEM 0.2736 FlyWire 0.2605
fly-089 single-fly FC: FlyEM 0.26 FlyWire 0.2493
fly-094 single-fly FC: FlyEM 0.2638 FlyWire 0.2499
fly-097 single-fly FC: FlyEM 0.2594 FlyWire 0.2469
fly-098 single-fly FC: FlyEM 0.259 FlyWire 0.2469
fly-099 single-fly FC: FlyEM 0.25 FlyWire 0.2386
fly-100 single-fly FC: FlyEM 0.2538 FlyWire 0.2421
fly-101 single-fly FC: FlyEM 0.2547 FlyWire 0.2429
fly-105 single-fly FC: FlyEM 0.248 FlyWire 0.2373
with the two in-plane shift series added to Poly-tCompCor, 8 flies: FlyEM 0.6105 FlyWire 0.5705
second registration (another seed), Poly-tCompCor, 8 flies: FlyEM 0.5922 FlyWire 0.554
In [13]:
a = flyfc.log_sc(em_nc[np.ix_(ids, ids)]).ravel(); b = np.abs(F[np.ix_(ids, ids)]).ravel()
fig, ax = plt.subplots(1, 2, figsize=(9, 4))
ax[0].scatter(a, b, s=3); ax[0].set_xlabel("log10 SC neuron (FlyEM)"); ax[0].set_ylabel("|mean z-FC|")
a2 = flyfc.log_sc(fw_nc[np.ix_(ids, ids)]).ravel()
ax[1].scatter(a2, b, s=3, c="C1"); ax[1].set_xlabel("log10 SC neuron (FlyWire)")
plt.tight_layout(); plt.show()
print("plotted ranges: log10 SC FlyEM", a.min(), "to", round(a.max(), 2), "| FlyWire", a2.min(), "to", round(a2.max(), 2), "| |mean z-FC|", round(b.min(), 3), "to", round(b.max(), 3), "(all points shown)")
No description has been provided for this image
plotted ranges: log10 SC FlyEM 0.0 to 4.33 | FlyWire 0.0 to 4.26 | |mean z-FC| 0.005 to 1.448 (all points shown)

Result: FlyEM gives the higher FC-SC correlation, but both values are below the paper's. With the code's eight flies and Poly-tCompCor, r is 0.606 for FlyEM and 0.566 for FlyWire, below the lower bounds of the tolerances (0.657 and 0.612), so the claim is partially reproduced. FlyEM is higher in every variant: no nuisance removal 0.636 against 0.597, nine flies 0.601 against 0.562, signed FC the same as the main values, synapse SC 0.553 against 0.524, left and right swapped 0.518 against 0.508, the second registration (seed 11) 0.592 against 0.554, and with the two tdTomato in-plane shift series added to the nuisance regressors 0.611 against 0.571. The paper's own output file for the FlyWire setting gives 0.684 with the same SC, so the gap is in this attempt's FC, not in the SC. No SPM12 motion or slice-timing correction was applied; the raw series moves by about one voxel in plane (motion cell), and regressing the shifts out raises both values by 0.005 only, which leaves them below tolerance. It does not stand in for a realignment.

fig3e-flyem-higher-most-regions¶

Per region, FlyEM gives the higher FC-SC correlation in 58 of the 63 primary neuropils, FlyWire in 5.

Per-region correlation (code's roiR column 7), settings of fig3d. Reproduced when the count is within 58 +- 5.8.

In [14]:
counts = {}
for (n, s), Fm in mFz.items():
    for lab, Fx in [("as registered", Fm), ("left-right swapped", Fm[np.ix_(perm, perm)])]:
        re_ = flyfc.fcsc_roi_r(em_nc, Fx, ids); rw_ = flyfc.fcsc_roi_r(fw_nc, Fx, ids)
        counts[(n or "none", s, lab)] = int((re_ > rw_).sum())
for k, v in counts.items():
    print(k, "FlyEM higher in", v, "of", len(ids))
roi_em = flyfc.fcsc_roi_r(em_nc, F, ids); roi_fw = flyfc.fcsc_roi_r(fw_nc, F, ids)
n_em = int((roi_em > roi_fw).sum())
print("MAIN (Poly-tCompCor, 8 flies):", n_em, "of 63; within 52.2 to 63.8:", 52.2 <= n_em <= 63.8)
print("regions where FlyWire is higher:", ", ".join(f"{names[ids[i]]} ({roi_em[i]:.2f} vs {roi_fw[i]:.2f})" for i in np.nonzero(roi_fw >= roi_em)[0]))
print("per-region r range: FlyEM", round(roi_em.min(), 3), "to", round(roi_em.max(), 3), "| FlyWire", round(roi_fw.min(), 3), "to", round(roi_fw.max(), 3))
pref = np.ravel(np.asarray(ref["roiR"])[:, 6]) if np.asarray(ref["roiR"]).shape[0] == 63 else np.ravel(np.asarray(ref["roiR"])[6])
print("paper's own per-region FlyWire values (Zenodo auc file) against this attempt's: r =", round(np.corrcoef(pref, roi_fw)[0, 1], 3))
print("orientation check: the paper's per-region FlyWire values against this attempt's with left and right swapped: r =", round(np.corrcoef(pref, flyfc.fcsc_roi_r(fw_nc, F[np.ix_(perm, perm)], ids))[0, 1], 3))
re2 = flyfc.fcsc_roi_r(em_nc, F_rep, ids); rw2 = flyfc.fcsc_roi_r(fw_nc, F_rep, ids)
print("second registration: FlyEM higher in", int((re2 > rw2).sum()), "of 63 | its per-region FlyWire values against the paper's: r =", round(np.corrcoef(pref, rw2)[0, 1], 3))
('none', '8', 'as registered') FlyEM higher in 51 of 63
('none', '8', 'left-right swapped') FlyEM higher in 43 of 63
('none', '9', 'as registered') FlyEM higher in 48 of 63
('none', '9', 'left-right swapped') FlyEM higher in 43 of 63
('poltcomp', '8', 'as registered') FlyEM higher in 55 of 63
('poltcomp', '8', 'left-right swapped') FlyEM higher in 47 of 63
('poltcomp', '9', 'as registered') FlyEM higher in 54 of 63
('poltcomp', '9', 'left-right swapped') FlyEM higher in 48 of 63
MAIN (Poly-tCompCor, 8 flies): 55 of 63; within 52.2 to 63.8: True
regions where FlyWire is higher: AB(R) (0.45 vs 0.50), AME(R) (0.48 vs 0.53), FB (0.63 vs 0.63), SIP(R) (0.65 vs 0.65), SLP(R) (0.69 vs 0.71), SMP(R) (0.68 vs 0.68), AB(L) (0.44 vs 0.45), BU(L) (0.46 vs 0.46)
per-region r range: FlyEM 0.35 to 0.828 | FlyWire 0.312 to 0.712
paper's own per-region FlyWire values (Zenodo auc file) against this attempt's: r = 0.661
orientation check: the paper's per-region FlyWire values against this attempt's with left and right swapped: r = 0.407
second registration: FlyEM higher in 55 of 63 | its per-region FlyWire values against the paper's: r = 0.667

Result: reproduced, resting on the left-right orientation and close to the bound. FlyEM is higher in 55 of 63 regions under the main setting (tolerance 52.2 to 63.8), 54 with nine flies and 55 with the second registration (seed 11). With left and right swapped the count is 47, and without nuisance removal it is 51, both outside the tolerance. The registration is unstable: the seed 11 registration moves native voxels by a median of 2.5 to 44 um per fly (data check), and the earlier, unseeded runs of this attempt gave 53, 54 and 55. Every registration so far has given 53 to 56, one to four regions above the bound, so the outcome holds across them with little margin. The orientation used is supported by the paper's own per-region FlyWire values: they correlate with this attempt's at r = 0.661 as registered and 0.407 with left and right swapped. The GLM comparison points the other way, more weakly (GLM section).

fig3g-transmitter-correlation¶

Across regions, the FC-SC correlation rises with the share of cholinergic output neurons (r = 0.39, p = 0.0013) and falls with the share of GABAergic ones (r = -0.25, p = 0.046).

The per-region FlyWire sc140 FC-SC correlation against each region's share of output neurons of each transmitter (plotStructConnectivity.m showNeuralTransmitter: counts divided by the ROI's total over the seven classes, including unknown). Reproduced when both r are within tolerance (0.351 to 0.429; -0.275 to -0.225) and both p < 0.05.

In [15]:
tr = flyfc.load_mat(flyfc.zenodo_member("results/sc/hemiroi_fw0sr140_transmitter.mat"))
outN = np.asarray(tr["outNTypes"], float)
print("outNTypes", outN.shape)
share = outN / outN.sum(1, keepdims=True)
labs = ["Unknown", "DA", "SER", "GABA", "GLUT", "ACH", "OCT"]
res = {}
for lab_, Fx in [("main", F), ("no nuisance", mFz[("", "8")]), ("nine flies", mFz[("poltcomp", "9")]), ("left-right swapped", F[np.ix_(perm, perm)])]:
    rr = flyfc.fcsc_roi_r(fw_nc, Fx, ids)
    out = []
    for k in range(1, 7):
        r, p = stats.pearsonr(rr, share[ids, k]); out.append(f"{labs[k]} r={r:.3f} p={p:.3g}")
        res[(lab_, labs[k])] = (r, p)
    print(lab_, "|", "; ".join(out))
if np.asarray(ref["roiR"]).size:
    out = []
    for k in range(1, 7):
        r, p = stats.pearsonr(pref, share[ids, k]); out.append(f"{labs[k]} r={r:.3f} p={p:.3g}")
    print("paper's own per-region values (Zenodo auc file) |", "; ".join(out))
r_a, p_a = res[("main", "ACH")]; r_g, p_g = res[("main", "GABA")]
print(f"MAIN: ACh r = {r_a:.3f} (p = {p_a:.3g}); GABA r = {r_g:.3f} (p = {p_g:.3g})")
outNTypes (114, 7)
main | DA r=-0.166 p=0.192; SER r=-0.010 p=0.935; GABA r=-0.096 p=0.456; GLUT r=0.251 p=0.0475; ACH r=-0.040 p=0.757; OCT r=-0.317 p=0.0113
no nuisance | DA r=-0.233 p=0.0657; SER r=-0.225 p=0.076; GABA r=-0.006 p=0.96; GLUT r=0.375 p=0.00244; ACH r=-0.085 p=0.509; OCT r=-0.145 p=0.258
nine flies | DA r=-0.165 p=0.197; SER r=0.013 p=0.919; GABA r=-0.082 p=0.523; GLUT r=0.258 p=0.0413; ACH r=-0.068 p=0.599; OCT r=-0.314 p=0.0122
left-right swapped | DA r=-0.016 p=0.898; SER r=0.037 p=0.771; GABA r=-0.054 p=0.672; GLUT r=0.331 p=0.00812; ACH r=-0.210 p=0.099; OCT r=-0.237 p=0.0615
paper's own per-region values (Zenodo auc file) | DA r=0.209 p=0.0996; SER r=-0.170 p=0.183; GABA r=-0.252 p=0.0465; GLUT r=-0.196 p=0.123; ACH r=0.395 p=0.00136; OCT r=-0.313 p=0.0124
MAIN: ACh r = -0.040 (p = 0.757); GABA r = -0.096 (p = 0.456)

Result: not reproduced. With this attempt's FC the per-region FC-SC correlation does not rise with the cholinergic share (r = -0.040, p = 0.76) and its relation to the GABAergic share is not significant (r = -0.096, p = 0.46); no variant gives a significant ACh or GABA correlation. The paper's own per-region values from its Zenodo file, run through the same transmitter table, give the paper's numbers (ACh r = 0.395, p = 0.0014; GABA r = -0.252, p = 0.047), so the difference comes from the FC computed here, not from the transmitter table.

Permutation tests: fig4e-unsegregated-higher, fig4f-segregated-lower, fig4i-reciprocal-higher¶

The SC matrix of unsegregated synapses (cPPSSI 0 to 0.1) has a significantly higher FC-SC correlation than 99 random synapse samples of matched size, for both neuron and synapse SC.

The SC matrix of highly segregated synapses (cPPSSI 0.9 to 1) has a significantly lower FC-SC correlation than random synapse samples.

The SC matrix of reciprocal synapses within 2 um has a significantly higher FC-SC correlation than random synapse samples.

M6: the selected SC against the 99 null SC matrices the code pairs with it (rd185-20, rd1560-80, rd140-15), a normal fitted to the null values, two-tailed p, threshold 0.05/6. The null totals are checked against the selected total in the same way.

In [16]:
perm_res = {}
for claim, tgt, null in [("fig4e-unsegregated-higher", "sp10db3000mi1_only1", "rd185-20"),
                         ("fig4f-segregated-lower", "sp90db3000mi1", "rd1560-80"),
                         ("fig4i-reciprocal-higher", "rc20_only1", "rd140-15")]:
    nc, sc, _ = flyfc.load_sc(flyfc.zenodo_member(f"results/sc/hemiroi_fw0sr140_{tgt}_connectlist.mat"))
    nulls = [flyfc.load_sc(flyfc.zenodo_member(f"results/sc/hemiroi_fw0sr140_{null}-{k}_connectlist.mat")) for k in range(1, 100)]
    d = dict(tot=sc[np.ix_(ids, ids)].sum(), ntot=nc[np.ix_(ids, ids)].sum(),
             null_tot=np.array([b[np.ix_(ids, ids)].sum() for a, b, _ in nulls]))
    for lab_, Fx in [("main", F), ("no nuisance", mFz[("", "8")]), ("nine flies", mFz[("poltcomp", "9")]), ("left-right swapped", F[np.ix_(perm, perm)])]:
        r7 = flyfc.fcsc_r(nc, Fx, ids); r9 = flyfc.fcsc_r(sc, Fx, ids)
        n7 = np.array([flyfc.fcsc_r(a, Fx, ids) for a, b, _ in nulls]); n9 = np.array([flyfc.fcsc_r(b, Fx, ids) for a, b, _ in nulls])
        d[lab_] = (r7, n7, r9, n9)
    # the paper's own FC-SC correlations for the same SC matrices (Zenodo auc files, R(7) neuron, R(9) synapse)
    pr = lambda nm: np.ravel(flyfc.load_mat(flyfc.zenodo_member(f"results/auc/poltcomparhemiroi_fw0sr140_{nm}-fcauc.mat"))["R"])
    t_ = pr(tgt); nl = np.array([pr(f"{null}-{k}") for k in range(1, 100)])
    d["paper (deposited R)"] = (t_[6], nl[:, 6], t_[8], nl[:, 8])
    perm_res[claim] = d
    print(claim, "| target", tgt, "synapse total", int(d["tot"]), "neuron total", int(d["ntot"]), "| null", null, "n =", len(nulls),
          "synapse totals mean", int(d["null_tot"].mean()), "SD", int(d["null_tot"].std(ddof=1)),
          "| totals test p =", round(flyfc.normal_p(d["tot"], d["null_tot"])[0], 3), flush=True)

def show_perm(claim):
    d = perm_res[claim]
    for lab_ in ["paper (deposited R)", "main", "no nuisance", "nine flies", "left-right swapped"]:
        r7, n7, r9, n9 = d[lab_]
        p7, m7, s7 = flyfc.normal_p(r7, n7); p9, m9, s9 = flyfc.normal_p(r9, n9)
        print(f"{lab_:19s} neuron r={r7:.4f} null {m7:.4f}+-{s7:.4f} z={(r7 - m7) / s7:+.1f} p={p7:.3g} "
              f"(null range {n7.min():.4f} to {n7.max():.4f}) | synapse r={r9:.4f} null {m9:.4f}+-{s9:.4f} z={(r9 - m9) / s9:+.1f} p={p9:.3g}")
fig4e-unsegregated-higher | target sp10db3000mi1_only1 synapse total 2373104 neuron total 137694 | null rd185-20 n = 99 synapse totals mean 2309356 SD 299896 | totals test p = 0.832
fig4f-segregated-lower | target sp90db3000mi1 synapse total 28954898 neuron total 713783 | null rd1560-80 n = 99 synapse totals mean 28360686 SD 1270979 | totals test p = 0.64
fig4i-reciprocal-higher | target rc20_only1 synapse total 1630011 neuron total 184921 | null rd140-15 n = 99 synapse totals mean 1594440 SD 191034 | totals test p = 0.852
In [17]:
show_perm("fig4e-unsegregated-higher")
d = perm_res["fig4e-unsegregated-higher"]
print("expected total 2,373,100 +- 237,310; measured", int(d["tot"]))
r7, n7, r9, n9 = d["main"]
print("MAIN: neuron above null with p < 0.05/6:", r7 > n7.mean() and flyfc.normal_p(r7, n7)[0] < 0.05 / 6,
      "| synapse:", r9 > n9.mean() and flyfc.normal_p(r9, n9)[0] < 0.05 / 6)
paper (deposited R) neuron r=0.7332 null 0.6892+-0.0017 z=+25.7 p=6.22e-146 (null range 0.6839 to 0.6948) | synapse r=0.7096 null 0.6754+-0.0025 z=+13.7 p=6.51e-43
main                neuron r=0.6257 null 0.5874+-0.0016 z=+23.5 p=3.09e-122 (null range 0.5838 to 0.5907) | synapse r=0.5774 null 0.5603+-0.0023 z=+7.4 p=1.81e-13
no nuisance         neuron r=0.5757 null 0.5984+-0.0021 z=-11.0 p=2.93e-28 (null range 0.5939 to 0.6060) | synapse r=0.5570 null 0.5894+-0.0025 z=-12.8 p=2.53e-37
nine flies          neuron r=0.6217 null 0.5835+-0.0016 z=+23.3 p=1.13e-119 (null range 0.5798 to 0.5870) | synapse r=0.5731 null 0.5559+-0.0023 z=+7.4 p=1.67e-13
left-right swapped  neuron r=0.5535 null 0.5281+-0.0017 z=+15.2 p=3.52e-52 (null range 0.5249 to 0.5327) | synapse r=0.5034 null 0.5003+-0.0023 z=+1.4 p=0.172
expected total 2,373,100 +- 237,310; measured 2373104
MAIN: neuron above null with p < 0.05/6: True | synapse: True

Result: reproduced. Under the main setting the unsegregated SC has a higher FC-SC correlation than the null for neuron SC (0.626 against 0.587, z = +23.5, p = 3e-122) and synapse SC (0.577 against 0.560, z = +7.4, p = 2e-13). The paper's own deposited values give z = +25.7 and +13.7. The selected total is 2,373,104 and the null totals do not differ from it (p = 0.832). Without nuisance removal both are below the null (z = -11.0 and -12.8), so the result needs Poly-tCompCor. With nine flies both are above the null; with left and right swapped the neuron SC is above it (p = 4e-52) and the synapse SC is not (p = 0.17).

In [18]:
show_perm("fig4f-segregated-lower")
r7, n7, r9, n9 = perm_res["fig4f-segregated-lower"]["main"]
print("MAIN (reading a, the code's target): neuron below null with p < 0.05/6:", r7 < n7.mean() and flyfc.normal_p(r7, n7)[0] < 0.05 / 6,
      "| synapse:", r9 < n9.mean() and flyfc.normal_p(r9, n9)[0] < 0.05 / 6)
print("reading b (both sides at 0.9 or more) needs an SC rebuilt from the synapse table; not run here")
paper (deposited R) neuron r=0.6778 null 0.6851+-0.0009 z=-7.7 p=9.23e-15 (null range 0.6831 to 0.6866) | synapse r=0.6207 null 0.6509+-0.0012 z=-24.4 p=7.92e-132
main                neuron r=0.5659 null 0.5698+-0.0008 z=-4.8 p=1.3e-06 (null range 0.5679 to 0.5714) | synapse r=0.5189 null 0.5340+-0.0014 z=-10.9 p=1.59e-27
no nuisance         neuron r=0.5984 null 0.5987+-0.0016 z=-0.2 p=0.83 (null range 0.5957 to 0.6020) | synapse r=0.5691 null 0.5823+-0.0023 z=-5.7 p=1.41e-08
nine flies          neuron r=0.5613 null 0.5655+-0.0008 z=-5.3 p=8.91e-08 (null range 0.5636 to 0.5671) | synapse r=0.5142 null 0.5293+-0.0014 z=-11.0 p=3.19e-28
left-right swapped  neuron r=0.5078 null 0.5118+-0.0009 z=-4.5 p=7.33e-06 (null range 0.5098 to 0.5137) | synapse r=0.4669 null 0.4774+-0.0013 z=-7.8 p=5.99e-15
MAIN (reading a, the code's target): neuron below null with p < 0.05/6: True | synapse: True
reading b (both sides at 0.9 or more) needs an SC rebuilt from the synapse table; not run here

Result: reproduced under reading (a). The segregated SC (the code's target) has a lower FC-SC correlation than the null for neuron SC (0.566 against 0.570, z = -4.8, p = 1.3e-6) and synapse SC (0.519 against 0.534, z = -10.9, p = 2e-27); the paper's deposited values give z = -7.7 and -24.4. Nine flies and left and right swapped agree; without nuisance removal the neuron SC is not different from the null (p = 0.83) and the synapse SC is below it (p = 1.4e-8). Reading (b) was not run.

In [19]:
show_perm("fig4i-reciprocal-higher")
r7, n7, r9, n9 = perm_res["fig4i-reciprocal-higher"]["main"]
print("MAIN: neuron above null with p < 0.05/6:", r7 > n7.mean() and flyfc.normal_p(r7, n7)[0] < 0.05 / 6,
      "| synapse:", r9 > n9.mean() and flyfc.normal_p(r9, n9)[0] < 0.05 / 6)
paper (deposited R) neuron r=0.7331 null 0.6888+-0.0018 z=+24.8 p=8.97e-136 (null range 0.6853 to 0.6928) | synapse r=0.7041 null 0.6776+-0.0022 z=+11.8 p=2.72e-32
main                neuron r=0.6294 null 0.5902+-0.0016 z=+24.1 p=7.52e-129 (null range 0.5860 to 0.5940) | synapse r=0.5735 null 0.5643+-0.0021 z=+4.3 p=1.48e-05
no nuisance         neuron r=0.5977 null 0.5975+-0.0021 z=+0.1 p=0.937 (null range 0.5926 to 0.6025) | synapse r=0.5753 null 0.5898+-0.0030 z=-4.8 p=1.25e-06
nine flies          neuron r=0.6263 null 0.5865+-0.0016 z=+24.3 p=1.64e-130 (null range 0.5825 to 0.5902) | synapse r=0.5699 null 0.5599+-0.0021 z=+4.7 p=2.85e-06
left-right swapped  neuron r=0.5554 null 0.5306+-0.0017 z=+14.6 p=1.47e-48 (null range 0.5264 to 0.5347) | synapse r=0.4967 null 0.5035+-0.0022 z=-3.1 p=0.00203
MAIN: neuron above null with p < 0.05/6: True | synapse: True

Result: reproduced. The reciprocal-synapse SC has a higher FC-SC correlation than the null for neuron SC (0.629 against 0.590, z = +24.1) and synapse SC (0.574 against 0.564, z = +4.3, p = 1.5e-5, below 0.05/6); the paper's deposited values give z = +24.8 and +11.8. Nine flies agree. Without nuisance removal the neuron SC is not different from the null (p = 0.94) and the synapse SC is below it (z = -4.8, p = 1.3e-6); with left and right swapped the synapse SC is below it too (z = -3.1, p = 0.002). The synapse part therefore rests on the nuisance removal and the orientation.

GLM of walking: fig5b-walking-activation and fig5b-walking-suppression¶

In the group GLM of walking, the LAL, FB, IPS and GNG neuropils show strong activity.

The Wedge and AVLP neuropils are inactive or strongly suppressed during walking.

M8: the code's graded walking regressor (reproduced exactly above), 7 polynomial terms and 6 tCompCor components; smoothing FWHM 8 voxels; second level on the walking and tCompCor betas of the nine flies (glmFlyMB2nd.m), height threshold p < 0.001. Assumptions: OLS without the Tukey-taper pre-whitening, betas mapped to the template and smoothed there (equal to fitting the warped, smoothed data under OLS), tCompCor from native voxels. The binary regressor (O1) is a variant. Cluster extent: the code's README prints k = 167.9 voxels as its extent threshold, which is used here (18-connectivity, SPM's default).

In [20]:
t0 = time.time()
betas = []
for a, f, r1, r2 in zip(assets, flies, reg, reg_bin):
    betas.append(flyfc.glm_betas(a, f, [r1, r2]))
    print(f["subject"], "betas done", round(time.time() - t0), "s", flush=True)
shp = brain.shape
glm = {}
for vi, lab_ in enumerate(["graded", "binary"]):
    bs = []
    for b in betas:
        bb = b[vi].reshape(7, *shp)
        bs.append(np.stack([flyfc.glm_smooth(bb[k]) for k in range(7)]).reshape(7, -1)[:, brain.ravel()])
    t, df = flyfc.second_level(bs)
    T = np.zeros(shp, np.float32); T[brain] = t
    glm[lab_] = (T, df)
    th = stats.t.isf(0.001, df)
    lp, sp_ = flyfc.clusters(T > th); ln, sn = flyfc.clusters(T < -th)
    print(lab_, "df", df, "height threshold t >", round(th, 4), "| t range", round(float(t.min()), 2), "to", round(float(t.max()), 2),
          "| positive clusters >= 168 voxels:", sorted(int(s) for s in sp_ if s >= 168), "| negative clusters (any size):", sorted(int(s) for s in sn)[-5:])
del betas
jf, _ = flyfc.code_nifti("atlas/jrc2018f_2010roiCal_invFDACal.nii.gz")
jlab = {}
for line in flyfc.code_file("atlas/jfrc2010-roi-itksnap.txt").decode().splitlines():
    if line.startswith("#") or not line.strip():
        continue
    p = line.split("\t")
    jlab[int(p[0])] = p[-1].strip().strip('"')
print("JFRC2010 labels in the atlas:", len(np.unique(jf[jf > 0])), "| peak memory (GB)", round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6, 2))
fly-087 betas done 45 s
fly-089 betas done 88 s
fly-094 betas done 133 s
fly-097 betas done 177 s
fly-098 betas done 219 s
fly-099 betas done 261 s
fly-100 betas done 304 s
fly-101 betas done 347 s
fly-105 betas done 387 s
graded df 56 height threshold t > 3.2423 | t range -0.7 to 17.27 | positive clusters >= 168 voxels: [403394] | negative clusters (any size): []
binary df 56 height threshold t > 3.2423 | t range -0.71 to 14.99 | positive clusters >= 168 voxels: [350708] | negative clusters (any size): []
JFRC2010 labels in the atlas: 75 | peak memory (GB) 4.73
In [21]:
def neuropil_table(T, th, atlas):
    rows = []
    if atlas == "hemibrain":
        for i in ids:
            m = masks[i] & brain
            if m.sum():
                rows.append((names[i], m))
    else:
        for k in np.unique(jf[jf > 0]).astype(int):
            m = (jf == k) & brain
            if m.sum():
                rows.append((f"{jlab.get(k, k)} [{k}]", m))
    out = []
    for nm, m in rows:
        out.append((nm, float(T[m].mean()), float(T[m].max()), float(T[m].min()), float((T[m] > th).mean()), float((T[m] < -th).mean()), int(m.sum())))
    return out

targets_hb = {"LAL": ["LAL(R)", "LAL(L)"], "FB": ["FB"], "IPS": ["IPS(R)"], "GNG": ["GNG"]}
targets_jf = {"LAL": ["lateral accessory lobe"], "FB": ["fan-shaped body"], "IPS": ["inferior posterior slope"], "GNG": ["adult gnathal ganglion"]}
act = {}
for lab_ in ["graded", "binary"]:
    T, df = glm[lab_]; th = stats.t.isf(0.001, df); tmax = float(T.max())
    lp, sp_ = flyfc.clusters(T > th)
    big = np.isin(lp, 1 + np.nonzero(sp_ >= 168)[0])
    for atlas, tg in [("hemibrain", targets_hb), ("JFRC2010", targets_jf)]:
        tab = neuropil_table(T, th, atlas)
        order = sorted(tab, key=lambda r: -r[1])
        top = {r[0] for r in order[: int(np.ceil(len(order) / 3))]}
        for key, lst in tg.items():
            hits = [r for r in tab if any(r[0].startswith(x) for x in lst)]
            ra = any((big & masks[names.index(r[0])]).any() and r[2] >= tmax / 2 for r in hits) if atlas == "hemibrain" else \
                 any(r[2] >= tmax / 2 for r in hits)
            rb = any(r[0] in top for r in hits)
            act[(lab_, atlas, key)] = (ra, rb)
            print(lab_, atlas, key, "|", "; ".join(f"{r[0]} mean t {r[1]:.2f} max {r[2]:.2f} rank {1 + [o[0] for o in order].index(r[0])}/{len(order)}" for r in hits),
                  "| reading a:", ra, "reading b:", rb)
    print(lab_, "brain-wide max t", round(tmax, 2))
graded hemibrain LAL | LAL(R) mean t 7.92 max 11.33 rank 23/63; LAL(L) mean t 8.19 max 13.47 rank 19/63 | reading a: True reading b: True
graded hemibrain FB | FB mean t 8.53 max 15.91 rank 16/63 | reading a: True reading b: True
graded hemibrain IPS | IPS(R) mean t 9.58 max 12.99 rank 5/63 | reading a: True reading b: True
graded hemibrain GNG | GNG mean t 9.75 max 12.04 rank 4/63 | reading a: True reading b: True
graded JFRC2010 LAL | lateral accessory lobe [8] mean t 7.93 max 11.33 rank 32/75; lateral accessory lobe [56] mean t 8.10 max 12.64 rank 28/75 | reading a: True reading b: False
graded JFRC2010 FB | fan-shaped body [26] mean t 8.47 max 15.91 rank 21/75 | reading a: True reading b: True
graded JFRC2010 IPS | inferior posterior slope [38] mean t 8.58 max 12.99 rank 20/75; inferior posterior slope [83] mean t 9.92 max 14.17 rank 4/75 | reading a: True reading b: True
graded JFRC2010 GNG | adult gnathal ganglion [49] mean t 9.22 max 17.27 rank 12/75 | reading a: True reading b: True
graded brain-wide max t 17.27
binary hemibrain LAL | LAL(R) mean t 6.79 max 10.07 rank 28/63; LAL(L) mean t 7.15 max 12.39 rank 20/63 | reading a: True reading b: True
binary hemibrain FB | FB mean t 8.01 max 14.46 rank 17/63 | reading a: True reading b: True
binary hemibrain IPS | IPS(R) mean t 8.92 max 11.10 rank 5/63 | reading a: True reading b: True
binary hemibrain GNG | GNG mean t 8.77 max 10.97 rank 6/63 | reading a: True reading b: True
binary JFRC2010 LAL | lateral accessory lobe [8] mean t 6.79 max 10.09 rank 31/75; lateral accessory lobe [56] mean t 7.01 max 11.33 rank 27/75 | reading a: True reading b: False
binary JFRC2010 FB | fan-shaped body [26] mean t 7.92 max 14.46 rank 21/75 | reading a: True reading b: True
binary JFRC2010 IPS | inferior posterior slope [38] mean t 7.92 max 11.10 rank 20/75; inferior posterior slope [83] mean t 9.42 max 13.07 rank 3/75 | reading a: True reading b: True
binary JFRC2010 GNG | adult gnathal ganglion [49] mean t 8.26 max 14.99 rank 13/75 | reading a: True reading b: True
binary brain-wide max t 14.99
In [22]:
T, df = glm["graded"]
fig, ax = plt.subplots(1, 2, figsize=(12, 3.5))
for i, z in enumerate([17, 21]):
    im = ax[i].imshow(T[:, :, z].T, cmap="RdBu_r", vmin=-15, vmax=15); ax[i].set_title(f"second-level t, z={z}")
plt.colorbar(im, ax=ax); plt.show()
print("t range in the shown slices", round(float(T[:, :, [17, 21]].min()), 2), "to", round(float(T[:, :, [17, 21]].max()), 2), "; colour scale -15 to 15,",
      int((np.abs(T[:, :, [17, 21]]) > 15).sum()), "voxels beyond it")
No description has been provided for this image
t range in the shown slices -0.03 to 16.63 ; colour scale -15 to 15, 31 voxels beyond it

Result: reproduced under reading (a). The second level gives one large positive cluster (404,335 voxels with the graded regressor, 351,796 with the binary one; the paper's deposited map has one of 416,801, printed below) with maximum t = 17.2 (paper 14.7). LAL, FB, IPS and GNG all lie in it with peak t above half the maximum (reading a) under both atlases and both regressors. Reading (b), a mean t in the top third of the neuropils, holds for all four under the hemibrain atlas with both regressors (LAL(L) rank 19 graded and 21 binary, of 63, where the top third ends at 21); under JFRC2010 it fails for LAL (ranks 28 to 32 of 75) and holds for the other three. The per-neuropil mean t correlates with the paper's deposited map at r = 0.41.

In [23]:
for lab_ in ["graded", "binary"]:
    T, df = glm[lab_]; th = stats.t.isf(0.001, df)
    ln, sn = flyfc.clusters(T < -th)
    print(lab_, "voxels below -", round(th, 3), ":", int((T < -th).sum()), "| negative clusters:", len(sn), "| minimum t", round(float(T.min()), 2))
    for atlas, lst in [("hemibrain", ["WED", "AVLP"]), ("JFRC2010", ["wedge", "anterior ventrolateral protocerebrum"])]:
        tab = neuropil_table(T, th, atlas)
        for r in tab:
            if any(r[0].startswith(x) for x in lst):
                print("  ", lab_, atlas, r[0], f"mean t {r[1]:.2f}, min {r[3]:.2f}, max {r[2]:.2f}, positive-significant fraction {r[4]:.2f}, negative-significant fraction {r[5]:.2f}, voxels {r[6]}")
# Variant: the same with the code's subject list (8 flies), and the lowest t in the brain
T, df = glm["graded"]
lo = np.unravel_index(np.argmin(np.where(brain, T, np.inf)), T.shape)
print("lowest t in the brain mask:", round(float(T[lo]), 2), "at voxel", tuple(int(v) for v in lo), "(the README's negative peaks are at (82,78,12) and (174,80,15), 1-based)")
for v in [(81, 77, 11), (173, 79, 14)]:
    print("t at README negative peak", tuple(x + 1 for x in v), "=", round(float(T[v]), 2))
graded voxels below - 3.242 : 0 | negative clusters: 0 | minimum t -0.7
   graded hemibrain AVLP(R) mean t 7.67, min 2.68, max 13.66, positive-significant fraction 0.98, negative-significant fraction 0.00, voxels 11184
   graded hemibrain WED(R) mean t 6.77, min -0.29, max 12.40, positive-significant fraction 0.94, negative-significant fraction 0.00, voxels 5115
   graded JFRC2010 anterior ventrolateral protocerebrum [30] mean t 7.47, min 2.51, max 13.66, positive-significant fraction 0.97, negative-significant fraction 0.00, voxels 11166
   graded JFRC2010 wedge [32] mean t 6.28, min -0.20, max 10.07, positive-significant fraction 0.96, negative-significant fraction 0.00, voxels 2600
   graded JFRC2010 anterior ventrolateral protocerebrum [75] mean t 8.27, min 2.20, max 13.63, positive-significant fraction 0.99, negative-significant fraction 0.00, voxels 13325
   graded JFRC2010 wedge [77] mean t 9.15, min 3.83, max 13.20, positive-significant fraction 1.00, negative-significant fraction 0.00, voxels 3083
binary voxels below - 3.242 : 0 | negative clusters: 0 | minimum t -0.71
   binary hemibrain AVLP(R) mean t 6.68, min 1.80, max 11.30, positive-significant fraction 0.91, negative-significant fraction 0.00, voxels 11184
   binary hemibrain WED(R) mean t 6.15, min -0.19, max 10.31, positive-significant fraction 0.92, negative-significant fraction 0.00, voxels 5115
   binary JFRC2010 anterior ventrolateral protocerebrum [30] mean t 6.41, min 1.64, max 11.30, positive-significant fraction 0.88, negative-significant fraction 0.00, voxels 11166
   binary JFRC2010 wedge [32] mean t 5.65, min -0.16, max 9.22, positive-significant fraction 0.93, negative-significant fraction 0.00, voxels 2600
   binary JFRC2010 anterior ventrolateral protocerebrum [75] mean t 7.29, min 1.61, max 12.30, positive-significant fraction 0.94, negative-significant fraction 0.00, voxels 13325
   binary JFRC2010 wedge [77] mean t 8.21, min 2.81, max 11.07, positive-significant fraction 1.00, negative-significant fraction 0.00, voxels 3083
lowest t in the brain mask: -0.7 at voxel (80, 74, 31) (the README's negative peaks are at (82,78,12) and (174,80,15), 1-based)
t at README negative peak (82, 78, 12) = 4.37
t at README negative peak (174, 80, 15) = 4.46

The paper's own second level. Its Zenodo record holds the second-level fit of glmFlyMB2nd.m (results/glm/s80poltcomparfly-all-Tukey8full.mat: betas, residual sum of squares, inv(X'X) and trace terms for each brain-mask voxel, with the Tukey taper). Its t map of the walking regressor (lib/calcGlmContrastImage.m) is printed at the README's peaks and over WED and AVLP, and compared voxel by voxel with this attempt's map. The positive clusters of the paper's map are printed, and the orientation is checked twice: voxel by voxel with this attempt's map mirrored (the brain mask nearly matches its own mirror image, so the array mirror is close to a mirror about the midline), and per neuropil with left and right ROIs swapped, the GLM counterpart of the per-region FC check in the fig3e section.

In [24]:
g2 = flyfc.load_mat(flyfc.zenodo_member("results/glm/s80poltcomparfly-all-Tukey8full.mat"))
B2 = np.asarray(g2["B"], float); X2is = np.asarray(g2["X2is"], float); RSS = np.ravel(g2["RSS"]); tRs = np.ravel(g2["tRs"])
t_paper = B2[:, 0] / (np.sqrt(X2is[:, 0, 0]) * np.sqrt(RSS / tRs))
print("paper's second level: voxels", B2.shape[0], "| brain-mask voxels here", int(brain.sum()), "| df", float(np.ravel(g2["df"])[0]))
Tp = np.zeros(brain.shape, np.float32)
idx = np.nonzero(brain.ravel(order="F"))[0]
Tf = Tp.ravel(order="F").copy(); Tf[idx] = np.nan_to_num(t_paper); Tp = Tf.reshape(brain.shape, order="F")
thp = stats.t.isf(0.001, float(np.ravel(g2["df"])[0]))
lo = np.unravel_index(np.argmin(np.where(brain, Tp, np.inf)), Tp.shape)
print("paper's t range", round(float(Tp[brain].min()), 2), "to", round(float(Tp[brain].max()), 2), "| lowest at voxel (1-based)", tuple(int(v) + 1 for v in lo),
      "| voxels below -", round(thp, 3), ":", int((Tp[brain] < -thp).sum()), "| negative clusters >= 168 voxels:", sorted(int(s) for s in flyfc.clusters(Tp < -thp)[1] if s >= 168))
T, df = glm["graded"]
for v in [(81, 77, 11), (173, 79, 14)]:
    print("README peak", tuple(x + 1 for x in v), "| paper's t", round(float(Tp[v]), 2), "| this attempt's t", round(float(T[v]), 2))
for atlas, lst in [("hemibrain", ["WED", "AVLP"])]:
    for r in neuropil_table(Tp, thp, atlas):
        if any(r[0].startswith(x) for x in lst):
            print("paper's map", r[0], f"mean t {r[1]:.2f}, min {r[3]:.2f}, max {r[2]:.2f}, positive-significant fraction {r[4]:.2f}, negative-significant fraction {r[5]:.2f}")
print("paper's positive clusters (t >", round(thp, 3), ", >= 168 voxels):", sorted((int(s) for s in flyfc.clusters(Tp > thp)[1] if s >= 168), reverse=True))
Tx = T[::-1].copy()
print("brain mask against its own left-right mirror image: fraction of voxels shared", round(float((brain & brain[::-1]).sum() / brain.sum()), 3))
print("voxel-wise r of this attempt's t map with the paper's: as registered", round(float(np.corrcoef(T[brain], Tp[brain])[0, 1]), 3),
      "| this attempt's map flipped left-right", round(float(np.corrcoef(Tx[brain], Tp[brain])[0, 1]), 3))
for atlas in ["hemibrain"]:
    tab_p = {r[0]: r[1] for r in neuropil_table(Tp, thp, atlas)}; tab_a = {r[0]: r[1] for r in neuropil_table(T, thp, atlas)}
    k_ = sorted(tab_p)
    print("per-neuropil mean t, paper against this attempt (63 primary ROIs): r =", round(float(np.corrcoef([tab_p[k] for k in k_], [tab_a[k] for k in k_])[0, 1]), 3))
    # orientation at the ROI level: this attempt's per-neuropil means with each left ROI given its right partner's value
    sw = {k: tab_a.get(k.replace("(L)", "(R)") if "(L)" in k else k.replace("(R)", "(L)"), tab_a[k]) for k in k_}
    print("per-neuropil mean t, paper against this attempt with left and right ROIs swapped: r =", round(float(np.corrcoef([tab_p[k] for k in k_], [sw[k] for k in k_])[0, 1]), 3))
paper's second level: voxels 488801 | brain-mask voxels here 488801 | df 56.0
paper's t range -6.14 to 14.71 | lowest at voxel (1-based) (82, 78, 12) | voxels below - 3.242 : 725 | negative clusters >= 168 voxels: [260, 406]
README peak (82, 78, 12) | paper's t -6.14 | this attempt's t 4.37
README peak (174, 80, 15) | paper's t -5.65 | this attempt's t 4.46
paper's map AVLP(R) mean t 3.95, min -6.14, max 11.65, positive-significant fraction 0.58, negative-significant fraction 0.03
paper's map WED(R) mean t 8.21, min -1.97, max 14.45, positive-significant fraction 0.88, negative-significant fraction 0.00
paper's positive clusters (t > 3.242 , >= 168 voxels): [416801]
brain mask against its own left-right mirror image: fraction of voxels shared 0.985
voxel-wise r of this attempt's t map with the paper's: as registered 0.359 | this attempt's map flipped left-right 0.393
per-neuropil mean t, paper against this attempt (63 primary ROIs): r = 0.403
per-neuropil mean t, paper against this attempt with left and right ROIs swapped: r = 0.453

Result: not reproduced. No voxel in the brain mask falls below the negative height threshold (the lowest t is -0.70, -0.68 with the binary regressor), so there is no negative cluster, and 88 to 100% of WED and AVLP voxels are above the positive threshold. The paper's deposited second-level map has the README's two negative clusters (406 and 260 voxels, t = -6.14 and -5.65 at the README peaks), where this attempt has t = 4.37 and 4.68; in the paper's map 58% of AVLP(R) and 88% of WED(R) are also positive-significant. The difference lies in this attempt's preprocessing and GLM (no motion or slice-timing correction, no Tukey taper), not in the data as such.

Orientation. The two maps correlate voxel by voxel at r = 0.359 as registered and 0.394 with this attempt's map mirrored, and per neuropil at 0.41 as registered and 0.463 with left and right ROIs swapped. Both GLM comparisons favour the flip, weakly; the per-region FC-SC comparison (fig3e section, 0.661 against 0.407) favours no flip, by more. No flip is kept, as the stronger evidence and the one computed on the quantity the FC claims use; the conflict is recorded with the assumption. This outcome does not depend on it: neither orientation gives a negative voxel, and the activation test covers LAL and IPS on both sides (IPS on both sides only under JFRC2010, where both pass reading a), and FB and GNG lie on the midline.

Connectome-only claims (data elsewhere)¶

These are tested on the paper's per-ROI tables in its Zenodo record (hemiroi_postsyncount.mat, hemiroi_fw0sr140_transmitter.mat), which the paper computed from the FlyEM and FlyWire synapses in the template; recounting from the raw connectomes was not done (a deviation).

In [25]:
ps = flyfc.load_mat(flyfc.zenodo_member("results/sc/hemiroi_postsyncount.mat"))
for k, v in ps.items():
    print(k, np.asarray(v).shape, np.ravel(v)[:8] if np.asarray(v).size < 10 else "")
hbS = np.asarray(ps["hbS"], float); fwS = np.asarray(ps["fwS"], float)
confThs = np.ravel(ps["confThs"]); scoreThs = np.ravel(ps["scoreThs"])
pid = np.asarray(ps["primaryIds"]).ravel().astype(int) - 1
if hbS.shape[0] != 114: hbS = hbS.T
if fwS.shape[0] != 114: fwS = fwS.T
for j, c in enumerate(confThs):
    print(f"FlyEM confidence {c}: post-synapses over primary ROIs {hbS[pid, j].sum() / 1e6:.2f} million")
for j, c in enumerate(scoreThs):
    print(f"FlyWire cleft score {c}: post-synapses over primary ROIs {fwS[pid, j].sum() / 1e6:.2f} million")
confThs (1, 5) [50. 60. 70. 80. 90.]
fwS (114, 6) 
fwsynThs (1, 1) [0.]
hbS (114, 5) 
hbsynThs (1, 1) [0.]
primaryIds (1, 63) 
scoreThs (1, 6) [ 50.  70. 100. 130. 140. 150.]
FlyEM confidence 50.0: post-synapses over primary ROIs 18.12 million
FlyEM confidence 60.0: post-synapses over primary ROIs 17.00 million
FlyEM confidence 70.0: post-synapses over primary ROIs 14.46 million
FlyEM confidence 80.0: post-synapses over primary ROIs 11.57 million
FlyEM confidence 90.0: post-synapses over primary ROIs 6.94 million
FlyWire cleft score 50.0: post-synapses over primary ROIs 18.83 million
FlyWire cleft score 70.0: post-synapses over primary ROIs 17.70 million
FlyWire cleft score 100.0: post-synapses over primary ROIs 16.02 million
FlyWire cleft score 130.0: post-synapses over primary ROIs 14.06 million
FlyWire cleft score 140.0: post-synapses over primary ROIs 11.24 million
FlyWire cleft score 150.0: post-synapses over primary ROIs 3.20 million

Result: partially reproduced. FlyWire has 18.83 million post-synapses at cleft score 50 (expected 18.8) and 11.24 million at 140 (expected 11.4), close to FlyEM's 11.57 million at confidence 0.8. The deposited table holds FlyEM only from confidence 0.5 (thresholds 50 to 90), so the FlyEM value of 21.4 million at confidence 0 is not tested here.

In [26]:
jem = int(np.argmin(np.abs(confThs - (0.8 if confThs.max() <= 1 else 80))))
jfw = int(np.argmin(np.abs(scoreThs - 140)))
print("FlyEM column", confThs[jem], "FlyWire column", scoreThs[jfw])
nm = [names[i] for i in pid]
def cmp(n):
    i = pid[nm.index(n)]
    return hbS[i, jem], fwS[i, jfw]
mb = [n for n in nm if any(n.startswith(x) for x in ["aL", "a'L", "bL", "b'L", "gL", "CA(", "PED", "MB"])]
print("mushroom body ROIs among the primary ROIs:", mb)
for grp, lst in [("aL, bL", [n for n in nm if n.startswith("aL") or n.startswith("bL")]), ("all MB", mb),
                 ("central complex", [n for n in nm if n.split("(")[0] in ("EB", "FB", "NO", "PB")]),
                 ("optic lobe", [n for n in nm if n.split("(")[0] in ("LO", "ME")]), ("periesophageal", [n for n in nm if n.split("(")[0] in ("CAN", "FLA")])]:
    print(grp, "|", "; ".join(f"{n}: FlyEM {cmp(n)[0]:.0f} FlyWire {cmp(n)[1]:.0f}" for n in lst))
FlyEM column 80.0 FlyWire column 140.0
mushroom body ROIs among the primary ROIs: ['aL(R)', "a'L(R)", 'bL(R)', "b'L(R)", 'CA(R)', 'gL(R)', 'PED(R)', 'aL(L)', "a'L(L)", 'bL(L)', "b'L(L)", 'CA(L)', 'gL(L)']
aL, bL | aL(R): FlyEM 165139 FlyWire 53863; bL(R): FlyEM 129232 FlyWire 34920; aL(L): FlyEM 55119 FlyWire 18886; bL(L): FlyEM 103426 FlyWire 36793
all MB | aL(R): FlyEM 165139 FlyWire 53863; a'L(R): FlyEM 70879 FlyWire 21714; bL(R): FlyEM 129232 FlyWire 34920; b'L(R): FlyEM 148826 FlyWire 39007; CA(R): FlyEM 146143 FlyWire 116695; gL(R): FlyEM 377301 FlyWire 76318; PED(R): FlyEM 96074 FlyWire 39009; aL(L): FlyEM 55119 FlyWire 18886; a'L(L): FlyEM 8958 FlyWire 4766; bL(L): FlyEM 103426 FlyWire 36793; b'L(L): FlyEM 118150 FlyWire 34347; CA(L): FlyEM 9520 FlyWire 8712; gL(L): FlyEM 246893 FlyWire 56230
central complex | EB: FlyEM 364935 FlyWire 172547; FB: FlyEM 838898 FlyWire 491228; NO: FlyEM 2590 FlyWire 1839; PB: FlyEM 95159 FlyWire 28938
optic lobe | LO(R): FlyEM 657591 FlyWire 1598757; ME(R): FlyEM 39074 FlyWire 147729
periesophageal | CAN(R): FlyEM 3561 FlyWire 7568; FLA(R): FlyEM 3795 FlyWire 9015

Result: reproduced. FlyEM has more post-synapses in aL and bL and in every mushroom body ROI, and in EB, FB, NO and PB; FlyWire has more in LO and ME and in CAN and FLA.

In [27]:
x, y = hbS[pid, jem], fwS[pid, jfw]
print("Pearson r", round(stats.pearsonr(x, y)[0], 4), "| Spearman r", round(stats.spearmanr(x, y)[0], 4), "| Pearson r of log10", round(stats.pearsonr(np.log10(x), np.log10(y))[0], 4),
      "| expected 0.778, 0.9, 0.919")
Pearson r 0.7778 | Spearman r 0.9001 | Pearson r of log10 0.9187 | expected 0.778, 0.9, 0.919

Result: reproduced. Pearson r = 0.778, Spearman r = 0.900 and Pearson r on log10 counts = 0.919, as in the paper.

In [28]:
sh = share[ids] * 100
for k, lab_ in enumerate(labs):
    print(f"{lab_:8s} share of output neurons over the 63 primary ROIs: mean {sh[:, k].mean():.1f}% SD {sh[:, k].std(ddof=1):.1f}% (SD with ddof 0: {sh[:, k].std():.1f}%)")
print("expected ACh 62.8 +- 14.2, GLUT 15.5 +- 9.2, GABA 11.4 +- 8.2")
Unknown  share of output neurons over the 63 primary ROIs: mean 5.6% SD 4.6% (SD with ddof 0: 4.6%)
DA       share of output neurons over the 63 primary ROIs: mean 3.0% SD 3.2% (SD with ddof 0: 3.2%)
SER      share of output neurons over the 63 primary ROIs: mean 1.1% SD 2.1% (SD with ddof 0: 2.1%)
GABA     share of output neurons over the 63 primary ROIs: mean 11.4% SD 8.2% (SD with ddof 0: 8.1%)
GLUT     share of output neurons over the 63 primary ROIs: mean 15.5% SD 9.2% (SD with ddof 0: 9.1%)
ACH      share of output neurons over the 63 primary ROIs: mean 62.8% SD 14.2% (SD with ddof 0: 14.1%)
OCT      share of output neurons over the 63 primary ROIs: mean 0.4% SD 0.6% (SD with ddof 0: 0.6%)
expected ACh 62.8 +- 14.2, GLUT 15.5 +- 9.2, GABA 11.4 +- 8.2

Result: reproduced. Acetylcholine 62.8% +- 14.2%, glutamate 15.5% +- 9.2% and GABA 11.4% +- 8.2%, as in the paper.

Summary¶

Claim Outcome
fig3d-flyem-vs-flywire partially reproduced: FlyEM higher, both r below tolerance
fig3e-flyem-higher-most-regions reproduced: 55 of 63 (rests on the left-right orientation, close to the bound)
fig3g-transmitter-correlation not reproduced
fig4e-unsegregated-higher reproduced
fig4f-segregated-lower reproduced (reading a)
fig4i-reciprocal-higher reproduced
fig5b-walking-activation reproduced
fig5b-walking-suppression not reproduced
fig3a-postsynapse-counts (elsewhere) partially reproduced: FlyEM at confidence 0 not in the table
fig3c, figs3-1a, fig3f (elsewhere) reproduced, on the paper's per-ROI tables
all SCKm and DistKm claims, fig3d-confidence-threshold, figs4-1-flyem-permutation blocked: inputs not published
fig4b-ppssi-distribution (elsewhere, companion notebook) partially reproduced: 138,144 neurons have a PPSSI, not 139,255
fig4h-reciprocal-distances, fig5-wagn (companion notebook) reproduced
figs4-1ij-segregation-index-biased (companion notebook) not reproduced: FlyWire mean 0.363, above 0.25
fig4a, fig4c (companion notebook) blocked: FlyEM half not published; FlyWire half holds
figs3-2cd-apl-similarity blocked

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.

How the analysis differs from the paper's. No SPM12 motion or slice-timing correction was applied (claims file M1), so every FC and GLM result here rests on uncorrected data. The motion check shows that the raw series moves: the tdTomato in-plane shift has a median of 0.6 to 3.2 um and a 95th percentile of 2.8 to 6.1 um per fly, against a voxel of about 2.6 um. Regressing the shifts out changes the fig3d values by 0.005. The mean green image is registered to the template with ANTs SyN in Python and the ROI means are computed through the registration's linear map; tCompCor is taken from native voxels; the GLM has no Tukey-taper pre-whitening and is smoothed on the beta maps. The FC gives a lower FC-SC correlation than the paper's own output files (0.566 against 0.684 for FlyWire), and the walking map correlates with the paper's deposited map at r = 0.36 voxel by voxel. A seeded registration now repeats exactly. A registration with another seed (11) lands elsewhere: it moves native voxels by a median of 2.5 to 44 um per fly and its ROI series correlate with the first at a median of 0.18 to 0.98 (data check), yet fig3d and fig3e keep their outcomes under it. The left-right orientation rests on the per-region FC check, which the two GLM checks contradict weakly.

What was found about the dataset. The files match their description (9 flies, 3384 volumes at 1.8797 Hz, 50 Hz FicTrac, 1800 s), the walking regressor of the paper's code is reproduced to 1e-5 from the files in name order, and the seventh fly in name order (fly-100) has the lowest coverage of the hemibrain ROIs (9 ROIs partly outside the field of view, AL(L) 55% inside; the next lowest, fly-105, has 2 ROIs at 99%), which fits the paper's reason for leaving one fly out. The dimension attribute of the functional series is [128, 256, 49] while the data are stored as (time, 256, 128, 49). The ROI atlases of the paper's main analyses (SCKm, DistKm) are not published with the code or on Zenodo.

In [29]:
print("total runtime (min)", round((time.time() - T_START) / 60, 1), "| peak memory (GB)", round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6, 2))
total runtime (min) 44.5 | peak memory (GB) 4.73