Markowitz et al. (2023): dLight photometry claims, on dandiset 000559¶

Paper: Markowitz, Gillis, Jay et al. (2023), "Spontaneous behaviour is structured by reinforcement without explicit reward", Nature 614, 108-117, doi:10.1038/s41586-022-05611-2. The claims file (claims/markowitz-2023.yaml) was written from the version of record (Europe PMC, PMC9892006): main text, legends, Methods and Extended Data legends.

Dataset: DANDI:000559, version 0.261113.1911 (doi:10.48324/dandi.000559/0.261113.1911). The paper cites no version of the dandiset. This is the most recent published version; its release notes say the earlier versions mislabelled the dLight-only mice and left the catch trials out, and the claims file's description (groups, catch trials, session numbers) matches this version better. The files are streamed; nothing is downloaded to disk.

This notebook tests the claims on dLight photometry (Figs. 1, 2, Extended Data Figs. 2, 3, 7). The Opto-DA claims are in optoda.ipynb. Claims tested and blocked here:

claim here
ed2a-syllable-repertoire tested
fig1e-velocity-timescales tested
ed3c-keypoint-velocity tested
fig1f-syllable-vs-movement-onset tested
fig1f-dip-then-peak tested
fig1h-syllable-dlight-differs tested
fig1j-weak-kinematic-correlation tested
fig1l-identity-not-decodable blocked (too_large)
fig2a-food-reward-transients blocked (data_missing); its spontaneous half is shown
fig2b-dlight-usage-across-syllables tested
fig2i-dlight-entropy-across-syllables tested
fig2b-across-experiments tested
fig2e-dlight-predicts-future-usage tested
fig2e-not-autocorrelation tested
fig2g-usage-crosscorrelation tested
fig2h-specific-to-syllable tested
fig2k-dlight-predicts-sequence-variability tested
ed7-dms-fewer-transients, ed7b-dms-transient-shape, ed7d-dms-smaller-peaks tested
fig3c-calibration blocked (data_missing)
fig4i blocked (other): depends on the decoding models, not run
ed6b, ed6e, ed7-dms-no-usage-prediction, ed7e (encoding models) blocked (other): not run
fig4b, fig4c, fig4f, fig4h, fig4h-additive, fig5 blocked (other): not run
In [1]:
import zlib, time, resource
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import markowitz as M

PAPER = "markowitz-2023"
def rng_for(claim, k=0):
    return np.random.default_rng(zlib.crc32(f"{PAPER}/{claim}".encode()) + k)
def seed_of(claim):
    return zlib.crc32(f"{PAPER}/{claim}".encode())

T0 = time.time()
A = M.list_assets()
print(A.kind.value_counts(dropna=False).to_string())
rows = [r for _, r in A[A.kind.isin(["photometry", "reinforcement-photometry"])].iterrows()]
SESS = M.load_many(M.load_photometry, rows)
print(len(SESS), "photometry files loaded in", round(time.time() - T0), "s")
kind
reinforcement               1340
photometry                   264
reinforcement-photometry     236
velocity-modulation           94
keypoint                       5
NaN                            3
500 photometry files loaded in 72 s
In [2]:
def first(v, default=np.nan):
    return v[0] if isinstance(v, list) and len(v) else default

S = pd.DataFrame([dict(i=i, path=d["path"], mouse=d["subject"], group=d["group"], ophys=d["has_ophys"],
                       sn=first(d.get("ts_session_number")), sns=set(d.get("ts_session_number", [])),
                       post_targets=[t for t, s in zip(d.get("ts_target_syllable", []), d.get("ts_session_number", []))
                                     if s in (3, 4) and t >= 0],
                       stim=first(d.get("ts_stim_duration")),
                       etype=first(d.get("ts_experiment_type"), ""), exclude=any(d.get("ts_exclude", [False])),
                       targets=[t for t in d.get("ts_target_syllable", []) if t >= 0],
                       maxpct=d.get("qc_max_pct", np.nan), refcorr=d.get("qc_corr", np.nan),
                       qcb_p90=d.get("qcb_p90_pct", np.nan), qcb_corr=d.get("qcb_corr", np.nan),
                       qcb_raw=d.get("qcb_raw_max", np.nan),
                       lab_max=first(d.get("ts_signal_max")), lab_corr=first(d.get("ts_signal_reference_corr")),
                       n=len(d["t"]) if d["t"] is not None else 0, start=d["start"])
                  for i, d in enumerate(SESS)])
S["area"] = np.where(S.group == "dms-dlight", "DMS", "DLS")
# quality control, reading (a): the Methods' maximum % dF/F0 > 1.5 and dLight-reference r < 0.6
S["qc"] = S.ophys & (S.maxpct > 1.5) & (S.refcorr < 0.6)
# reading (b), the code's rule: 90th percentile of the smoothed dF/F > 1.5%, smoothed r < 0.6, raw dF/F <= 1.0
S["qc_b"] = S.ophys & (S.qcb_p90 > 1.5) & (S.qcb_corr < 0.6) & (S.qcb_raw <= 1.0)
# baseline photometry experiments: no stimulation. dLight-only mice: all; dLight+ChrimsonR mice:
# session numbers -1 and 0 (code reading, which drops the post days 3 and 4), and the Methods
# reading, which adds the post days with the target syllable's instances removed. A file can be the
# baseline day of one target and the post day of another (two rows of its TargetSessions table): it
# is a baseline file under both readings, and under the Methods reading the post-day target's
# instances are removed from it.
chr_ = S.group == "dls-chrimson-dlight"
S["has_base"] = S.sns.apply(lambda s: bool(s & {-1, 0}))
S["has_post"] = S.sns.apply(lambda s: bool(s & {3, 4}))
S["pure_post"] = chr_ & S.has_post & ~S.has_base
S["base_code"] = (~chr_ | S.has_base) & ~S.exclude & (S.etype != "excitation_photometry")
S["base_methods"] = S.base_code | (chr_ & S.has_post & ~S.exclude & (S.etype != "excitation_photometry"))
DLS = S[(S.area == "DLS") & S.qc & S.base_code]
DLSm = S[(S.area == "DLS") & S.qc & S.base_methods]
DMS = S[(S.area == "DMS") & S.qc]
DLSb = S[(S.area == "DLS") & S.qc_b & S.base_code]        # quality control reading (b)
DMSb = S[(S.area == "DMS") & S.qc_b]
In [3]:
print("files by group, with and without photometry:")
print(S.groupby(["group", "ophys"]).size().to_string())
print("\nmice with photometry per group:", S[S.ophys].groupby("group").mouse.nunique().to_dict())
print("mice without any photometry file:", sorted(set(S.mouse) - set(S[S.ophys].mouse)))
print("\nQC (a), files failing:", S[S.ophys & ~S.qc][["path", "maxpct", "refcorr"]].to_string())
print("max % dF/F range", S.maxpct.min().round(2), S.maxpct.max().round(2),
      "; dLight-reference r range", S.refcorr.min().round(3), S.refcorr.max().round(3))
print("lab's signal_max against our max % dF/F: Spearman r =",
      round(stats.spearmanr(S.lab_max, S.maxpct, nan_policy="omit")[0], 3))
print("\ndLight+ChrimsonR files that are the baseline day of one target and the post day of another:",
      int((chr_ & S.has_base & S.has_post).sum()), "; pure post-day files:", int(S.pure_post.sum()))
print("\nQC reading (b) on", int(S.ophys.sum()), "files with photometry: 90th percentile <= 1.5% in",
      int((S.ophys & (S.qcb_p90 <= 1.5)).sum()), "; smoothed r >= 0.6 in", int((S.ophys & (S.qcb_corr >= 0.6)).sum()),
      "; raw dF/F above 1.0 in", int((S.ophys & (S.qcb_raw > 1.0)).sum()), "; passing", int(S.qc_b.sum()),
      "(reading (a):", int(S.qc.sum()), ")")
print("raw dF/F maximum per file, percentiles 50, 90, 99:", np.percentile(S[S.ophys].qcb_raw, [50, 90, 99]).round(3))
print("files passing (a) and failing (b):")
print(S[S.qc & ~S.qc_b][["mouse", "base_code", "maxpct", "refcorr", "qcb_p90", "qcb_corr", "qcb_raw"]].round(3).to_string())
print("\nexperiment sets, step by step (files -> with photometry -> QC (a) -> QC (b)):")
for nm, sel in [("DLS baseline, code reading", (S.area == "DLS") & S.base_code),
                ("DLS baseline, Methods reading", (S.area == "DLS") & S.base_methods),
                ("DMS", S.area == "DMS")]:
    print(f"  {nm}: {int(sel.sum())} -> {int((sel & S.ophys).sum())} -> {int((sel & S.qc).sum())} -> {int((sel & S.qc_b).sum())}")
print("  left out of the DLS sets before these steps: excluded by the lab", int(((S.area == "DLS") & S.exclude).sum()),
      "; 2-s excitation sessions", int((S.etype == "excitation_photometry").sum()),
      "; stimulation days (session numbers 1, 2 only)", int((chr_ & ~S.has_base & ~S.has_post & ~S.exclude & (S.etype != "excitation_photometry")).sum()))
print("\nDLS baseline experiments (code reading):", len(DLS), "in", DLS.mouse.nunique(), "mice;",
      "with post days (Methods reading):", len(DLSm), "; under QC (b):", len(DLSb), "; DMS under QC (b):", len(DMSb))
print(DLS.groupby("mouse").size().to_string())
print("\nDMS experiments:", len(DMS), "in", DMS.mouse.nunique(), "mice")
print(DMS.groupby("mouse").size().to_string())
d0 = SESS[DLS.i.iloc[0]]
fs = np.array([np.median(np.diff(SESS[i]["t"])) for i in S[S.ophys].i])
print("\nphotometry sample interval (s): min", fs.min().round(5), "max", fs.max().round(5))
print("syllable series sorted in time in every file:", all(d["syl_sorted"] for d in SESS))
print("samples per experiment: min", S[S.ophys].n.min(), "median", S[S.ophys].n.median(), "max", S[S.ophys].n.max(),
      "(30 min at 30 Hz is 54000)")
allsyl = np.concatenate([SESS[i]["syl"] for i in DLS.i])
print("offline syllable labels range", allsyl.min(), allsyl.max(), "; distinct", len(np.unique(allsyl)))
v = np.concatenate([SESS[i]["speed"] for i in DLS.i])
print("2D speed (mm/s) percentiles 1, 50, 99:", np.percentile(v, [1, 50, 99]).round(1))
zz = np.concatenate([SESS[i]["z"] for i in DLS.i])
print("processed dLight z: mean", np.nanmean(zz).round(3), "sd", np.nanstd(zz).round(3), "NaN fraction", np.isnan(zz).mean().round(4))
del allsyl, v, zz
# Clock check: syllable-associated dLight differs across syllables when measured at the syllable
# onsets; with the labels shifted in time the contrast should fall (one experiment per mouse).
for sh in [-60, -15, -6, 0, 6, 15, 60]:
    vals = []
    for m, sub in DLS.groupby("mouse"):
        d = SESS[sub.i.iloc[0]]
        s_, l_ = M.runs(d["syl"])
        s2 = np.clip(s_ + sh, 0, len(d["z"]) - 10)
        da = d["z"][s2[:, None] + np.arange(10)].max(1)
        vals.append(pd.DataFrame(dict(label=l_, da=da)))
    x = pd.concat(vals)
    H = stats.kruskal(*[g.da.to_numpy() for _, g in x.groupby("label") if len(g) > 20])[0]
    print(f"syllable labels shifted by {sh:+d} samples: Kruskal-Wallis H of instance dLight across syllables = {H:.0f}")
# The same per mouse, over all its experiments, to compare the two DLS groups (dLight-only files and
# dLight+ChrimsonR reinforcement-photometry files) and DMS: a clock offset in one group would move its best shift.
SHIFTS = [-15, -12, -9, -6, -3, 0, 3, 6, 9]
CLK = []
for area, sub_a in [("DLS", DLS), ("DMS", DMS)]:
    for m, sub in sub_a.groupby("mouse"):
        Hs = []
        for sh in SHIFTS:
            vals = []
            for i in sub.i:
                d = SESS[i]
                s_, l_ = M.runs(d["syl"])
                s2 = np.clip(s_ + sh, 0, len(d["z"]) - 10)
                vals.append(pd.DataFrame(dict(label=l_, da=d["z"][s2[:, None] + np.arange(10)].max(1))))
            x = pd.concat(vals)
            Hs.append(stats.kruskal(*[g.da.to_numpy() for _, g in x.groupby("label") if len(g) > 20])[0])
        CLK.append(dict(group=sub.group.iloc[0], mouse=m, best_shift=SHIFTS[int(np.argmax(Hs))],
                        **{f"H{s:+d}": round(h) for s, h in zip(SHIFTS, Hs)}))
CLK = pd.DataFrame(CLK)
print("\nper-mouse H with the labels shifted (samples), all baseline experiments of each mouse:")
print(CLK.to_string())
print("best shift by group:", CLK.groupby("group").best_shift.agg(lambda s: s.value_counts().to_dict()).to_dict())
# Clock ranges: the files give every series its own timestamps; the photometry and the syllable labels
# are joined on them. Offsets of the first and last timestamps, by group:
rng_ = pd.DataFrame([dict(group=S.group[i], start_offset=SESS[i]["t_range"][0] - SESS[i]["syl_range"][0],
                          end_offset=SESS[i]["t_range"][1] - SESS[i]["syl_range"][1])
                     for i in S[S.ophys].i if SESS[i].get("syl_range") is not None])
print("\nphotometry first (last) timestamp minus syllable series first (last) timestamp, s:")
print(rng_.groupby("group").describe(percentiles=[0.5]).round(2).T.to_string())
files by group, with and without photometry:
group                ophys
dls-chrimson-dlight  False     10
                     True     226
dls-dlight           False     22
                     True      75
dms-dlight           False     92
                     True      75

mice with photometry per group: {'dls-chrimson-dlight': 8, 'dls-dlight': 6, 'dms-dlight': 8}
mice without any photometry file: ['dls-dlight-6', 'dls-dlight-8', 'dms-dlight-7', 'dms-dlight-9']

QC (a), files failing:                                                                                                                                             path        maxpct   refcorr
265  sub-dlight-chrimson-6/sub-dlight-chrimson-6_ses-reinforcement-photometry-eab24978-761d-402f-9e53-f2b6e2b56f68_behavior+image+ogen+ophys.nwb  10803.769412  0.998392
max % dF/F range 2.37 22797.77 ; dLight-reference r range 0.016 0.998
lab's signal_max against our max % dF/F: Spearman r = 0.901

dLight+ChrimsonR files that are the baseline day of one target and the post day of another: 38 ; pure post-day files: 45

QC reading (b) on 376 files with photometry: 90th percentile <= 1.5% in 19 ; smoothed r >= 0.6 in 3 ; raw dF/F above 1.0 in 3 ; passing 354 (reading (a): 375 )
raw dF/F maximum per file, percentiles 50, 90, 99: [0.106 0.181 0.314]
files passing (a) and failing (b):
                 mouse  base_code     maxpct  refcorr  qcb_p90  qcb_corr  qcb_raw
40        dms-dlight-1       True      5.256    0.047    1.352     0.171    0.053
41        dms-dlight-1       True      6.100    0.044    1.487     0.119    0.061
55        dms-dlight-1       True      2.805    0.075    0.820     0.270    0.028
69        dms-dlight-1       True      3.260    0.061    0.869     0.211    0.033
102       dls-dlight-3       True      6.202    0.055    1.425     0.168    0.062
120       dls-dlight-2       True      5.417    0.039    1.391     0.111    0.054
121       dms-dlight-1       True      4.637    0.040    1.018     0.160    0.046
140       dms-dlight-1       True      3.257    0.085    0.951     0.297    0.033
148       dls-dlight-4       True      5.572    0.066    1.341     0.195    0.056
152       dms-dlight-6       True      5.649    0.165    1.440     0.303    0.056
159  dlight-chrimson-3      False    212.258    0.360    3.502     0.263    2.123
173  dlight-chrimson-4       True      5.155    0.087    1.467     0.165    0.052
180       dms-dlight-1       True      3.919    0.047    1.056     0.184    0.039
183       dls-dlight-7       True  22797.770    0.016    1.487     0.170  227.978
192  dlight-chrimson-4      False      5.838    0.154    1.486     0.362    0.058
215       dms-dlight-1       True      2.371    0.297    0.830     0.718    0.024
225  dlight-chrimson-4      False      5.528    0.173    1.493     0.388    0.055
242  dlight-chrimson-4       True      3.997    0.167    1.323     0.413    0.040
280       dms-dlight-6       True      7.096    0.142    1.390     0.259    0.071
329       dms-dlight-6       True      5.326    0.073    1.210     0.170    0.053
406  dlight-chrimson-4       True      5.870    0.277    1.574     0.633    0.059

experiment sets, step by step (files -> with photometry -> QC (a) -> QC (b)):
  DLS baseline, code reading: 188 -> 164 -> 164 -> 157
  DLS baseline, Methods reading: 233 -> 205 -> 204 -> 195
  DMS: 167 -> 75 -> 75 -> 64
  left out of the DLS sets before these steps: excluded by the lab 0 ; 2-s excitation sessions 2 ; stimulation days (session numbers 1, 2 only) 98

DLS baseline experiments (code reading): 164 in 14 mice; with post days (Methods reading): 204 ; under QC (b): 157 ; DMS under QC (b): 64
mouse
dlight-chrimson-1    11
dlight-chrimson-2    12
dlight-chrimson-3     9
dlight-chrimson-4    13
dlight-chrimson-5     8
dlight-chrimson-6    13
dlight-chrimson-8    11
dlight-chrimson-9    12
dls-dlight-1         12
dls-dlight-2         14
dls-dlight-3         14
dls-dlight-4         14
dls-dlight-5         10
dls-dlight-7         11

DMS experiments: 75 in 8 mice
mouse
dms-dlight-1     10
dms-dlight-10    12
dms-dlight-11    11
dms-dlight-13     7
dms-dlight-14     6
dms-dlight-4      8
dms-dlight-6     10
dms-dlight-8     11

photometry sample interval (s): min 0.03337 max 0.03337
syllable series sorted in time in every file: True
samples per experiment: min 20738 median 48264.5 max 54001 (30 min at 30 Hz is 54000)
offline syllable labels range 0 57 ; distinct 58
2D speed (mm/s) percentiles 1, 50, 99: [  1.8  33.5 288.7]
processed dLight z: mean -0.0 sd 0.998 NaN fraction 0.0
syllable labels shifted by -60 samples: Kruskal-Wallis H of instance dLight across syllables = 81
syllable labels shifted by -15 samples: Kruskal-Wallis H of instance dLight across syllables = 257
syllable labels shifted by -6 samples: Kruskal-Wallis H of instance dLight across syllables = 941
syllable labels shifted by +0 samples: Kruskal-Wallis H of instance dLight across syllables = 888
syllable labels shifted by +6 samples: Kruskal-Wallis H of instance dLight across syllables = 333
syllable labels shifted by +15 samples: Kruskal-Wallis H of instance dLight across syllables = 158
syllable labels shifted by +60 samples: Kruskal-Wallis H of instance dLight across syllables = 79
per-mouse H with the labels shifted (samples), all baseline experiments of each mouse:
                  group              mouse  best_shift  H-15  H-12  H-9   H-6   H-3   H+0   H+3  H+6  H+9
0   dls-chrimson-dlight  dlight-chrimson-1          -3   513   681  856  1080  1135   889   565  338  249
1   dls-chrimson-dlight  dlight-chrimson-2          -3   242   332  548   836  1001   937   720  468  289
2   dls-chrimson-dlight  dlight-chrimson-3          -3   270   391  653   944  1002   834   540  304  180
3   dls-chrimson-dlight  dlight-chrimson-4          -3   306   445  712  1054  1201  1099   812  571  437
4   dls-chrimson-dlight  dlight-chrimson-5          -6   204   303  505   668   663   513   271  208  164
5   dls-chrimson-dlight  dlight-chrimson-6          -3   390   535  833  1420  1911  1720  1145  627  314
6   dls-chrimson-dlight  dlight-chrimson-8          -3   396   519  710   999  1201  1024   704  437  277
7   dls-chrimson-dlight  dlight-chrimson-9          -3   211   371  587   878  1075   957   822  516  364
8            dls-dlight       dls-dlight-1          -3   293   498  722  1052  1289   999   659  337  195
9            dls-dlight       dls-dlight-2          -3   265   386  538   746   827   719   515  362  232
10           dls-dlight       dls-dlight-3          -3   379   453  591   796  1066   989   705  372  179
11           dls-dlight       dls-dlight-4          -3   310   381  464   614   715   674   458  314  212
12           dls-dlight       dls-dlight-5          -3   439   601  894  1013  1160   949   632  444  274
13           dls-dlight       dls-dlight-7          -3   420   530  725   933  1283  1165   850  484  255
14           dms-dlight       dms-dlight-1          -3   245   306  371   468   516   459   391  275  196
15           dms-dlight      dms-dlight-10          -3   300   406  514   626   688   650   514  393  245
16           dms-dlight      dms-dlight-11          -3   137   142  160   174   191   177   161  137   84
17           dms-dlight      dms-dlight-13          -3   188   269  393   497   672   663   454  296  194
18           dms-dlight      dms-dlight-14          -3   312   465  651   852  1018   927   606  326  163
19           dms-dlight       dms-dlight-4          -3   181   247  370   516   589   507   374  280  219
20           dms-dlight       dms-dlight-6           0   407   575  834  1137  1515  1695  1233  675  367
21           dms-dlight       dms-dlight-8           0   333   411  508   568   686   777   753  550  342
best shift by group: {'dls-chrimson-dlight': {-3: 7, -6: 1}, 'dls-dlight': {-3: 6}, 'dms-dlight': {-3: 6, 0: 2}}

photometry first (last) timestamp minus syllable series first (last) timestamp, s:
group               dls-chrimson-dlight  dls-dlight  dms-dlight
start_offset count               226.00       75.00       75.00
             mean                 33.53        0.00        6.96
             std                  33.10        0.00       56.37
             min                   1.60        0.00        0.00
             50%                  28.67        0.00        0.00
             max                 239.07        0.00      487.47
end_offset   count               226.00       75.00       75.00
             mean               -213.35     -121.20      -64.84
             std                  87.39       65.12      116.29
             min                -869.53     -280.03     -621.33
             50%                -219.47     -123.47       -0.03
             max                 -13.03       -0.03       -0.03
In [4]:
# Syllable instances with their syllable-associated dLight (max z from onset to 0.3 s).
def inst_table(sub):
    out = []
    for _, r in sub.iterrows():
        x = M.instances(SESS[r.i])
        x["exp"] = r.i
        x["mouse"] = r.mouse
        x["post"] = r.pure_post
        x["is_target"] = x.label.isin(r.post_targets)
        out.append(x)
    return pd.concat(out, ignore_index=True)

Iall = inst_table(DLSm)
I = Iall[~Iall.is_target]              # Methods reading: post-day target instances removed
Ic = Iall[Iall.exp.isin(DLS.i)]        # code reading: post days dropped, baseline files kept whole
del Iall
print("DLS instances, Methods reading:", len(I), "in", I.exp.nunique(), "experiments; code reading:", len(Ic), "in", Ic.exp.nunique())
assert set(Ic.exp) == set(DLS.i)
DLS instances, Methods reading: 577337 in 204 experiments; code reading: 472606 in 164

ed2a-syllable-repertoire¶

"MoSeq identifies 37 commonly used syllables, with median duration 400 ms (mean 566 ms, s.d. 636 ms)."

In [5]:
# Reading (a): all DLS photometry experiments of the 16 dLight mice, with and without photometry,
# offline labels. Usage of a syllable is its share of a mouse's instances, averaged over mice.
def all_dls_instances():
    sub = S[(S.area == "DLS") & S.base_methods]
    rows_ = []
    for _, r in sub.iterrows():
        d = SESS[r.i]
        s, lab = M.runs(d["syl"])
        on = d["t"][s]
        rows_.append(pd.DataFrame(dict(mouse=r.mouse, label=lab.astype(int), dur=np.r_[np.diff(on), np.nan])))
    return pd.concat(rows_, ignore_index=True), sub

ALL, sub_a = all_dls_instances()
use = ALL.groupby("mouse").label.value_counts(normalize=True).unstack(fill_value=0)
mean_use = use.mean(0).sort_values(ascending=False)
SYL37 = sorted(mean_use[mean_use > 0.01].index)
print("reading (a):", len(sub_a), "experiments,", ALL.mouse.nunique(), "mice,", len(ALL), "instances")
print("syllables with mean usage > 1%:", len(SYL37))
dur = ALL.dur.dropna() * 1000
print(f"durations (ms): median {dur.median():.0f}, mean {dur.mean():.0f}, s.d. {dur.std():.0f}, n = {len(dur)}")
dur37 = ALL[ALL.label.isin(SYL37)].dur.dropna() * 1000
print(f"  of the {len(SYL37)} syllables only: median {dur37.median():.0f}, mean {dur37.mean():.0f}, s.d. {dur37.std():.0f}")
fu = pd.concat([pd.Series(SESS[i]["syl"]).value_counts(normalize=True).rename(SESS[i]["subject"]) for i in sub_a.i], axis=1)
print("variant, usage as share of frames:", (fu.T.groupby(level=0).mean().mean(0) > 0.01).sum(), "syllables > 1%")
print("variant, the 14 photometry mice only:", (use.loc[DLS.mouse.unique()].mean(0) > 0.01).sum(), "syllables > 1%")
print("syllables in use per mouse (any instance):", use.gt(0).sum(1).to_dict())
reading (a): 233 experiments, 16 mice, 672061 instances
syllables with mean usage > 1%: 36
durations (ms): median 400, mean 561, s.d. 627, n = 671828
  of the 36 syllables only: median 400, mean 575, s.d. 633
variant, usage as share of frames: 35 syllables > 1%
variant, the 14 photometry mice only: 37 syllables > 1%
syllables in use per mouse (any instance): {'dlight-chrimson-1': 57, 'dlight-chrimson-2': 57, 'dlight-chrimson-3': 57, 'dlight-chrimson-4': 58, 'dlight-chrimson-5': 57, 'dlight-chrimson-6': 57, 'dlight-chrimson-8': 58, 'dlight-chrimson-9': 58, 'dls-dlight-1': 58, 'dls-dlight-2': 58, 'dls-dlight-3': 58, 'dls-dlight-4': 58, 'dls-dlight-5': 58, 'dls-dlight-6': 57, 'dls-dlight-7': 58, 'dls-dlight-8': 58}
/tmp/ipykernel_2623/3591045717.py:15: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  mean_use = use.mean(0).sort_values(ascending=False)
/tmp/ipykernel_2623/3591045717.py:24: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  print("variant, usage as share of frames:", (fu.T.groupby(level=0).mean().mean(0) > 0.01).sum(), "syllables > 1%")
/tmp/ipykernel_2623/3591045717.py:25: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  print("variant, the 14 photometry mice only:", (use.loc[DLS.mouse.unique()].mean(0) > 0.01).sum(), "syllables > 1%")
/tmp/ipykernel_2623/3591045717.py:26: Pandas4Warning: Starting with pandas version 4.0 all arguments of sum will be keyword-only.
  print("syllables in use per mouse (any instance):", use.gt(0).sum(1).to_dict())

Result: reproduced. Under reading (a), the DLS photometry experiments of the 16 dLight mice (233 experiments), 36 syllables have a mean usage above 1% (37 within its tolerance of 3.7), and the 671,828 durations have a median of 400 ms, a mean of 561 ms and an s.d. of 627 ms, all within tolerance. Over the 14 photometry mice alone 37 syllables pass the 1% bar. Reading (b) is in optoda.ipynb.

Reading (b), all open-field experiments of the dandiset with offline labels, includes the Opto-DA experiments; it is computed in optoda.ipynb (section ed2a), which loads those files.

fig1h-syllable-dlight-differs¶

"Average syllable-associated dLight amplitudes differ across syllables (Kruskal-Wallis H = 209.29, P < 1e-25, n = 518 mouse-syllable pairs)."

In [6]:
# Onset-aligned waveforms per mouse, each z-scored over -10 to +10 s (Methods, dLight average
# waveform z-scoring), with circular-shuffle normalisation of the averages.
L = 601                      # -10 .. +10 s at 30 Hz
LAG = np.arange(-300, 301)

def snippets(i, starts):
    z = SESS[i]["z"]
    n = len(z)
    ok = (starts - 300 >= 0) & (starts + 300 < n)
    idx = starts[ok][:, None] + LAG[None, :]
    X = z[idx].astype(np.float32)
    good = np.all(np.isfinite(X), 1)
    X = X[good]
    X = (X - X.mean(1, keepdims=True)) / X.std(1, keepdims=True)
    return X, np.flatnonzero(ok)[good]

def shuffle_norm(X, groups, ngroups, cols, nshuf, rng):
    """Group averages of the rows of X at columns `cols`, z-scored against `nshuf` averages
    of circularly permuted rows (Methods, dLight average waveform z-scoring)."""
    from scipy.sparse import csr_matrix
    N = len(X)
    G = csr_matrix((np.ones(N), (groups, np.arange(N))), shape=(ngroups, N))
    cnt = np.asarray(G.sum(1)).ravel()
    cnt[cnt == 0] = np.nan
    avg = (G @ X[:, cols]) / cnt[:, None]
    sh = np.empty((nshuf, ngroups, len(cols)), np.float32)
    rows_ = np.arange(N)[:, None]
    for s in range(nshuf):
        k = rng.integers(0, X.shape[1], N)
        sh[s] = (G @ X[rows_, (cols[None, :] + k[:, None]) % X.shape[1]]) / cnt[:, None]
    mu, sd = sh.mean(0), sh.std(0)
    return avg, (avg - mu) / sd, (sh - mu) / sd

COLS = np.arange(300 - 30, 300 + 31)          # -1 .. +1 s
t03 = np.arange(30, 40)                        # columns of COLS for 0 .. 0.3 s
NSHUF = 1000
In [7]:
# The 37 syllables of the dLight analyses: mean usage over the 14 photometry mice above 1%
# (all_behavior_00 keeps syllables whose mean usage over mice exceeds 1%; ed2a counts over all 16).
use14 = use.loc[sorted(DLS.mouse.unique())].mean(0)
SYL37 = sorted(use14[use14 > 0.01].index)
print("syllables with mean usage > 1% over the 14 photometry mice:", len(SYL37))

def movement_onsets(i, still=False):
    """Methods, Movement initiation analyses: centroid speed z-scored per experiment, 50-point
    boxcar, derivative cubed, scipy find_peaks with height, width and prominence 1.
    The derivative is taken per second (z per s): per frame no peak reaches the height of 1.
    With `still`, only detections preceded by relative stillness are kept, as the Methods describe
    the events ("moments where mice transitioned from periods of relative stillness to movement"):
    the smoothed speed averaged over the second before the detection is below the experiment's
    25th percentile of smoothed speed (the percentile is an assumption)."""
    from scipy.signal import find_peaks
    v = SESS[i]["speed"].astype(float)
    v = (v - v.mean()) / v.std()
    v = np.convolve(v, np.ones(50) / 50, mode="same")
    sc = (np.gradient(v) * M.FS) ** 3
    pk, _ = find_peaks(sc, height=1, width=1, prominence=1)
    if still:
        cv = np.r_[0, np.cumsum(v)]
        pre = np.array([(cv[p] - cv[max(p - 30, 0)]) / max(p - max(p - 30, 0), 1) if p > 0 else np.inf for p in pk])
        pk = pk[pre < np.percentile(v, 25)]
    return pk

def speed_around(i, pk):
    """2D speed (mm/s) from 1 s before to 1 s after each detection: mean before, at, after."""
    sp = SESS[i]["speed"]
    pk = pk[(pk - 30 >= 0) & (pk + 31 <= len(sp))]
    a = sp[pk[:, None] + np.arange(-30, 31)]
    return a[:, :30].sum(0), a[:, 30].sum(), a[:, 31:].sum(0), len(pk)

def highpass(X):
    from scipy.signal import butter, filtfilt
    b, a = butter(2, 1.0 / (M.FS / 2), "high")        # order 2 is a standard choice
    Y = filtfilt(b, a, X, axis=1).astype(np.float32)
    return (Y - Y.mean(1, keepdims=True)) / Y.std(1, keepdims=True)

def instances_of(sub):
    return Ic if sub is DLS else DMSI

DMSI = inst_table(DMS)
t0 = time.time()
WAVE, SYL_SNIP_N, ONSET, MOVDIAG, CM = {}, {}, {}, [], []
rng = rng_for("fig1f-syllable-vs-movement-onset")
rng_h = rng_for("fig1h-syllable-dlight-differs")
# count-matched check of fig1f: the shuffle z grows with the number of events, so syllable onsets are
# also drawn at random down to the number of movement initiations of the mouse; claim seed and +1000 .. +4000
CM_SEEDS = [0, 1000, 2000, 3000, 4000]
rng_cm = {k: rng_for("fig1f-syllable-vs-movement-onset", 2 + k) for k in CM_SEEDS}
for area, sub_area in [("DLS", DLS), ("DMS", DMS)]:
    II = instances_of(sub_area)
    for m, sub in sub_area.groupby("mouse"):
        Xs, gs, Xm, Xg = [], [], [], []
        diag = dict(area=area, mouse=m, minutes=0.0, n_all=0, n_still=0)
        acc = {k: [0, 0, 0, 0] for k in ["all", "still"]}
        for i in sub.i:
            x = II[II.exp == i]
            X, keep = snippets(i, x.start.to_numpy())
            Xs.append(X)
            lab = x.label.to_numpy()[keep]
            gs.append(np.where(np.isin(lab, SYL37), np.searchsorted(SYL37, lab), len(SYL37)))
            pk_all, pk_still = movement_onsets(i), movement_onsets(i, still=True)
            Xm.append(snippets(i, pk_all)[0]); Xg.append(snippets(i, pk_still)[0])
            diag["minutes"] += len(SESS[i]["z"]) / M.FS / 60
            diag["n_all"] += len(pk_all); diag["n_still"] += len(pk_still)
            for k, pk in [("all", pk_all), ("still", pk_still)]:
                acc[k] = [a + b for a, b in zip(acc[k], speed_around(i, pk))]
        for k in ["all", "still"]:
            pre, at, post, n_ = acc[k]
            diag[f"{k}_speed_pre"] = pre.mean() / n_; diag[f"{k}_speed_at"] = at / n_; diag[f"{k}_speed_post"] = post.mean() / n_
        MOVDIAG.append(diag)
        X = np.concatenate(Xs); g = np.concatenate(gs); Xm = np.concatenate(Xm); Xg = np.concatenate(Xg)
        out = {}
        # all syllable onsets, and movement initiations: shuffle-normalised averages
        _, out["syl"], out["syl_sh"] = shuffle_norm(X, np.zeros(len(X), int), 1, COLS, NSHUF, rng)
        _, out["mov"], out["mov_sh"] = shuffle_norm(Xm, np.zeros(len(Xm), int), 1, COLS, NSHUF, rng)
        _, out["movs"], _ = shuffle_norm(Xg, np.zeros(len(Xg), int), 1, COLS, NSHUF, rng)
        # reading (a) of fig1f (DLS only): each snippet high-passed at 1 Hz, as the fig_1f, s5f
        # notebook; 100 shuffles (the Fig. 1f legend's number), to keep the run within its time
        if area == "DLS":
            _, out["syl_hp"], _ = shuffle_norm(highpass(X), np.zeros(len(X), int), 1, COLS, 100, rng)
            _, out["mov_hp"], _ = shuffle_norm(highpass(Xm), np.zeros(len(Xm), int), 1, COLS, 100, rng)
            _, out["movs_hp"], _ = shuffle_norm(highpass(Xg), np.zeros(len(Xg), int), 1, COLS, 100, rng)
            # count-matched: syllable onsets drawn down to the initiation count, both readings, 100 shuffles
            for match, nm in [("still", len(Xg)), ("all", len(Xm))]:
                for k, rg in rng_cm.items():
                    Y = X[np.sort(rg.choice(len(X), nm, replace=False))]
                    _, zhp, _ = shuffle_norm(highpass(Y), np.zeros(nm, int), 1, COLS, 100, rg)
                    _, zb, _ = shuffle_norm(Y, np.zeros(nm, int), 1, COLS, 100, rg)
                    CM.append(dict(mouse=m, match=match, n=nm, seed=k, a_syl=np.abs(zhp[0]).mean(), b_syl=zb[0, t03].max()))
        out["n_syl"], out["n_mov"], out["n_movs"] = len(X), len(Xm), len(Xg)
        ONSET[(area, m)] = out
        if area == "DLS":
            sel = g < len(SYL37)
            avg, zn, _ = shuffle_norm(X[sel], g[sel], len(SYL37), COLS, NSHUF, rng_h)
            WAVE[m] = (avg, zn)
            SYL_SNIP_N[m] = np.bincount(g[sel], minlength=len(SYL37))
        del X, Xm, Xg
MOVDIAG = pd.DataFrame(MOVDIAG)
# Quality control reading (b): the onset-aligned averages again for the mice whose experiment set it changes
ONSET_B = {}
rng_b = rng_for("fig1f-syllable-vs-movement-onset", 1)
for area, sa, sb in [("DLS", DLS, DLSb), ("DMS", DMS, DMSb)]:
    II = instances_of(sa)
    for m, sub in sb.groupby("mouse"):
        if set(sub.i) == set(sa[sa.mouse == m].i):
            ONSET_B[(area, m)] = ONSET[(area, m)]
            continue
        X = np.concatenate([snippets(i, II[II.exp == i].start.to_numpy())[0] for i in sub.i])
        Xg = np.concatenate([snippets(i, movement_onsets(i, still=True))[0] for i in sub.i])
        Xm = np.concatenate([snippets(i, movement_onsets(i))[0] for i in sub.i])
        o = {}
        _, o["syl"], _ = shuffle_norm(X, np.zeros(len(X), int), 1, COLS, NSHUF, rng_b)
        _, o["mov"], _ = shuffle_norm(Xm, np.zeros(len(Xm), int), 1, COLS, NSHUF, rng_b)
        _, o["movs"], _ = shuffle_norm(Xg, np.zeros(len(Xg), int), 1, COLS, NSHUF, rng_b)
        ONSET_B[(area, m)] = o
        del X, Xm, Xg
print("onset-aligned averages for", len(ONSET), "mice,", NSHUF, "shuffles each, in", round(time.time() - t0), "s")
syllables with mean usage > 1% over the 14 photometry mice: 37
/tmp/ipykernel_2623/3112929122.py:3: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  use14 = use.loc[sorted(DLS.mouse.unique())].mean(0)
onset-aligned averages for 22 mice, 1000 shuffles each, in 991 s
In [8]:
rows_ = []
for m, sub in DLS.groupby("mouse"):
    x = Ic[(Ic.mouse == m) & Ic.label.isin(SYL37)]
    a = x.groupby("label").da.mean().reindex(SYL37)
    avg, zn = WAVE[m]
    for j, s in enumerate(SYL37):
        rows_.append(dict(mouse=m, label=s, a=a[s], b=avg[j, t03].mean(), c=avg[j, t03].max(), d=zn[j, t03].max(),
                          n=SYL_SNIP_N[m][j]))
P1h = pd.DataFrame(rows_)
print("mouse-syllable pairs:", len(P1h), "; pairs with no instance:", P1h.a.isna().sum(),
      "; instances per pair: min", P1h.n.min(), "median", P1h.n.median())
for k, name in [("a", "mean syllable-associated dLight"), ("b", "mean of z-scored average, 0-0.3 s"),
                ("c", "max of z-scored average, 0-0.3 s"), ("d", "peak of shuffle-normalised average, 0-0.3 s")]:
    grp = [g[k].dropna().to_numpy() for _, g in P1h.groupby("label")]
    H, p = stats.kruskal(*grp)
    print(f"({k}) {name}: H = {H:.2f}, P = {p:.2e}, range of values {P1h[k].min():.2f} to {P1h[k].max():.2f}")
# Methods reading of baseline (post days with the target removed)
grp = [g.da.to_numpy() for _, g in I[I.label.isin(SYL37)].groupby(["mouse", "label"]).da.mean().reset_index().groupby("label")]
print("(a) with post days, target removed: H = %.2f, P = %.2e" % stats.kruskal(*grp))
grp = [g.da.to_numpy() for _, g in Ic[Ic.label.isin(SYL37) & Ic.exp.isin(DLSb.i)].groupby(["mouse", "label"]).da.mean().reset_index().groupby("label")]
print("(a) under quality control (b), %d experiments: H = %.2f, P = %.2e" % ((len(DLSb),) + tuple(stats.kruskal(*grp))))
mouse-syllable pairs: 518 ; pairs with no instance: 0 ; instances per pair: min 73 median 677.0
(a) mean syllable-associated dLight: H = 280.39, P = 1.30e-39, range of values 0.34 to 1.34
(b) mean of z-scored average, 0-0.3 s: H = 300.77, P = 1.59e-43, range of values -0.37 to 0.35
(c) max of z-scored average, 0-0.3 s: H = 289.64, P = 2.20e-41, range of values -0.28 to 0.40
(d) peak of shuffle-normalised average, 0-0.3 s: H = 292.45, P = 6.36e-42, range of values -7.56 to 14.35
(a) with post days, target removed: H = 277.95, P = 3.80e-39
(a) under quality control (b), 157 experiments: H = 282.86, P = 4.37e-40

Result: partially reproduced. Across the 518 mouse-syllable pairs (14 mice x 37 syllables) the Kruskal-Wallis test gives P below 1e-38 under every reading (H from 280.39 to 300.77), but H is above the tolerance of 209.29 +- 20.93 under all four readings, under quality control (b) (H = 282.86) and with the post days (H = 277.95).

fig1f-syllable-vs-movement-onset¶

"The average syllable-associated dLight transient exceeds that associated with movement initiation (P = 0.0006, n = 14 mice)."

In [9]:
print("Movement initiations: detections per minute and 2D speed (mm/s) averaged over the second before,")
print("at, and over the second after each detection; all detections, and those preceded by relative stillness")
md = MOVDIAG.assign(all_per_min=MOVDIAG.n_all / MOVDIAG.minutes, still_per_min=MOVDIAG.n_still / MOVDIAG.minutes)
print(md[["area", "mouse", "all_per_min", "all_speed_pre", "all_speed_at", "all_speed_post",
          "still_per_min", "still_speed_pre", "still_speed_at", "still_speed_post"]].round(1).to_string())
print("median 2D speed over the DLS experiments (mm/s):", round(float(np.median(np.concatenate([SESS[i]["speed"] for i in DLS.i]))), 1))
rows_ = []
for (area, m), o in ONSET.items():
    if area != "DLS":
        continue
    rows_.append(dict(mouse=m, n_syl=o["n_syl"], n_mov=o["n_mov"], n_movs=o["n_movs"],
                      a_syl=np.abs(o["syl_hp"][0]).mean(), a_mov=np.abs(o["mov_hp"][0]).mean(),
                      a_movs=np.abs(o["movs_hp"][0]).mean(),
                      b_syl=o["syl"][0, t03].max(), b_mov=o["mov"][0, t03].max(), b_movs=o["movs"][0, t03].max(),
                      b100_syl=None, b100_mov=None))
F1 = pd.DataFrame(rows_)
# the legend's 100 shuffles: the same averages z-scored against the first 100 shuffles
for k in ["syl", "mov"]:
    vals = []
    for m in F1.mouse:
        o = ONSET[("DLS", m)]
        sh = o[k + "_sh"][:100]                          # already z-scored against all 1,000
        vals.append(((o[k][0, t03] - sh.mean(0)[0, t03]) / sh.std(0)[0, t03]).max())
    F1[f"b100_{k}"] = vals
print(F1.round(2).to_string())
def f1_test(r, mov):
    w = stats.wilcoxon(F1[f"{r}_syl"], F1[f"{r}_{mov}"])
    print(f"reading ({r}), {'initiations from stillness' if mov == 'movs' else 'all initiations'}: syllable > movement in "
          f"{(F1[f'{r}_syl'] > F1[f'{r}_{mov}']).sum()} of {len(F1)} mice; median {F1[f'{r}_syl'].median():.2f} against "
          f"{F1[f'{r}_{mov}'].median():.2f}; Wilcoxon W = {w.statistic:.0f}, P = {w.pvalue:.2g}")
for mov in ["movs", "mov"]:
    for r in (["a", "b"] if mov == "movs" else ["a", "b", "b100"]):
        f1_test(r, mov)
# quality control reading (b), reading (b) of the comparison
Fb = pd.DataFrame([dict(mouse=m, syl=o["syl"][0, t03].max(), mov=o["mov"][0, t03].max(), movs=o["movs"][0, t03].max())
                   for (a, m), o in ONSET_B.items() if a == "DLS"])
for mov in ["movs", "mov"]:
    w = stats.wilcoxon(Fb.syl, Fb[mov])
    print(f"QC (b), {len(DLSb)} experiments, reading (b), {'initiations from stillness' if mov == 'movs' else 'all initiations'}: "
          f"syllable > movement in {(Fb.syl > Fb[mov]).sum()} of {len(Fb)} mice; W = {w.statistic:.0f}, P = {w.pvalue:.2g}")
# Count-matched check: in each mouse, syllable onsets drawn at random down to the number of movement
# initiations (from stillness, or all detections), z-scored against 100 shuffles; the claim's seed and four more.
# The movement values are those above (reading (a) 100 shuffles, reading (b) 1,000).
CMd = pd.DataFrame(CM).merge(F1[["mouse", "a_mov", "a_movs", "b_mov", "b_movs"]], on="mouse")
print("\ncount-matched syllable values, claim seed, per mouse:")
print(CMd[CMd.seed == 0].pivot(index="mouse", columns="match", values=["n", "a_syl", "b_syl"]).round(2).to_string())
for match, mov in [("still", "movs"), ("all", "mov")]:
    for r in ["a", "b"]:
        out_ = []
        for k in CM_SEEDS:
            x = CMd[(CMd.match == match) & (CMd.seed == k)]
            w = stats.wilcoxon(x[f"{r}_syl"], x[f"{r}_{mov}"])
            out_.append(f"+{k}: {(x[f'{r}_syl'] > x[f'{r}_{mov}']).sum()}/{len(x)}, median {x[f'{r}_syl'].median():.2f}, P = {w.pvalue:.2g}")
        print(f"count-matched, reading ({r}), {'initiations from stillness' if match == 'still' else 'all initiations'} "
              f"(movement median {CMd[CMd.seed == 0][f'{r}_{mov}'].median():.2f}): syllable > movement in " + "; ".join(out_))
# The two DLS groups: syllable-onset averages of the dLight+ChrimsonR mice (reinforcement-photometry files)
# against the dLight-only mice, and the time of each mouse's maximum from 0 to +1 s
F1["group"] = F1.mouse.map(DLS.drop_duplicates("mouse").set_index("mouse").group)
F1["t_max_syl"] = [LAG[COLS][30 + np.argmax(ONSET[("DLS", m)]["syl"][0][30:])] / M.FS for m in F1.mouse]
print("\nby DLS group, medians:")
print(F1.groupby("group")[["n_syl", "a_syl", "b_syl", "a_movs", "b_movs", "b_mov", "t_max_syl"]].median().round(2).to_string())
print("time of the syllable-onset maximum (0 to +1 s) per mouse:", F1.set_index("mouse").t_max_syl.round(2).to_dict())
ga, gb = F1[F1.group == "dls-dlight"].b_syl, F1[F1.group != "dls-dlight"].b_syl
u = stats.mannwhitneyu(ga, gb, alternative="two-sided")
print(f"reading (b) syllable peak, {len(ga)} dLight-only against {len(gb)} dLight+ChrimsonR mice: U = {u.statistic:.0f} of {len(ga) * len(gb)}, P = {u.pvalue:.3f}")
for mov in ["movs", "mov"]:
    x = F1[F1.group == "dls-dlight"]
    w = stats.wilcoxon(x.b_syl, x[f"b_{mov}"])
    print(f"reading (b), the dLight-only mice only, {'initiations from stillness' if mov == 'movs' else 'all initiations'}: "
          f"syllable > movement in {(x.b_syl > x[f'b_{mov}']).sum()} of {len(x)}; P = {w.pvalue:.3f} (the smallest possible with 6 mice is 0.031)")
Movement initiations: detections per minute and 2D speed (mm/s) averaged over the second before,
at, and over the second after each detection; all detections, and those preceded by relative stillness
   area              mouse  all_per_min  all_speed_pre  all_speed_at  all_speed_post  still_per_min  still_speed_pre  still_speed_at  still_speed_post
0   DLS  dlight-chrimson-1         27.5      67.099998     82.500000      135.500000            4.3        21.700001       28.700001         96.300003
1   DLS  dlight-chrimson-2         25.6      50.000000     66.199997      108.400002            3.2        14.700000       18.700001         69.599998
2   DLS  dlight-chrimson-3         26.8      62.200001     81.699997      130.100006            3.1        18.400000       25.000000         84.099998
3   DLS  dlight-chrimson-4         27.3      56.000000     73.099998      114.699997            3.4        16.200001       20.900000         77.500000
4   DLS  dlight-chrimson-5         29.6      76.599998     98.300003      148.399994            5.5        26.799999       37.799999        107.300003
5   DLS  dlight-chrimson-6         28.3      51.599998     65.199997      103.699997            3.6        16.000000       20.500000         68.699997
6   DLS  dlight-chrimson-8         25.7      51.700001     65.000000      106.699997            3.6        16.799999       21.400000         72.500000
7   DLS  dlight-chrimson-9         27.1      64.400002     81.599998      130.699997            4.8        21.000000       27.700001         88.400002
8   DLS       dls-dlight-1         25.2      54.599998     67.800003      105.099998            2.3        14.300000       17.900000         61.000000
9   DLS       dls-dlight-2         27.2      58.299999     74.599998      118.800003            4.0        20.400000       26.700001         85.699997
10  DLS       dls-dlight-3         26.1      42.700001     54.700001       88.500000            3.0        12.300000       15.700000         55.200001
11  DLS       dls-dlight-4         25.6      50.900002     65.500000      100.800003            2.9        16.799999       20.600000         64.500000
12  DLS       dls-dlight-5         29.2      57.200001     70.000000      106.199997            4.2        17.900000       23.000000         71.699997
13  DLS       dls-dlight-7         25.9      52.799999     66.099998      105.000000            2.5        14.900000       18.900000         65.000000
14  DMS       dms-dlight-1         28.7      44.000000     57.000000       93.099998            3.6        12.100000       16.600000         57.799999
15  DMS      dms-dlight-10         25.6      54.500000     71.400002      123.199997            4.0        17.200001       22.400000         85.800003
16  DMS      dms-dlight-11         29.4      48.700001     62.200001      101.599998            4.6        14.600000       20.600000         71.300003
17  DMS      dms-dlight-13         26.5      50.900002     62.599998      102.500000            2.5        13.300000       15.800000         62.599998
18  DMS      dms-dlight-14         32.8      49.200001     60.000000       95.300003            6.1        17.000000       20.700001         69.099998
19  DMS       dms-dlight-4         28.2      44.599998     58.000000      101.599998            3.3        11.700000       15.300000         60.799999
20  DMS       dms-dlight-6         28.9      41.500000     48.900002       79.000000            3.3        13.000000       14.800000         48.900002
21  DMS       dms-dlight-8         25.4      46.700001     58.900002       87.199997            1.6        12.100000       15.000000         47.500000
median 2D speed over the DLS experiments (mm/s): 33.5
                mouse  n_syl  n_mov  n_movs  a_syl  a_mov  a_movs  b_syl  b_mov  b_movs  b100_syl  b100_mov
0   dlight-chrimson-1  33948   7574    1174   2.35   2.55    1.40   2.12  -7.50   -0.03      2.05     -7.96
1   dlight-chrimson-2  32302   7963     987   2.58   3.76    1.54  -2.65  -2.41    5.27     -2.57     -2.39
2   dlight-chrimson-3  24537   5986     696   2.24   3.83    1.21   2.73  -3.01    2.19      3.28     -3.33
3   dlight-chrimson-4  31401   8773    1095   2.27   3.34    1.19  -4.28  -5.16    0.99     -4.05     -5.07
4   dlight-chrimson-5  23122   5859    1079   1.12   2.09    1.16   0.34  -1.56    0.49      0.27     -1.77
5   dlight-chrimson-6  37178   9307    1192   2.96   4.47    1.56  -0.53  -4.84    0.74     -0.50     -4.47
6   dlight-chrimson-8  31406   7702    1060   2.00   3.03    1.00   2.58  -5.79   -1.56      2.40     -5.67
7   dlight-chrimson-9  33511   8770    1553   1.58   2.87    1.25  -0.57  -4.36    3.51     -0.66     -4.15
8        dls-dlight-1  32553   8236     731   2.45   2.34    0.82   5.02  -6.68    0.19      5.53     -6.37
9        dls-dlight-2  43107  10593    1532   1.97   2.81    1.18   3.46  -5.75   -1.32      3.51     -5.61
10       dls-dlight-3  41349  10088    1152   2.55   1.96    0.92   3.54  -4.21    0.87      3.48     -4.29
11       dls-dlight-4  37059   9884    1130   1.85   2.01    0.85   4.11  -7.28   -2.03      4.06     -7.09
12       dls-dlight-5  29909   7993    1135   2.21   2.75    0.99   4.38  -6.95    0.04      4.12     -7.26
13       dls-dlight-7  36515   8000     778   2.56   2.48    0.94   2.73  -6.62   -0.53      2.66     -6.33
reading (a), initiations from stillness: syllable > movement in 13 of 14 mice; median 2.25 against 1.17; Wilcoxon W = 1, P = 0.00024
reading (b), initiations from stillness: syllable > movement in 9 of 14 mice; median 2.65 against 0.34; Wilcoxon W = 37, P = 0.36
reading (a), all initiations: syllable > movement in 3 of 14 mice; median 2.25 against 2.78; Wilcoxon W = 9, P = 0.004
reading (b), all initiations: syllable > movement in 13 of 14 mice; median 2.65 against -5.45; Wilcoxon W = 1, P = 0.00024
reading (b100), all initiations: syllable > movement in 13 of 14 mice; median 2.53 against -5.34; Wilcoxon W = 1, P = 0.00024
QC (b), 157 experiments, reading (b), initiations from stillness: syllable > movement in 9 of 14 mice; W = 38, P = 0.39
QC (b), 157 experiments, reading (b), all initiations: syllable > movement in 13 of 14 mice; W = 1, P = 0.00024

count-matched syllable values, claim seed, per mouse:
                         n         a_syl       b_syl      
match                  all   still   all still   all still
mouse                                                     
dlight-chrimson-1   7574.0  1174.0  1.15  0.93  1.46  0.82
dlight-chrimson-2   7963.0   987.0  1.48  1.15 -2.23 -0.39
dlight-chrimson-3   5986.0   696.0  1.22  0.85  1.30 -0.53
dlight-chrimson-4   8773.0  1095.0  1.25  0.93 -1.98 -1.17
dlight-chrimson-5   5859.0  1079.0  0.79  0.92  0.72 -0.59
dlight-chrimson-6   9307.0  1192.0  1.67  1.10  0.08 -0.47
dlight-chrimson-8   7702.0  1060.0  1.25  0.96  2.54  1.81
dlight-chrimson-9   8770.0  1553.0  0.98  1.05  0.19  0.35
dls-dlight-1        8236.0   731.0  1.46  0.82  2.97  1.47
dls-dlight-2       10593.0  1532.0  1.20  0.75  1.77  0.29
dls-dlight-3       10088.0  1152.0  1.45  0.97  1.34 -0.27
dls-dlight-4        9884.0  1130.0  1.27  1.00  3.51  2.66
dls-dlight-5        7993.0  1135.0  1.46  1.13  2.53  1.85
dls-dlight-7        8000.0   778.0  1.63  1.33  1.91  0.26
count-matched, reading (a), initiations from stillness (movement median 1.17): syllable > movement in +0: 5/14, median 0.96, P = 0.068; +1000: 3/14, median 0.97, P = 0.013; +2000: 2/14, median 0.91, P = 0.0023; +3000: 2/14, median 0.84, P = 0.0031; +4000: 4/14, median 0.93, P = 0.013
count-matched, reading (b), initiations from stillness (movement median 0.34): syllable > movement in +0: 7/14, median 0.27, P = 0.86; +1000: 8/14, median 0.79, P = 0.63; +2000: 6/14, median -0.13, P = 0.5; +3000: 10/14, median 1.07, P = 0.27; +4000: 7/14, median 0.87, P = 0.9
count-matched, reading (a), all initiations (movement median 2.78): syllable > movement in +0: 0/14, median 1.26, P = 0.00012; +1000: 0/14, median 1.48, P = 0.00012; +2000: 0/14, median 1.51, P = 0.00012; +3000: 0/14, median 1.33, P = 0.00012; +4000: 0/14, median 1.42, P = 0.00012
count-matched, reading (b), all initiations (movement median -5.45): syllable > movement in +0: 14/14, median 1.40, P = 0.00012; +1000: 14/14, median 1.29, P = 0.00012; +2000: 14/14, median 1.38, P = 0.00012; +3000: 14/14, median 1.51, P = 0.00012; +4000: 14/14, median 1.20, P = 0.00012

by DLS group, medians:
                       n_syl  a_syl  b_syl  a_movs  b_movs  b_mov  t_max_syl
group                                                                       
dls-chrimson-dlight  31854.0   2.25  -0.10    1.23    0.87  -4.60       0.98
dls-dlight           36787.0   2.33   3.83    0.93   -0.24  -6.65       0.33
time of the syllable-onset maximum (0 to +1 s) per mouse: {'dlight-chrimson-1': 1.0, 'dlight-chrimson-2': 1.0, 'dlight-chrimson-3': 0.3, 'dlight-chrimson-4': 1.0, 'dlight-chrimson-5': 0.3, 'dlight-chrimson-6': 1.0, 'dlight-chrimson-8': 0.3, 'dlight-chrimson-9': 0.97, 'dls-dlight-1': 0.3, 'dls-dlight-2': 0.33, 'dls-dlight-3': 0.33, 'dls-dlight-4': 0.33, 'dls-dlight-5': 0.3, 'dls-dlight-7': 0.33}
reading (b) syllable peak, 6 dLight-only against 8 dLight+ChrimsonR mice: U = 48 of 48, P = 0.001
reading (b), the dLight-only mice only, initiations from stillness: syllable > movement in 6 of 6; P = 0.031 (the smallest possible with 6 mice is 0.031)
reading (b), the dLight-only mice only, all initiations: syllable > movement in 6 of 6; P = 0.031 (the smallest possible with 6 mice is 0.031)

Result: partially reproduced; the criterion is met by one reading, and the other reading goes the opposite way once event counts are matched. With the changepoint derivative taken per second (per frame no peak reaches the height of 1), all detections occur 25 to 30 times a minute and the mean speed in the second before them is 43 to 77 mm/s, above the median of 33.5 mm/s, so most are not the Methods' transitions from stillness. Keeping the detections preceded by relative stillness (mean speed 12 to 27 mm/s in the second before, 55 to 107 mm/s in the second after), reading (a) gives syllable onsets above movement initiations in 13 of 14 mice (medians 2.25 against 1.17, Wilcoxon P = 0.00024), and reading (b) does not (9 of 14, P = 0.36). With all detections, the criterion's definition, (b) favours syllables (13 of 14, P = 0.00024, also with 100 shuffles and under quality control (b)) and (a) favours movement initiations (3 of 14, P = 0.004).

The shuffle z grows with the number of events, and syllable onsets outnumber initiations from stillness about 30 to 1 (23,122 to 43,107 against 696 to 1,553 per mouse). With syllable onsets drawn down to each mouse's initiation count, reading (a) no longer favours syllables over initiations from stillness: syllables are higher in 5 of 14 mice (P = 0.068) under the claim's seed and in 2 to 4 of 14 under the four further seeds (P 0.0023 to 0.013), favouring initiations. Reading (b) shows no difference (6 to 10 of 14, P 0.27 to 0.90). Matched to all detections, (b) favours syllables in 14 of 14 mice and (a) favours movement in 14 of 14 (P = 0.00012 under all five seeds). So the reproduced outcome recorded in round 2, which rested on reading (a) with initiations from stillness, came from the difference in event counts. Under the criterion's definition reading (b) meets the rule and reading (a) is significant in the opposite direction, so the claim holds in part; the round-3 verifier agreed and the outcome is now partially reproduced. The criterion has no rule for readings significant in opposite directions, and read literally reading (b) alone would meet it; this gap is a question for a reader.

The two DLS groups differ: the reading (b) syllable peak has a median of 3.83 in the 6 dLight-only mice and -0.10 in the 8 dLight+ChrimsonR mice (U = 48 of 48, P = 0.001), and the syllable-onset average reaches its maximum within 0 to +1 s at 0.30 to 0.33 s in every dLight-only mouse but at 0.97 to 1.0 s in 5 of the 8 dLight+ChrimsonR mice. In the dLight-only mice alone reading (b) favours syllables in 6 of 6 under both definitions (P = 0.031, the smallest possible). The clock check (sanity cell) gives the same best shift in both groups, so the difference is not explained here.

fig1f-dip-then-peak¶

"DLS dopamine fluctuates at syllable transitions with a dip followed by a peak."

In [10]:
tt = LAG[COLS] / M.FS
for key, label in [("syl", "1,000 shuffles")]:
    mice = sorted(F1.mouse)
    avg = np.mean([ONSET[("DLS", m)][key][0] for m in mice], 0)
    sh = np.mean([ONSET[("DLS", m)][key + "_sh"][:, 0, :] for m in mice], 0)   # shuffles averaged over mice
    lo, hi = np.percentile(sh, [2.5, 97.5], axis=0)
    below = np.flatnonzero(avg < lo); above = np.flatnonzero(avg > hi)
    imin, imax = np.argmin(avg), np.argmax(avg)
    print(f"{label}: minimum {avg[imin]:.2f} at {tt[imin]:+.3f} s (interval {lo[imin]:.2f} to {hi[imin]:.2f}); "
          f"maximum {avg[imax]:.2f} at {tt[imax]:+.3f} s (interval {lo[imax]:.2f} to {hi[imax]:.2f})")
    print("  times below the interval:", np.round(tt[below], 3))
    print("  times above the interval:", np.round(tt[above], 3))
    holds = len(below) > 0 and len(above) > 0 and tt[imin] < tt[imax] and avg[imin] < lo[imin] and avg[imax] > hi[imax]
    print("  dip below the interval followed by a peak above it:", holds)
    per_mouse = [(tt[np.argmin(ONSET[("DLS", m)][key][0])] < tt[np.argmax(ONSET[("DLS", m)][key][0])]) for m in mice]
    print("  mice whose minimum precedes their maximum within -1 to +1 s:", sum(per_mouse), "of", len(mice))
fig, ax = plt.subplots(figsize=(5, 3))
ax.fill_between(tt, lo, hi, color="0.85", label="95% shuffle interval")
ax.plot(tt, avg, "k", label="mean of 14 mice")
ax.axvline(0, ls=":", c="0.5"); ax.set_xlabel("time from syllable onset (s)"); ax.set_ylabel("dLight (z vs shuffles)")
ax.legend(fontsize=7); plt.tight_layout(); plt.show()
print("plotted range of the average:", avg.min().round(2), "to", avg.max().round(2))
1,000 shuffles: minimum -16.33 at +0.000 s (interval -0.55 to 0.56); maximum 1.67 at +1.000 s (interval -0.53 to 0.49)
  times below the interval: [-0.967 -0.933 -0.9   -0.867 -0.833 -0.8   -0.767 -0.733 -0.7   -0.667
 -0.633 -0.6   -0.567 -0.533 -0.5   -0.467 -0.433 -0.4   -0.367 -0.333
 -0.3   -0.267 -0.233 -0.2   -0.167 -0.133 -0.1   -0.067 -0.033  0.
  0.033  0.067  0.1    0.133  0.167  0.2  ]
  times above the interval: [0.267 0.3   0.333 0.367 0.4   0.633 0.667 0.7   0.733 0.767 0.8   0.833
 0.867 0.9   0.933 0.967 1.   ]
  dip below the interval followed by a peak above it: True
  mice whose minimum precedes their maximum within -1 to +1 s: 13 of 14
No description has been provided for this image
plotted range of the average: -16.33 to 1.67

Result: reproduced, resting on the claims file's assumed window. The mean of the 14 mice falls below the 95% shuffle interval from -0.97 to +0.2 s, with its minimum (-16.33) at the onset, and rises above it from +0.27 to +0.4 s and from +0.63 s on; the minimum precedes the maximum in 13 of 14 mice. The maximum (1.67) is at +1.0 s, the edge of the assumed window, where the average is still rising; the peak inside the window that the criterion needs is the rise above the interval at +0.27 to +0.4 s. In 5 of the 8 dLight+ChrimsonR mice the syllable-onset average has its maximum at 0.97 to 1.0 s (fig1f section).

fig1j-weak-kinematic-correlation¶

"Syllable-associated dopamine transient amplitudes correlate only weakly with the velocity and angular velocity of the syllable instance."

In [11]:
from sklearn.linear_model import HuberRegressor
from sklearn.model_selection import KFold

def huber_cv_r(x, y, rng, n_rep=100, eps=1.05, fit_intercept=True):
    """Pearson r of pooled held-out predictions of a Huber regression, per repeat of fivefold CV."""
    x = np.asarray(x, float).reshape(len(x), -1); y = np.asarray(y, float)
    rs = []
    for _ in range(n_rep):
        pred = np.empty_like(y)
        for tr, te in KFold(5, shuffle=True, random_state=int(rng.integers(2**31))).split(x):
            h = HuberRegressor(epsilon=eps, fit_intercept=fit_intercept, max_iter=500).fit(x[tr], y[tr])
            pred[te] = h.predict(x[te])
        rs.append(np.corrcoef(pred, y)[0, 1])
    return np.array(rs)

def huber_shuffle(x, y, rng, n_shuf=1000, n_rep=5, **kw):
    """Null of held-out r with x permuted (fivefold repeated n_rep times, as the code's null)."""
    return np.array([np.nanmean(huber_cv_r(rng.permutation(x), y, rng, n_rep=n_rep, **kw)) for _ in range(n_shuf)])
In [12]:
rng = rng_for("fig1j-weak-kinematic-correlation")
samp = pd.concat([g.sample(2000, random_state=int(rng.integers(2**31)))
                  for _, g in Ic[np.isfinite(Ic.dur)].groupby("mouse")])
print("instances:", len(samp), "from", samp.mouse.nunique(), "mice")
R1j = {}
for dl, dname in [("da", "(a) max z 0-0.3 s"), ("zmean", "(b) mean z over the instance")]:
    for kin in ["vel", "angvel"]:
        x = samp[kin].to_numpy(); y = samp[dl].to_numpy()
        if kin == "angvel":
            x = np.abs(x)
        # 5 repeats of fivefold CV (the claims file says 100; the spread over repeats is in the
        # third decimal); the shuffle P uses the plain Pearson r over 1,000 permutations, as the
        # Huber fits on 28,000 points are too slow to repeat 1,000 times here
        r = huber_cv_r(x, y, rng, n_rep=5)
        r0 = np.corrcoef(x, y)[0, 1]
        null = np.array([np.corrcoef(rng.permutation(x), y)[0, 1] for _ in range(1000)])
        p = (1 + np.sum(np.abs(null) >= abs(r0))) / 1001
        R1j[(dl, kin)] = r.mean()
        print(f"{dname}, {kin}: held-out r = {r.mean():.3f} (range over repeats {r.min():.3f} to {r.max():.3f}); "
              f"raw Pearson r = {r0:.3f}; shuffle |r| 95th pct {np.percentile(np.abs(null), 95):.3f}, P = {p:.4f}")
print("all |r| < 0.3 under reading (a):", all(abs(R1j[("da", k)]) < 0.3 for k in ["vel", "angvel"]),
      "; under (b):", all(abs(R1j[("zmean", k)]) < 0.3 for k in ["vel", "angvel"]))
instances: 28000 from 14 mice
(a) max z 0-0.3 s, vel: held-out r = 0.090 (range over repeats 0.088 to 0.090); raw Pearson r = -0.091; shuffle |r| 95th pct 0.011, P = 0.0010
(a) max z 0-0.3 s, angvel: held-out r = 0.025 (range over repeats 0.024 to 0.027); raw Pearson r = -0.028; shuffle |r| 95th pct 0.012, P = 0.0010
(b) mean z over the instance, vel: held-out r = 0.079 (range over repeats 0.078 to 0.079); raw Pearson r = -0.079; shuffle |r| 95th pct 0.012, P = 0.0010
(b) mean z over the instance, angvel: held-out r = 0.017 (range over repeats 0.015 to 0.019); raw Pearson r = -0.019; shuffle |r| 95th pct 0.012, P = 0.0030
all |r| < 0.3 under reading (a): True ; under (b): True

Result: reproduced, against the claims file's assumed bound of |r| < 0.3. On 28,000 instances the held-out r is 0.090 (velocity) and 0.025 (angular velocity) under reading (a) and 0.079 and 0.017 under reading (b); the raw correlations are negative (-0.091 and -0.028 under (a)).

fig2b-dlight-usage-across-syllables¶

"Syllables associated on average with more DLS dopamine in an experiment tend to be used more."

In [13]:
def per_exp_syllable(II):
    """Per experiment and syllable: mean syllable-associated dLight, count, outgoing-transition entropy."""
    g = II.groupby(["mouse", "exp", "label"])
    T = g.agg(da=("da", "mean"), count=("da", "size")).reset_index()
    # outgoing transitions within the experiment, destinations among the 37 syllables, prior 1/36
    # on each (dm_entropy in the fig_2b, 2i notebook), log base 2
    ent = []
    for e, x in II.groupby("exp"):
        lab = x.label.to_numpy()
        src, dst = lab[:-1], lab[1:]
        ok = np.isin(dst, SYL37)
        C = np.zeros((lab.max() + 1, len(SYL37)))
        np.add.at(C, (src[ok], np.searchsorted(SYL37, dst[ok])), 1)
        H = M.dm_entropy(C, 1 / 36)
        ent.append(pd.DataFrame(dict(exp=e, label=np.arange(len(C)), entropy=H)))
    return T.merge(pd.concat(ent), on=["exp", "label"], how="left")

PE = per_exp_syllable(Ic)
PE["da_z"] = PE.groupby("exp").da.transform(lambda v: (v - v.mean()) / v.std())
tot = PE.groupby(["mouse", "label"])["count"].sum()
PM = PE.groupby(["mouse", "label"]).agg(da_z=("da_z", "mean"), count=("count", "mean"), entropy=("entropy", "mean"))
PM = PM[tot.reindex(PM.index) >= 100].reset_index()
print("mouse-syllable pairs with at least 100 instances:", len(PM), "in", PM.mouse.nunique(), "mice")
mouse-syllable pairs with at least 100 instances: 719 in 14 mice
In [14]:
def fig2_test(x, y, claim, n_shuf=1000):
    rng = rng_for(claim)
    r = huber_cv_r(x, y, rng, n_rep=100)
    null = huber_shuffle(x, y, rng, n_shuf=n_shuf, n_rep=5)
    p = (1 + np.sum(null >= r.mean())) / (1 + n_shuf)
    return r.mean(), r.min(), r.max(), p, null

r, rmin, rmax, p, null = fig2_test(PM.da_z, PM["count"], "fig2b-dlight-usage-across-syllables")
print(f"held-out r = {r:.3f} (repeats {rmin:.3f} to {rmax:.3f}); null 95th percentile {np.percentile(null, 95):.3f}; one-sided P = {p:.4f}; n = {len(PM)}")
print("raw Pearson r:", round(np.corrcoef(PM.da_z, PM["count"])[0, 1], 3), "; Spearman:", round(stats.spearmanr(PM.da_z, PM["count"])[0], 3))
print("per mouse Spearman r:", PM.groupby("mouse").apply(lambda g: round(stats.spearmanr(g.da_z, g["count"])[0], 2), include_groups=False).to_dict())
# code's variant: dLight z-scored within mouse across experiment-syllable rows, instances shorter than 0.3 s left out
Iv = Ic[Ic.dur >= 0.3]
PEv = Iv.groupby(["mouse", "exp", "label"]).agg(da=("da", "mean"), count=("da", "size")).reset_index()
PEv["da_z"] = PEv.groupby("mouse").da.transform(lambda v: (v - v.mean()) / v.std())
PMv = PEv.groupby(["mouse", "label"]).agg(da_z=("da_z", "mean")).join(PM.set_index(["mouse", "label"])["count"], how="inner").reset_index()
rv = huber_cv_r(PMv.da_z, PMv["count"], rng_for("fig2b-dlight-usage-across-syllables", 1), n_rep=20)
print(f"variant (code): held-out r = {rv.mean():.3f}, n = {len(PMv)}")
held-out r = 0.194 (repeats 0.169 to 0.207); null 95th percentile 0.035; one-sided P = 0.0010; n = 719
raw Pearson r: 0.208 ; Spearman: 0.164
per mouse Spearman r: {'dlight-chrimson-1': 0.04, 'dlight-chrimson-2': 0.35, 'dlight-chrimson-3': 0.24, 'dlight-chrimson-4': 0.21, 'dlight-chrimson-5': -0.03, 'dlight-chrimson-6': 0.29, 'dlight-chrimson-8': 0.21, 'dlight-chrimson-9': 0.03, 'dls-dlight-1': 0.06, 'dls-dlight-2': 0.12, 'dls-dlight-3': 0.06, 'dls-dlight-4': 0.16, 'dls-dlight-5': 0.22, 'dls-dlight-7': 0.25}
variant (code): held-out r = 0.192, n = 719

Result: reproduced. Over 719 mouse-syllable pairs, the held-out r between experiment-normalised dLight and counts is 0.194 (one-sided shuffle P = 0.001); the code's variant gives 0.192.

fig2i-dlight-entropy-across-syllables¶

In [15]:
r, rmin, rmax, p, null = fig2_test(PM.da_z, PM.entropy, "fig2i-dlight-entropy-across-syllables")
print(f"held-out r = {r:.3f} (repeats {rmin:.3f} to {rmax:.3f}); null 95th percentile {np.percentile(null, 95):.3f}; one-sided P = {p:.4f}; n = {len(PM)}")
print("raw Pearson r:", round(np.corrcoef(PM.da_z, PM.entropy)[0, 1], 3))
held-out r = 0.197 (repeats 0.163 to 0.210); null 95th percentile 0.037; one-sided P = 0.0010; n = 719
raw Pearson r: 0.211

Result: reproduced. The held-out r between experiment-normalised dLight and outgoing-transition entropy is 0.197 (one-sided shuffle P = 0.001, n = 719).

fig2b-across-experiments¶

In [16]:
PEa = PE.copy()
nexp = PEa.groupby("mouse").exp.nunique()
avg_per_sess = PEa.groupby(["mouse", "label"])["count"].sum() / nexp.reindex(PEa.groupby(["mouse", "label"])["count"].sum().index.get_level_values(0)).to_numpy()
keep = avg_per_sess[avg_per_sess >= 50].index
PEa = PEa.set_index(["mouse", "label"]).loc[keep].reset_index()
zs = lambda v: (v - v.mean()) / v.std() if v.std() > 0 else v * np.nan
PEa["da_zs"] = PEa.groupby(["mouse", "label"]).da.transform(zs)
PEa["count_zs"] = PEa.groupby(["mouse", "label"])["count"].transform(zs)
PX = PEa.groupby(["mouse", "exp"]).agg(da=("da_zs", "mean"), freq=("count_zs", "mean")).dropna().reset_index()
print("syllable-mouse pairs kept (>= 50 per session on average):", len(keep), "; experiments:", len(PX))
r, rmin, rmax, p, null = fig2_test(PX.da, PX.freq, "fig2b-across-experiments")
print(f"held-out r = {r:.3f} (repeats {rmin:.3f} to {rmax:.3f}); null 95th percentile {np.percentile(null, 95):.3f}; one-sided P = {p:.4f}")
print("raw Pearson r:", round(np.corrcoef(PX.da, PX.freq)[0, 1], 3))
syllable-mouse pairs kept (>= 50 per session on average): 335 ; experiments: 164
held-out r = 0.186 (repeats 0.095 to 0.228); null 95th percentile 0.068; one-sided P = 0.0030
raw Pearson r: 0.234

Result: reproduced. Over 164 experiments (335 syllable-mouse pairs kept), the held-out r between z-scored dLight and z-scored frequency is 0.186 (one-sided shuffle P = 0.003).

ed7-dms-fewer-transients, ed7b-dms-transient-shape, ed7d-dms-smaller-peaks¶

In [17]:
def crossings(z, thr=1.0, hold=3, floor=0.25):
    """Upward crossings of thr, kept when the next `hold` samples stay at or above `floor`
    (get_ncrossings in the fig_s07 notebook, as the claims file cites it)."""
    up = np.flatnonzero((z[:-1] < thr) & (z[1:] >= thr)) + 1
    ok = [i for i in up if i + hold < len(z) and np.all(z[i + 1:i + 1 + hold] >= floor)]
    return np.array(ok, int)

def exp_z(i):
    z = SESS[i]["z"].astype(float)
    return (z - np.nanmean(z)) / np.nanstd(z)

TR = []
for area, sub in [("DLS", DLS), ("DMS", DMS)]:
    for _, r in sub.iterrows():
        z = exp_z(r.i)
        c = crossings(z)
        nb = len(z) // 9000                            # 300-s bins
        rate = [np.sum((c >= k * 9000) & (c < (k + 1) * 9000)) / 300 for k in range(nb)]
        snip = [z[j - 90:j + 91] for j in c if j - 90 >= 0 and j + 91 <= len(z)]
        TR.append(dict(area=area, mouse=r.mouse, exp=r.i, rate=np.mean(rate) if rate else np.nan, n=len(c),
                       wave=np.mean(snip, 0) if snip else np.full(181, np.nan)))
TR = pd.DataFrame(TR)
print(TR.groupby("area").agg(experiments=("exp", "size"), mice=("mouse", "nunique"), transients=("n", "sum")).to_string())
      experiments  mice  transients
area                               
DLS           164    14      235564
DMS            75     8      105897
In [18]:
pm = TR.groupby(["area", "mouse"]).rate.agg(["mean", "median"]).reset_index()
for stat_ in ["mean", "median"]:
    a = pm[pm.area == "DLS"][stat_]; b = pm[pm.area == "DMS"][stat_]
    u = stats.mannwhitneyu(a, b, alternative="two-sided")
    print(f"per-mouse {stat_} rate (per s): DLS median {a.median():.3f} (n={len(a)}), DMS median {b.median():.3f} (n={len(b)}); "
          f"U = {u.statistic:.0f}, f = {u.statistic / (len(a) * len(b)):.2f}, P = {u.pvalue:.4f}")
print(pm.round(3).to_string())
per-mouse mean rate (per s): DLS median 0.882 (n=14), DMS median 0.822 (n=8); U = 101, f = 0.90, P = 0.0012
per-mouse median rate (per s): DLS median 0.881 (n=14), DMS median 0.829 (n=8); U = 102, f = 0.91, P = 0.0009
   area              mouse   mean  median
0   DLS  dlight-chrimson-1  0.923   0.926
1   DLS  dlight-chrimson-2  0.840   0.834
2   DLS  dlight-chrimson-3  0.873   0.868
3   DLS  dlight-chrimson-4  0.833   0.852
4   DLS  dlight-chrimson-5  1.002   1.011
5   DLS  dlight-chrimson-6  0.848   0.849
6   DLS  dlight-chrimson-8  0.881   0.883
7   DLS  dlight-chrimson-9  0.884   0.874
8   DLS       dls-dlight-1  0.936   0.934
9   DLS       dls-dlight-2  0.906   0.906
10  DLS       dls-dlight-3  0.927   0.931
11  DLS       dls-dlight-4  0.885   0.894
12  DLS       dls-dlight-5  0.880   0.879
13  DLS       dls-dlight-7  0.878   0.869
14  DMS       dms-dlight-1  0.888   0.886
15  DMS      dms-dlight-10  0.842   0.844
16  DMS      dms-dlight-11  0.780   0.828
17  DMS      dms-dlight-13  0.827   0.829
18  DMS      dms-dlight-14  0.713   0.770
19  DMS       dms-dlight-4  0.833   0.839
20  DMS       dms-dlight-6  0.818   0.822
21  DMS       dms-dlight-8  0.817   0.809

Result: reproduced. DMS mice have fewer transients per second than DLS mice (median of per-mouse means 0.822 against 0.882; U = 101, f = 0.90, P = 0.0012, 0.0047 after Holm), and U is within the tolerance of 97 +- 9.7. Under quality control (b) U = 107, P = 0.0001.

In [19]:
def shape(w):
    """fig_s07 notebook as cited: re-align where the slope first exceeds 0.035, then over 0-2 s area
    (trapezoid), time to peak, and full width at half maximum after cubic interpolation to 500 Hz."""
    from scipy.interpolate import interp1d
    sl = np.diff(w)
    k = np.flatnonzero(sl[:90] > 0.035)
    st = k[0] if len(k) else 90
    seg = w[st:st + 61]
    t = np.arange(len(seg)) / M.FS
    area_ = np.trapezoid(seg, t)
    tp = t[np.argmax(seg)]
    f = interp1d(t, seg, kind="cubic")
    tf = np.arange(0, t[-1], 1 / 500)
    sf = f(tf)
    half = sf.min() + (sf.max() - sf.min()) / 2
    above = np.flatnonzero(sf >= half)
    fwhm = (above[-1] - above[0]) / 500 if len(above) else np.nan
    shape.tp_interp = tf[np.argmax(sf)]               # variant: time to peak on the 500 Hz curve
    return area_, tp, fwhm

SH = []
for (area, m), g in TR.groupby(["area", "mouse"]):
    w = np.nanmean(np.stack(g.wave), 0)
    a_, tp, fw = shape(w)
    SH.append(dict(area=area, mouse=m, area_=a_, ttp=tp, fwhm=fw, ttp500=shape.tp_interp))
SH = pd.DataFrame(SH)
print(SH.round(3).to_string())
ps, us = [], []
for k in ["area_", "ttp", "fwhm"]:
    a = SH[SH.area == "DLS"][k]; b = SH[SH.area == "DMS"][k]
    u = stats.mannwhitneyu(a, b, alternative="two-sided"); ps.append(u.pvalue); us.append(u.statistic)
    print(f"{k}: DLS median {a.median():.3f}, DMS median {b.median():.3f}, U = {u.statistic:.0f}, P = {u.pvalue:.4f}")
a = SH[SH.area == "DLS"].ttp500; b = SH[SH.area == "DMS"].ttp500
u = stats.mannwhitneyu(a, b, alternative="two-sided")
print(f"variant, time to peak on the 500 Hz curve: DLS median {a.median():.3f}, DMS median {b.median():.3f}, U = {u.statistic:.0f}, P = {u.pvalue:.4f}")
rate_p = stats.mannwhitneyu(pm[pm.area == "DLS"]["mean"], pm[pm.area == "DMS"]["mean"]).pvalue
print("Holm over the four statistics (rate, area, time to peak, width):", np.round(M.holm([rate_p] + ps), 4))
# Quality control reading (b): the same four statistics on its experiment set
TRb = TR[TR.exp.isin(set(DLSb.i) | set(DMSb.i))]
pmb = TRb.groupby(["area", "mouse"]).rate.mean().reset_index()
SHb = pd.DataFrame([dict(area=a, mouse=m, **dict(zip(["area_", "ttp", "fwhm"], shape(np.nanmean(np.stack(g.wave), 0)))))
                    for (a, m), g in TRb.groupby(["area", "mouse"])])
psb = []
for k, D in [("rate", pmb), ("area_", SHb), ("ttp", SHb), ("fwhm", SHb)]:
    a = D[D.area == "DLS"][k]; b = D[D.area == "DMS"][k]
    u = stats.mannwhitneyu(a, b, alternative="two-sided"); psb.append(u.pvalue)
    print(f"QC (b), {len(TRb)} experiments, {k}: DLS median {a.median():.3f}, DMS median {b.median():.3f}, U = {u.statistic:.0f}, P = {u.pvalue:.4f}")
print("QC (b), Holm over the four:", np.round(M.holm(psb), 4))
   area              mouse  area_  ttp   fwhm  ttp500
0   DLS  dlight-chrimson-1  0.350  0.1  0.196   0.098
1   DLS  dlight-chrimson-2  0.518  0.2  0.288   0.194
2   DLS  dlight-chrimson-3  0.356  0.1  0.202   0.098
3   DLS  dlight-chrimson-4  0.591  0.2  0.316   0.190
4   DLS  dlight-chrimson-5  0.296  0.1  0.174   0.096
5   DLS  dlight-chrimson-6  0.390  0.1  0.204   0.098
6   DLS  dlight-chrimson-8  0.383  0.1  0.212   0.096
7   DLS  dlight-chrimson-9  0.392  0.2  0.210   0.196
8   DLS       dls-dlight-1  0.305  0.2  0.178   0.194
9   DLS       dls-dlight-2  0.342  0.2  0.190   0.194
10  DLS       dls-dlight-3  0.312  0.2  0.178   0.194
11  DLS       dls-dlight-4  0.354  0.2  0.190   0.196
12  DLS       dls-dlight-5  0.343  0.1  0.178   0.098
13  DLS       dls-dlight-7  0.364  0.2  0.190   0.194
14  DMS       dms-dlight-1  0.371  0.3  0.202   0.288
15  DMS      dms-dlight-10  0.411  0.2  0.254   0.194
16  DMS      dms-dlight-11  0.524  0.2  0.276   0.196
17  DMS      dms-dlight-13  0.387  0.2  0.224   0.196
18  DMS      dms-dlight-14  0.452  0.2  0.258   0.204
19  DMS       dms-dlight-4  0.399  0.2  0.268   0.196
20  DMS       dms-dlight-6  0.407  0.2  0.268   0.192
21  DMS       dms-dlight-8  0.449  0.2  0.274   0.192
area_: DLS median 0.355, DMS median 0.409, U = 20, P = 0.0128
ttp: DLS median 0.200, DMS median 0.200, U = 28, P = 0.0213
fwhm: DLS median 0.193, DMS median 0.263, U = 20, P = 0.0137
variant, time to peak on the 500 Hz curve: DLS median 0.192, DMS median 0.196, U = 22, P = 0.0180
Holm over the four statistics (rate, area, time to peak, width): [0.0047 0.0385 0.0385 0.0385]
QC (b), 221 experiments, rate: DLS median 0.881, DMS median 0.822, U = 107, P = 0.0001
QC (b), 221 experiments, area_: DLS median 0.357, DMS median 0.409, U = 20, P = 0.0128
QC (b), 221 experiments, ttp: DLS median 0.200, DMS median 0.200, U = 32, P = 0.0378
QC (b), 221 experiments, fwhm: DLS median 0.194, DMS median 0.263, U = 16, P = 0.0070
QC (b), Holm over the four: [0.0005 0.0257 0.0378 0.021 ]

Result: not reproduced. Time to peak (U = 28, P = 0.0213) and width (U = 20, P = 0.0137) differ, 0.0385 after Holm, but so does area (U = 20, P = 0.0128, 0.0385 after Holm), which the paper reports as not significant, and none of the three U values is within its tolerance (4, 16 and 27 in the paper). Under quality control (b) area is also significant (Holm P = 0.0257).

In [20]:
pk_cols = np.arange(30 - 5, 30 + 16)           # -5 .. +15 samples around onset, in COLS
PK = pd.DataFrame([dict(area=a, mouse=m, syl=o["syl"][0, pk_cols].max(), mov=o["mov"][0, pk_cols].max(),
                        movs=o["movs"][0, pk_cols].max(), n_syl=o["n_syl"], n_mov=o["n_mov"], n_movs=o["n_movs"])
                   for (a, m), o in ONSET.items()])
print(PK.round(2).to_string())
for k in ["mov", "movs", "syl"]:
    a = PK[PK.area == "DLS"][k]; b = PK[PK.area == "DMS"][k]
    u = stats.mannwhitneyu(a, b, alternative="two-sided")
    print(f"{k}: DLS median {a.median():.2f}, DMS median {b.median():.2f}; U = {u.statistic:.0f} (max {len(a) * len(b)}), P = {u.pvalue:.2e}")
PKb = pd.DataFrame([dict(area=a, mouse=m, syl=o["syl"][0, pk_cols].max(), mov=o["mov"][0, pk_cols].max(),
                         movs=o["movs"][0, pk_cols].max()) for (a, m), o in ONSET_B.items()])
for k in ["mov", "movs", "syl"]:
    a = PKb[PKb.area == "DLS"][k]; b = PKb[PKb.area == "DMS"][k]
    u = stats.mannwhitneyu(a, b, alternative="two-sided")
    print(f"QC (b) ({len(DLSb)} DLS, {len(DMSb)} DMS experiments), {k}: DLS median {a.median():.2f}, DMS median {b.median():.2f}; "
          f"U = {u.statistic:.0f}, P = {u.pvalue:.2e}")
# the dLight-only DLS mice alone against DMS (the two DLS groups differ in their syllable-onset peaks; see fig1f)
PK["group"] = PK.mouse.map(S.drop_duplicates("mouse").set_index("mouse").group)
for k in ["syl", "movs", "mov"]:
    a = PK[PK.group == "dls-dlight"][k]; b = PK[PK.area == "DMS"][k]
    u = stats.mannwhitneyu(a, b, alternative="two-sided")
    print(f"{len(a)} dLight-only DLS mice against {len(b)} DMS mice, {k}: medians {a.median():.2f} and {b.median():.2f}; U = {u.statistic:.0f} (max {len(a) * len(b)}), P = {u.pvalue:.3f}")
print("instances per mouse differ between areas and the shuffle z grows with them: syllable onsets per mouse, DLS median",
      PK[PK.area == "DLS"].n_syl.median(), "DMS median", PK[PK.area == "DMS"].n_syl.median())
   area              mouse   syl   mov  movs  n_syl  n_mov  n_movs
0   DLS  dlight-chrimson-1  2.12 -6.07  3.09  33948   7574    1174
1   DLS  dlight-chrimson-2 -2.49 -0.21  7.46  32302   7963     987
2   DLS  dlight-chrimson-3  2.73 -2.76  3.58  24537   5986     696
3   DLS  dlight-chrimson-4 -3.00 -2.15  5.54  31401   8773    1095
4   DLS  dlight-chrimson-5  0.34 -1.25  1.25  23122   5859    1079
5   DLS  dlight-chrimson-6  1.39 -3.47  3.77  37178   9307    1192
6   DLS  dlight-chrimson-8  2.58 -2.61  1.63  31406   7702    1060
7   DLS  dlight-chrimson-9  0.17 -3.64  3.51  33511   8770    1553
8   DLS       dls-dlight-1  5.02 -5.11  0.19  32553   8236     731
9   DLS       dls-dlight-2  3.83 -4.94  0.66  43107  10593    1532
10  DLS       dls-dlight-3  4.71 -4.21  1.63  41349  10088    1152
11  DLS       dls-dlight-4  4.30 -6.17 -0.59  37059   9884    1130
12  DLS       dls-dlight-5  4.38 -5.99  0.63  29909   7993    1135
13  DLS       dls-dlight-7  3.42 -6.48  1.74  36515   8000     778
14  DMS       dms-dlight-1  1.86 -5.77  1.05  27167   8097    1010
15  DMS      dms-dlight-10 -0.54 -3.73  2.15  34294   9088    1410
16  DMS      dms-dlight-11 -2.21 -0.82  4.33  22470   9074    1407
17  DMS      dms-dlight-13  2.59 -2.37  3.72  18519   5243     509
18  DMS      dms-dlight-14  3.98 -4.34  1.36  19388   5840    1095
19  DMS       dms-dlight-4 -0.12 -1.93  3.26  20903   6085     700
20  DMS       dms-dlight-6 -1.31 -0.53  6.62  28184   7848     890
21  DMS       dms-dlight-8  0.65 -5.13  2.48  26112   8288     532
mov: DLS median -3.93, DMS median -3.05; U = 42 (max 112), P = 3.65e-01
movs: DLS median 1.69, DMS median 2.87; U = 42 (max 112), P = 3.65e-01
syl: DLS median 2.65, DMS median 0.27; U = 78 (max 112), P = 1.45e-01
QC (b) (157 DLS, 64 DMS experiments), mov: DLS median -3.77, DMS median -2.55; U = 35, P = 1.65e-01
QC (b) (157 DLS, 64 DMS experiments), movs: DLS median 2.08, DMS median 2.87; U = 42, P = 3.65e-01
QC (b) (157 DLS, 64 DMS experiments), syl: DLS median 2.65, DMS median 0.27; U = 77, P = 1.65e-01
6 dLight-only DLS mice against 8 DMS mice, syl: medians 4.34 and 0.27; U = 46 (max 48), P = 0.003
6 dLight-only DLS mice against 8 DMS mice, movs: medians 0.64 and 2.87; U = 4 (max 48), P = 0.008
6 dLight-only DLS mice against 8 DMS mice, mov: medians -5.55 and -3.05; U = 7 (max 48), P = 0.029
instances per mouse differ between areas and the shuffle z grows with them: syllable onsets per mouse, DLS median 33032.0 DMS median 24291.0

Result: not reproduced. Peaks at syllable onsets (U = 78, P = 0.145) do not differ between the 14 DLS and 8 DMS mice, nor do peaks at movement initiations, all detections (U = 42, P = 0.365) or those from stillness (U = 42, P = 0.365, DMS higher); the paper reports U = 109 and 110. Quality control (b) gives the same pattern. With only the 6 dLight-only DLS mice, whose syllable-onset peaks are higher than the dLight+ChrimsonR mice's (fig1f section), the syllable half holds (U = 46 of 48, P = 0.003), but the movement half is significant in the opposite direction, DMS higher, for initiations from stillness (U = 4, P = 0.008) and for all detections (U = 7, P = 0.029).

fig2e-dlight-predicts-future-usage, fig2e-not-autocorrelation, fig2h-specific-to-syllable¶

Methods, "Analysing the moment-to-moment relationship between dLight and syllable statistics within an experiment", with the details the claims file takes from dlight_03, dlight_04 and dlight_08.

In [21]:
SEG = np.array([0, 360, 660, 900, 1680, 1800.01])     # segment edges (s), Extended Data Fig. 2e
NS = np.arange(10, 391, 20)                           # n = 10 .. 390 syllables
OFFS = np.arange(-5, 6)
NMAX = NS.max()

def fig2e_table(II):
    """Per index instance (one of the 37 syllables, with 390 following syllables and 5 before in
    the experiment): dLight, group (mouse, syllable, segment), and the behavioural measures."""
    out_x, out_Y, out_g, out_exp, out_seg = [], [], [], [], []
    for e, x in II.groupby("exp", sort=False):
        lab = x.label.to_numpy(); da = x.da.to_numpy(); vel = x.vel.to_numpy()
        t = x.onset.to_numpy() - x.onset.to_numpy()[0]
        n = len(lab)
        j = np.arange(5, n - NMAX)
        j = j[np.isin(lab[j], SYL37)]
        if len(j) == 0:
            continue
        oh = np.zeros((n + 1, lab.max() + 1), np.int32)
        oh[np.arange(n) + 1, lab] = 1
        coh = np.cumsum(oh, 0)                              # coh[k, L] = count of L in lab[:k]
        cda = np.r_[0, np.cumsum(da)]
        cvel = np.r_[0, np.cumsum(vel)]
        Y = []
        for nn in NS:                                       # same syllable among the next n - 1
            Y.append(coh[j + nn, lab[j]] - coh[j + 1, lab[j]])
        for nn in NS:                                       # mean dLight of the next n - 1 instances
            Y.append((cda[j + nn] - cda[j + 1]) / (nn - 1))
        for nn in NS:                                       # mean velocity over instances 0 .. n - 1
            Y.append((cvel[j + nn] - cvel[j]) / nn)
        for o in OFFS:                                      # syllable at offset o, its count in 10 from there
            L2 = lab[j + o]
            Y.append(coh[j + o + 10, L2] - coh[j + o, L2])
        out_Y.append(np.stack(Y, 1).astype(float))
        out_x.append(da[j])
        seg = np.searchsorted(SEG, t[j], side="right") - 1
        out_seg.append(seg)
        out_exp.append(np.full(len(j), e))
        out_g.append(list(zip([x.mouse.iloc[0]] * len(j), lab[j], seg)))
    X = np.concatenate(out_x); Y = np.concatenate(out_Y)
    seg = np.concatenate(out_seg); exp = np.concatenate(out_exp)
    keys = pd.Series([f"{a}|{b}|{c}" for a, b, c in sum(out_g, [])])
    gid, uniq = pd.factorize(keys)
    gseg = np.array([int(u.split("|")[2]) for u in uniq])
    return X, Y, gid, gseg, seg, exp

def grouped_r(x, Y, G, Sy, Syy, N):
    Sx = G @ x; Sxx = G @ (x * x)
    Sxy = G @ (x[:, None] * Y)
    num = N[:, None] * Sxy - Sx[:, None] * Sy
    den = np.sqrt((N * Sxx - Sx ** 2)[:, None] * (N[:, None] * Syy - Sy ** 2))
    with np.errstate(invalid="ignore", divide="ignore"):
        return num / den

def seg_mean(R, gseg):
    return np.stack([np.nanmean(R[gseg == s], 0) for s in range(5)])      # 5 segments x K

def fig2e_run(II, nshuf, rng):
    from scipy.sparse import csr_matrix
    X, Y, gid, gseg, seg, exp = fig2e_table(II)
    G = csr_matrix((np.ones(len(X)), (gid, np.arange(len(X)))))
    N = np.asarray(G.sum(1)).ravel()
    Sy = G @ Y; Syy = G @ (Y * Y)
    obs = seg_mean(grouped_r(X, Y, G, Sy, Syy, N), gseg)
    blocks = pd.Series(np.arange(len(X))).groupby([exp, seg]).indices.values()
    sh = np.empty((nshuf,) + obs.shape)
    for s in range(nshuf):
        xp = X.copy()
        for b in blocks:
            xp[b] = X[rng.permutation(b)]
        sh[s] = seg_mean(grouped_r(xp, Y, G, Sy, Syy, N), gseg)
    mu, sd = np.nanmean(sh, 0), np.nanstd(sh, 0)
    zobs = np.nanmean((obs - mu) / sd, 0)                  # z per segment, averaged over segments
    zsh = np.nanmean((sh - mu) / sd, 1)
    return dict(X=X, Y=Y, groups=len(N), n=len(X), zobs=zobs, zsh=zsh, robs=np.nanmean(obs, 0), seg=seg, gid=gid, gseg=gseg, exp=exp)

t0 = time.time()
F2 = fig2e_run(Ic, NSHUF, rng_for("fig2e-dlight-predicts-future-usage"))
print("index instances:", F2["n"], "; mouse-syllable-segment groups:", F2["groups"], "; in", round(time.time() - t0), "s")
print("index instances per segment (0-360, 360-660, 660-900, 900-1680, 1680-1800 s):", np.bincount(F2["seg"], minlength=5).tolist(),
      "; an index instance needs 390 following syllables, so the last segment has none and z is averaged over the others")
K = len(NS)
P_one = (1 + (F2["zsh"] >= F2["zobs"]).sum(0)) / (1 + NSHUF)
P_two = 2 * stats.norm.sf(np.abs((F2["zobs"] - F2["zsh"].mean(0)) / F2["zsh"].std(0)))   # normal approximation
band = np.percentile(np.abs(F2["zsh"]), 95, axis=0)
/tmp/ipykernel_2623/1429096657.py:55: RuntimeWarning: Mean of empty slice
  return np.stack([np.nanmean(R[gseg == s], 0) for s in range(5)])      # 5 segments x K
index instances: 362296 ; mouse-syllable-segment groups: 2072 ; in 68 s
index instances per segment (0-360, 360-660, 660-900, 900-1680, 1680-1800 s): [93013, 79662, 62992, 126629, 0] ; an index instance needs 390 following syllables, so the last segment has none and z is averaged over the others
/tmp/ipykernel_2623/1429096657.py:71: RuntimeWarning: Mean of empty slice
  mu, sd = np.nanmean(sh, 0), np.nanstd(sh, 0)
/home/runner/work/encore/encore/executed/markowitz-2023/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1998: RuntimeWarning: Degrees of freedom <= 0 for slice.
  var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
In [22]:
u = slice(0, K)
tab = pd.DataFrame(dict(n=NS, mean_r=F2["robs"][u], z=F2["zobs"][u], P_one_sided=P_one[u],
                        P_two_sided_holm=M.holm(P_two[u])))
print(tab.round(4).to_string(index=False))
sig = tab.P_one_sided < 0.05
print("significant (one-sided P < 0.05) at n =", NS[sig.to_numpy()].tolist())
print("reading (a), every n up to 390:", bool(sig.all()), "; reading (b), every n up to 210:", bool(sig[NS <= 210].all()),
      "; at n = 10:", bool(sig.iloc[0]))
print("code variant (two-sided, Holm) significant at n =", NS[(tab.P_two_sided_holm < 0.05).to_numpy() & (tab.z > 0).to_numpy()].tolist())
  n  mean_r      z  P_one_sided  P_two_sided_holm
 10  0.0277 6.9964        0.001            0.0000
 30  0.0205 5.1458        0.001            0.0000
 50  0.0174 4.3097        0.001            0.0000
 70  0.0151 3.7727        0.001            0.0000
 90  0.0125 3.1826        0.001            0.0000
110  0.0109 2.7737        0.001            0.0000
130  0.0094 2.3670        0.001            0.0000
150  0.0095 2.4222        0.001            0.0000
170  0.0086 2.2476        0.001            0.0000
190  0.0087 2.2545        0.001            0.0000
210  0.0088 2.2784        0.001            0.0000
230  0.0092 2.3895        0.001            0.0000
250  0.0098 2.5190        0.001            0.0000
270  0.0099 2.5448        0.001            0.0000
290  0.0097 2.5133        0.001            0.0000
310  0.0095 2.4699        0.001            0.0000
330  0.0088 2.2770        0.001            0.0000
350  0.0088 2.2314        0.001            0.0000
370  0.0081 2.0897        0.001            0.0001
390  0.0079 2.0719        0.001            0.0001
significant (one-sided P < 0.05) at n = [10, 30, 50, 70, 90, 110, 130, 150, 170, 190, 210, 230, 250, 270, 290, 310, 330, 350, 370, 390]
reading (a), every n up to 390: True ; reading (b), every n up to 210: True ; at n = 10: True
code variant (two-sided, Holm) significant at n = [10, 30, 50, 70, 90, 110, 130, 150, 170, 190, 210, 230, 250, 270, 290, 310, 330, 350, 370, 390]

Result: reproduced. The correlation between an instance's dLight and later use of the same syllable is significantly positive (one-sided P = 0.001) at every n from 10 to 390 syllables (z from 7.00 at n = 10 to 2.07 at n = 390), and under the code's two-sided Holm-corrected test as well. The last segment has no index instance with 390 following syllables, so z is averaged over four segments.

In [23]:
# Criterion (as amended after the reader's answer): significance one-sided, P < 0.05 against the shuffles, for
# all three curves (Fig. 2e legend); a curve has declined at n when it is not significantly positive there.
ac = slice(K, 2 * K); ve = slice(2 * K, 3 * K)
def fig2e_decide(zobs, zsh):
    p = (1 + (zsh >= zobs).sum(0)) / (1 + len(zsh))
    t = pd.DataFrame(dict(n=NS, z_usage=zobs[u], P_usage=p[u], z_autocorr=zobs[ac], P_autocorr=p[ac],
                          z_velocity=zobs[ve], P_velocity=p[ve]))
    sig_u = t.P_usage < 0.05; pos_a = t.P_autocorr < 0.05; pos_v = t.P_velocity < 0.05
    t["both_declined"] = sig_u & ~pos_a & ~pos_v
    if t.both_declined.any():
        out = "reproduced"
    elif pos_a[sig_u].all() or pos_v[sig_u].all():
        out = "not reproduced"
    else:
        out = "partially reproduced"
    return t, out
tab2, out2 = fig2e_decide(F2["zobs"], F2["zsh"])
print(tab2.round(4).to_string(index=False))
print("n with usage significant and both curves declined:", tab2.n[tab2.both_declined].tolist())
print("autocorrelation significantly positive at n =", tab2.n[tab2.P_autocorr < 0.05].tolist(),
      "; velocity significantly positive at n =", tab2.n[tab2.P_velocity < 0.05].tolist())
print("outcome under the criterion, claim's seed (the shuffles of fig2e-dlight-predicts-future-usage):", out2)
# Seed range: the same shuffles under the seed plus 1000 to 4000
t0 = time.time()
for off in [1000, 2000, 3000, 4000]:
    F2s = fig2e_run(Ic, NSHUF, rng_for("fig2e-dlight-predicts-future-usage", off))
    t_, o_ = fig2e_decide(F2s["zobs"], F2s["zsh"])
    print(f"seed + {off}: {o_}; autocorrelation significantly positive at n = {t_.n[t_.P_autocorr < 0.05].tolist()}; "
          f"velocity not significantly positive at n = {t_.n[t_.P_velocity >= 0.05].tolist()}; velocity P at n = 350 to 390 "
          f"{t_.P_velocity.iloc[-3:].round(3).tolist()}; usage significant at every n: {bool((t_.P_usage < 0.05).all())}")
    del F2s
print("seed range computed in", round(time.time() - t0), "s")
  n  z_usage  P_usage  z_autocorr  P_autocorr  z_velocity  P_velocity  both_declined
 10   6.9964    0.001      5.6273       0.001    -11.7346       1.000          False
 30   5.1458    0.001     -3.6601       1.000      1.2807       0.003          False
 50   4.3097    0.001     -1.1644       0.990      1.8631       0.001          False
 70   3.7727    0.001     -1.7969       1.000      1.9237       0.001          False
 90   3.1826    0.001     -2.0888       1.000      2.1822       0.001          False
110   2.7737    0.001     -2.1200       1.000      1.8495       0.001          False
130   2.3670    0.001     -2.6810       1.000      1.8062       0.001          False
150   2.4222    0.001     -2.9257       1.000      1.6085       0.002          False
170   2.2476    0.001     -3.2650       1.000      1.3302       0.004          False
190   2.2545    0.001     -3.4768       1.000      1.3265       0.006          False
210   2.2784    0.001     -3.5607       1.000      1.3525       0.004          False
230   2.3895    0.001     -3.5391       1.000      1.3910       0.004          False
250   2.5190    0.001     -3.6738       1.000      1.5436       0.001          False
270   2.5448    0.001     -3.8920       1.000      1.4781       0.002          False
290   2.5133    0.001     -4.0920       1.000      1.4202       0.004          False
310   2.4699    0.001     -4.0420       1.000      1.2428       0.012          False
330   2.2770    0.001     -4.1779       1.000      1.1145       0.018          False
350   2.2314    0.001     -4.2937       1.000      1.0574       0.023          False
370   2.0897    0.001     -4.3368       1.000      0.9539       0.028          False
390   2.0719    0.001     -4.2538       1.000      0.8496       0.046          False
n with usage significant and both curves declined: []
autocorrelation significantly positive at n = [10] ; velocity significantly positive at n = [30, 50, 70, 90, 110, 130, 150, 170, 190, 210, 230, 250, 270, 290, 310, 330, 350, 370, 390]
outcome under the criterion, claim's seed (the shuffles of fig2e-dlight-predicts-future-usage): partially reproduced
/tmp/ipykernel_2623/1429096657.py:55: RuntimeWarning: Mean of empty slice
  return np.stack([np.nanmean(R[gseg == s], 0) for s in range(5)])      # 5 segments x K
/tmp/ipykernel_2623/1429096657.py:71: RuntimeWarning: Mean of empty slice
  mu, sd = np.nanmean(sh, 0), np.nanstd(sh, 0)
/home/runner/work/encore/encore/executed/markowitz-2023/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1998: RuntimeWarning: Degrees of freedom <= 0 for slice.
  var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
seed + 1000: partially reproduced; autocorrelation significantly positive at n = [10]; velocity not significantly positive at n = [10]; velocity P at n = 350 to 390 [0.028, 0.034, 0.049]; usage significant at every n: True
seed + 2000: partially reproduced; autocorrelation significantly positive at n = [10]; velocity not significantly positive at n = [10]; velocity P at n = 350 to 390 [0.014, 0.028, 0.038]; usage significant at every n: True
seed + 3000: reproduced; autocorrelation significantly positive at n = [10]; velocity not significantly positive at n = [10, 390]; velocity P at n = 350 to 390 [0.032, 0.049, 0.079]; usage significant at every n: True
seed + 4000: reproduced; autocorrelation significantly positive at n = [10]; velocity not significantly positive at n = [10, 390]; velocity P at n = 350 to 390 [0.027, 0.043, 0.054]; usage significant at every n: True
seed range computed in 276 s

Result: partially reproduced under the claim's seed; the outcome changes with the seed. Under the amended criterion (one-sided tests, a curve declined where it is not significantly positive), the usage correlation is significant at every n from 10 to 390 (P = 0.001). The autocorrelation is significantly positive at n = 10 (z 5.63, P = 0.001) and has declined from n = 30 on (z -1.16 to -4.34, P 0.99 to 1.0). The velocity curve has declined at n = 10 (z -11.73, P = 1.0) and is significantly positive at every n from 30 to 390 (z 0.85 to 2.18, P 0.001 to 0.046). No n has both curves declined, so the reproduced case fails; neither curve is significantly positive at every n, so the not-reproduced case fails, and the criterion's partial case applies. The velocity P at n = 390 is near the threshold: under the seeds plus 1000 and 2000 the outcome is the same (P 0.049 and 0.038 at n = 390), and under the seeds plus 3000 and 4000 the velocity curve is not significant at n = 390 (P 0.079 and 0.054), both curves have declined there and the outcome is reproduced. The reader's answer made the partial case part of the criterion; before it this outcome was a judgment between two cases that did not cover the result.

In [24]:
oo = slice(3 * K, 3 * K + len(OFFS))
P_o = (1 + (F2["zsh"][:, oo] >= F2["zobs"][oo]).sum(0)) / (1 + NSHUF)
tab3 = pd.DataFrame(dict(offset=OFFS, mean_r=F2["robs"][oo], z=F2["zobs"][oo], P_one_sided=P_o, P_holm=M.holm(P_o)))
print(tab3.round(4).to_string(index=False))
z0 = tab3.z[tab3.offset == 0].iloc[0]
others = tab3[tab3.offset != 0]
print("offset 0 significant (Holm):", bool(tab3.P_holm[tab3.offset == 0].iloc[0] < 0.05),
      "; other offsets significant:", others.offset[others.P_holm < 0.05].tolist(),
      "; every other z below half of offset 0's:", bool((others.z < z0 / 2).all()))
# Check of the structural overlap: each offset's 10-syllable window overlaps the index window, and
# neighbouring syllables' counts co-vary with the index syllable's count. Correlation, over index
# instances, of each offset's count with the index syllable's count (offset 0):
Yo = F2["Y"][:, oo]; y0 = Yo[:, list(OFFS).index(0)]
print("r with the offset-0 count:", {int(o): round(float(np.corrcoef(Yo[:, k], y0)[0, 1]), 3) for k, o in enumerate(OFFS) if o != 0})
# Variant: each offset's count with the offset-0 count regressed out (pooled within-group slope),
# tested as above with 200 shuffles (fewer than the main test's 1,000, to keep the run short)
from scipy.sparse import csr_matrix
G_ = csr_matrix((np.ones(F2["n"]), (F2["gid"], np.arange(F2["n"]))))
N_ = np.asarray(G_.sum(1)).ravel()
gm = lambda v: (G_ @ v) / N_
y0d = y0 - gm(y0)[F2["gid"]]
Yr = np.stack([Yo[:, k] - (np.sum((Yo[:, k] - gm(Yo[:, k])[F2["gid"]]) * y0d) / np.sum(y0d ** 2)) * y0
               for k in range(len(OFFS))], 1)
Sy_, Syy_ = G_ @ Yr, G_ @ (Yr * Yr)
obs_r = seg_mean(grouped_r(F2["X"], Yr, G_, Sy_, Syy_, N_), F2["gseg"])
blocks_ = pd.Series(np.arange(F2["n"])).groupby([F2["exp"], F2["seg"]]).indices.values()
rng_r = rng_for("fig2h-specific-to-syllable", 1)
shr = []
for s in range(200):
    xp = F2["X"].copy()
    for b in blocks_:
        xp[b] = F2["X"][rng_r.permutation(b)]
    shr.append(seg_mean(grouped_r(xp, Yr, G_, Sy_, Syy_, N_), F2["gseg"]))
shr = np.array(shr)
mu_, sd_ = np.nanmean(shr, 0), np.nanstd(shr, 0)
zr = np.nanmean((obs_r - mu_) / sd_, 0); zrs = np.nanmean((shr - mu_) / sd_, 1)
pr = (1 + (zrs >= zr).sum(0)) / (1 + len(zrs))
nz = OFFS != 0
print("offset-0 count regressed out: z by offset", dict(zip(OFFS[nz].tolist(), np.round(zr[nz], 2).tolist())),
      "; Holm P over the 10 offsets", dict(zip(OFFS[nz].tolist(), np.round(M.holm(pr[nz]), 3).tolist())))
 offset  mean_r       z  P_one_sided  P_holm
     -5 -0.0105 -2.4671        1.000   1.000
     -4 -0.0108 -2.5761        1.000   1.000
     -3 -0.0138 -3.3450        1.000   1.000
     -2 -0.0067 -1.6347        1.000   1.000
     -1  0.0213  5.2894        0.001   0.011
      0  0.0277  6.9964        0.001   0.011
      1  0.0230  5.4652        0.001   0.011
      2  0.0062  1.4504        0.001   0.011
      3 -0.0050 -1.1285        0.989   1.000
      4 -0.0066 -1.6093        1.000   1.000
      5 -0.0092 -2.2685        1.000   1.000
offset 0 significant (Holm): True ; other offsets significant: [-1, 1, 2] ; every other z below half of offset 0's: False
r with the offset-0 count: {-5: 0.057, -4: 0.067, -3: 0.072, -2: 0.126, -1: 0.103, 1: 0.107, 2: 0.13, 3: 0.073, 4: 0.07, 5: 0.059}
/tmp/ipykernel_2623/1429096657.py:50: RuntimeWarning: invalid value encountered in sqrt
  den = np.sqrt((N * Sxx - Sx ** 2)[:, None] * (N[:, None] * Syy - Sy ** 2))
/tmp/ipykernel_2623/1429096657.py:55: RuntimeWarning: Mean of empty slice
  return np.stack([np.nanmean(R[gseg == s], 0) for s in range(5)])      # 5 segments x K
offset-0 count regressed out: z by offset {-5: -2.74, -4: -2.96, -3: -3.9, -2: -2.51, -1: 4.87, 1: 5.07, 2: 0.66, 3: -1.51, 4: -1.97, 5: -2.71} ; Holm P over the 10 offsets {-5: 1.0, -4: 1.0, -3: 1.0, -2: 1.0, -1: 0.05, 1: 0.05, 2: 0.796, 3: 1.0, 4: 1.0, 5: 1.0}
/home/runner/work/encore/encore/executed/markowitz-2023/.venv/lib/python3.13/site-packages/numpy/_core/fromnumeric.py:83: RuntimeWarning: invalid value encountered in reduce
  return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
/tmp/ipykernel_2623/2589814188.py:35: RuntimeWarning: Mean of empty slice
  mu_, sd_ = np.nanmean(shr, 0), np.nanstd(shr, 0)
/home/runner/work/encore/encore/executed/markowitz-2023/.venv/lib/python3.13/site-packages/numpy/lib/_nanfunctions_impl.py:1998: RuntimeWarning: Degrees of freedom <= 0 for slice.
  var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
/tmp/ipykernel_2623/2589814188.py:36: RuntimeWarning: Mean of empty slice
  zr = np.nanmean((obs_r - mu_) / sd_, 0); zrs = np.nanmean((shr - mu_) / sd_, 1)

Result: not reproduced. Offset 0 is significant (z = 7.00, Holm P = 0.011), but so are offsets -1 (z = 5.29), +1 (z = 5.47) and +2 (z = 1.45, Holm P = 0.011), and the z of -1 and +1 exceed half of offset 0's. The counts at -1 and +1 correlate with the offset-0 count at r = 0.10 and 0.11, and with it regressed out their z stay at 4.87 and 5.07, so the overlap of the windows does not account for them; with the 200 shuffles of that check their Holm P is 0.05, the smallest that test can give.

fig2k-dlight-predicts-sequence-variability¶

"A higher-amplitude dopamine transient at a syllable instance is followed by less predictable syllable choices over the next several seconds."

Method (claims file, as amended after the reader's answer; the details it leaves to the code are taken from dlight_06 and the fig_2k notebook at commit 14ed714): every DLS index instance (offline labels, code reading of the baseline set) with 49 following syllables in its experiment; for n = 5 and 10, the transitions among the n syllables starting at the index instance (get_syllable_sequence_stats), restricted to the 37 syllables (the code truncates the matrix to them). Instances are binned by their syllable-associated dLight into 20 bins, (a) equally spaced per mouse and syllable (Methods), (b) equal-count per mouse with syllables pooled (dlight_06, cell 31). Counts are summed per mouse, segment and bin, and groups with more than 100 transitions are kept. Entropy is the code's dm_entropy with the Perks prior and rows normalised, which is the mean row entropy of the 37 x 37 matrix plus a constant. The dLight bin is correlated with entropy over mice and bins per segment and n (Spearman as the code; Pearson as the Methods). The criterion's null is the Methods' ("Pearson coefficients estimated after shuffling dLight peak values"): 1,000 shuffles of the index instances' dLight values within mouse and segment, before binning, with the bins formed and the transitions counted again for each. Each correlation is z-scored against the shuffles per segment and averaged over segments; one-sided P from the shuffles' segment-averaged z. The seed range uses 200 shuffles under each of the seeds plus 1000 to 4000. The code's null (randomize_cols, destinations permuted within each row of every experiment-level matrix) is a variant with 200 shuffles. Only n = 5 and 10 are run, where the criterion decides.

In [25]:
NK = np.arange(5, 51, 5)
K37 = len(SYL37)
LUT37 = np.full(int(Ic.label.max()) + 1, -1); LUT37[SYL37] = np.arange(K37)

def fig2k_prepare(II, reading):
    """Index instances with 49 following syllables: dLight bin and segment."""
    J = []
    for e, x in II.groupby("exp", sort=False):
        n = len(x)
        j = np.arange(0, n - NK.max() + 1)
        t = x.onset.to_numpy() - x.onset.to_numpy()[0]
        J.append(pd.DataFrame(dict(exp=e, mouse=x.mouse.iloc[0], label=x.label.to_numpy()[j], da=x.da.to_numpy()[j],
                                   seg=np.searchsorted(SEG, t[j], side="right") - 1, j=j)))
    return fig2k_bin(pd.concat(J, ignore_index=True), reading)

def fig2k_bin(J, reading):
    if reading == "b":
        J["dbin"] = J.groupby("mouse").da.transform(lambda v: pd.qcut(v, 20, labels=False, duplicates="drop"))
    else:
        J["dbin"] = J.groupby(["mouse", "label"]).da.transform(lambda v: pd.cut(v, 20, labels=False))
    J = J.dropna(subset=["dbin"]).reset_index(drop=True)
    J["dbin"] = J.dbin.astype(int)
    return J

def fig2k_counts(II, J, nmax=NK.max()):
    """Transition counts (sparse) per experiment, segment and dLight bin, for each n up to `nmax`."""
    labs = {e: LUT37[x.label.to_numpy()] for e, x in II.groupby("exp", sort=False)}
    pre_key = J.groupby(["exp", "seg", "dbin"], sort=False).ngroup().to_numpy()
    fin_tab = pd.DataFrame(dict(pre=pre_key, mouse=J.mouse, seg=J.seg, dbin=J.dbin)).drop_duplicates("pre").sort_values("pre")
    fin_key = fin_tab.groupby(["mouse", "seg", "dbin"], sort=False).ngroup().to_numpy()
    fin_uniq = fin_tab.assign(f=fin_key).drop_duplicates("f").sort_values("f")[["mouse", "seg", "dbin"]].reset_index(drop=True)
    G = pre_key.max() + 1
    order = list(J.groupby("exp", sort=False).indices.items())
    pk = np.concatenate([pre_key[ix] for _, ix in order])
    out = {}
    acc = np.zeros(G * K37 * K37, np.int64)
    for k in range(nmax - 1):
        a = np.concatenate([labs[e][J.j.to_numpy()[ix] + k] for e, ix in order])
        b = np.concatenate([labs[e][J.j.to_numpy()[ix] + k + 1] for e, ix in order])
        ok = (a >= 0) & (b >= 0)
        acc += np.bincount((pk[ok] * K37 + a[ok]) * K37 + b[ok], minlength=G * K37 * K37)
        if k + 2 in NK:                                   # n syllables hold n - 1 transitions
            nz = np.flatnonzero(acc)
            out[k + 2] = (nz, acc[nz].copy())
    return dict(cnt=out, fin_key=fin_key, fin_uniq=fin_uniq, G=G)

def row_entropy_mean(C):
    a = 1.0 / (K37 * K37)                                 # Perks prior, 1 / tm.size
    P = (C + a) / (C.sum(-1, keepdims=True) + K37 * a)
    return -(P * np.log2(P)).sum(-1).mean(-1)

def fig2k_stat(D, n, seed=None):
    nz, val = D["cnt"][n]
    pre = nz // (K37 * K37); r = (nz // K37) % K37; c = nz % K37
    if seed is not None:                                  # destinations permuted within each row
        perm = np.random.default_rng(seed).permuted(np.tile(np.arange(K37), (D["G"] * K37, 1)), axis=1)
        c = perm[pre * K37 + r, c]
    F = len(D["fin_uniq"])
    Mx = np.bincount((D["fin_key"][pre] * K37 + r) * K37 + c, weights=val, minlength=F * K37 * K37).reshape(F, K37, K37)
    fu = D["fin_uniq"].assign(H=row_entropy_mean(Mx), tot=Mx.sum((1, 2)))
    fu = fu[fu.tot > 100]
    return np.array([[g.dbin.corr(g.H, method=meth) if len(g) > 2 else np.nan for s in range(5)
                      for g in [fu[fu.seg == s]]] for meth in ["spearman", "pearson"]]), len(fu)

def _f2k_job(args):
    D, n, seeds = args
    return [fig2k_stat(FK[D], n, s)[0] for s in seeds]

def fig2k_run(D, n, rng, nshuf, procs=4):
    """Observed statistic and `nshuf` shuffles (each with a seed drawn from the claim's generator)."""
    from multiprocessing import get_context
    obs, nf = fig2k_stat(FK[D], n)
    seeds = [int(x) for x in rng.integers(0, 2**63 - 1, nshuf)]
    chunks = [(D, n, seeds[k::procs]) for k in range(procs)]
    with get_context("fork").Pool(procs) as p:
        sh = np.concatenate([np.array(x) for x in p.map(_f2k_job, chunks)])      # nshuf x 2 x 5
    mu, sd = np.nanmean(sh, 0), np.nanstd(sh, 0)
    z = np.nanmean((obs - mu) / sd, -1)                   # per method, averaged over segments
    zs = np.nanmean((sh - mu) / sd, -1)
    p = (1 + (zs >= z).sum(0)) / (1 + nshuf)
    return dict(n=n, groups=nf, rho=np.nanmean(obs[0]), r=np.nanmean(obs[1]), z_spearman=z[0], z_pearson=z[1],
                P_spearman=p[0], P_pearson=p[1])

def fig2k_dbin(da, rd):
    """dLight bins of the rows of J0 for dLight values `da`, as fig2k_bin forms them (pd.qcut per mouse for
    reading (b), pd.cut per mouse and syllable for (a)), computed with numpy for speed in the shuffles;
    checked below to give the same bins as fig2k_bin."""
    out = np.empty(len(da), np.int64)
    for ix in (GI_b if rd == "b" else GI_a):
        v = da[ix]
        if rd == "b":
            e = np.unique(np.quantile(v, np.linspace(0, 1, 21)))
            out[ix] = np.maximum(e.searchsorted(v, "left") - 1, 0)
        else:
            mn, mx = v.min(), v.max()
            e = np.linspace(mn, mx, 21); e[0] -= (mx - mn) * 0.001
            out[ix] = e.searchsorted(v, "left") - 1
    return out

def fig2k_mouse_counts(da, rd, nmax):
    """Transition counts per mouse, segment and dLight bin, with the instances binned under reading `rd`.
    Used for the null of shuffled dLight values; summing over experiments first, as fig2k_counts does,
    gives the same counts (checked below on the observed data)."""
    code = (MCODE * 5 + J0.seg.to_numpy()) * 20 + fig2k_dbin(da, rd)
    uniq, key = np.unique(code, return_inverse=True)
    fu = pd.DataFrame(dict(seg=(uniq // 20) % 5, dbin=uniq % 20))
    F = len(fu)
    acc = np.zeros(F * K37 * K37, np.int64); out = {}
    for k in range(nmax - 1):
        a = AK[k]; b = AK[k + 1]; ok = (a >= 0) & (b >= 0)
        acc += np.bincount((key[ok] * K37 + a[ok]) * K37 + b[ok], minlength=F * K37 * K37)
        if k + 2 in NK:
            out[k + 2] = acc.reshape(F, K37, K37).copy()
    return out, fu

def fig2k_mouse_stat(Mx, fu):
    fu = fu.assign(H=row_entropy_mean(Mx), tot=Mx.sum((1, 2)))
    fu = fu[fu.tot > 100]
    return np.array([[g.dbin.corr(g.H, method=meth) if len(g) > 2 else np.nan for s in range(5)
                      for g in [fu[fu.seg == s]]] for meth in ["spearman", "pearson"]])

def _f2k_dnull_job(args):
    """Shuffles of the Methods' null: dLight peak values permuted among the index instances of each mouse
    and segment, before binning; the bins are formed again and the transitions counted again."""
    rd, n_list, seeds = args
    out = []
    for s in seeds:
        r_ = np.random.default_rng(s)
        perm = np.lexsort((r_.random(len(J0)), GRP))     # a random order within each mouse and segment
        da = np.empty_like(DA0); da[GSRT] = DA0[perm]
        cnt, fu = fig2k_mouse_counts(da, rd, max(n_list))
        out.append([fig2k_mouse_stat(cnt[n], fu) for n in n_list])
    return out

def fig2k_dnull(rd, rng, nshuf, n_list=(5, 10), procs=4):
    from multiprocessing import get_context
    seeds = [int(x) for x in rng.integers(0, 2**63 - 1, nshuf)]
    with get_context("fork").Pool(procs) as p:
        sh = np.concatenate([np.array(x) for x in p.map(_f2k_dnull_job, [(rd, list(n_list), seeds[q::procs]) for q in range(procs)])])
    cnt, fu = fig2k_mouse_counts(DA0, rd, max(n_list))
    rows_ = []
    for q, n in enumerate(n_list):
        obs = fig2k_mouse_stat(cnt[n], fu)
        mu, sd = np.nanmean(sh[:, q], 0), np.nanstd(sh[:, q], 0)
        z = np.nanmean((obs - mu) / sd, -1); zs = np.nanmean((sh[:, q] - mu) / sd, -1)
        p_pos = (1 + (zs >= z).sum(0)) / (1 + nshuf); p_neg = (1 + (zs <= z).sum(0)) / (1 + nshuf)
        rows_.append(dict(reading=rd, n=n, nshuf=nshuf, rho=np.nanmean(obs[0]), r=np.nanmean(obs[1]),
                          null_r_mean=np.nanmean(sh[:, q, 1]), z_spearman=z[0], z_pearson=z[1],
                          P_spearman=p_pos[0], P_pearson=p_pos[1], P_negative_spearman=p_neg[0], P_negative_pearson=p_neg[1]))
    return rows_

t0 = time.time()
FK = {}
for rd in ["b", "a"]:
    J_ = fig2k_prepare(Ic, rd)
    FK[rd] = fig2k_counts(Ic, J_, 10)                  # n = 5 and 10, where the criterion decides
    print(f"reading ({rd}): {len(J_)} index instances, {J_.mouse.nunique()} mice, {FK[rd]['G']} experiment-segment-bin groups, "
          f"{len(FK[rd]['fin_uniq'])} mouse-segment-bin groups; dLight bins per mouse {J_.groupby('mouse').dbin.nunique().min()} to {J_.groupby('mouse').dbin.nunique().max()}")
J0 = fig2k_prepare(Ic, "b")[["exp", "mouse", "label", "da", "seg", "j"]].copy()
DA0 = J0.da.to_numpy(); assert np.isfinite(DA0).all()
MCODE = pd.factorize(J0.mouse)[0]
GI_b = list(J0.groupby("mouse").indices.values()); GI_a = list(J0.groupby(["mouse", "label"]).indices.values())
# the label of the k-th syllable after each index instance, k = 0 .. 9, in the rows of J0
_labs = {e: LUT37[x.label.to_numpy()] for e, x in Ic.groupby("exp", sort=False)}
_off = dict(zip(_labs, np.cumsum([0] + [len(v) for v in _labs.values()])[:-1]))
_base = J0.exp.map(_off).to_numpy() + J0.j.to_numpy()
_lall = np.concatenate(list(_labs.values()))
AK = [_lall[_base + k] for k in range(10)]
GRP = J0.groupby(["mouse", "seg"]).ngroup().to_numpy(); GSRT = np.argsort(GRP, kind="stable")
print("mouse and segment groups within which dLight values are shuffled:", GRP.max() + 1)
_shuf = DA0[rng_for("fig2k-dlight-predicts-sequence-variability", 4).permutation(len(DA0))]
for rd in ["b", "a"]:
    same = [np.array_equal(fig2k_bin(J0.assign(da=x), rd).dbin.to_numpy(), fig2k_dbin(x, rd)) for x in [DA0, _shuf]]
    print(f"reading ({rd}): numpy bins equal to fig2k_bin's on the observed values and on one shuffle: {same}")
    assert all(same)
    cnt, fu = fig2k_mouse_counts(DA0, rd, 10)
    dev = max(np.nanmax(np.abs(fig2k_mouse_stat(cnt[n], fu) - fig2k_stat(FK[rd], n)[0])) for n in [5, 10])
    print(f"reading ({rd}): largest difference between the mouse-level and experiment-level counts' correlations at n = 5 and 10: {dev:.2e}")
# The criterion's null (Methods): 1,000 shuffles of the dLight peak values within mouse and segment, n = 5 and 10,
# where the criterion decides. Seed range: the same with 200 shuffles under the seeds plus 1000 to 4000.
K2 = pd.DataFrame(fig2k_dnull("b", rng_for("fig2k-dlight-predicts-sequence-variability"), NSHUF) +
                  fig2k_dnull("a", rng_for("fig2k-dlight-predicts-sequence-variability", 1), NSHUF))
print("criterion's null computed in", round(time.time() - t0), "s")
t0 = time.time()
K2S = pd.DataFrame([dict(seed_offset=off, **row_) for off in [1000, 2000, 3000, 4000] for rd, k in [("b", 0), ("a", 1)]
                    for row_ in fig2k_dnull(rd, rng_for("fig2k-dlight-predicts-sequence-variability", k + off), 200)])
print("seed range (200 shuffles each) computed in", round(time.time() - t0), "s")
reading (b): 464570 index instances, 14 mice, 13529 experiment-segment-bin groups, 1278 mouse-segment-bin groups; dLight bins per mouse 20 to 20
reading (a): 464570 index instances, 14 mice, 12930 experiment-segment-bin groups, 1261 mouse-segment-bin groups; dLight bins per mouse 20 to 20
mouse and segment groups within which dLight values are shuffled: 64
reading (b): numpy bins equal to fig2k_bin's on the observed values and on one shuffle: [True, True]
reading (b): largest difference between the mouse-level and experiment-level counts' correlations at n = 5 and 10: 5.55e-17
reading (a): numpy bins equal to fig2k_bin's on the observed values and on one shuffle: [True, True]
reading (a): largest difference between the mouse-level and experiment-level counts' correlations at n = 5 and 10: 2.22e-16
criterion's null computed in 190 s
seed range (200 shuffles each) computed in 149 s
In [26]:
print("criterion's null, dLight peak values shuffled within mouse and segment,", NSHUF, "shuffles:")
print(K2.round(4).to_string(index=False))
for rd in ["b", "a"]:
    for meth in ["spearman", "pearson"]:
        k_ = K2[K2.reading == rd].set_index("n")
        ok5_10 = bool((k_.loc[[5, 10], f"P_{meth}"] < 0.05).all() and (k_.loc[[5, 10], f"z_{meth}"] > 0).all())
        print(f"reading ({rd}), {meth}: significantly positive at n = 5 and 10: {ok5_10}")
print("seed range, seeds plus 1000 to 4000, 200 shuffles each:")
print(K2S[["seed_offset", "reading", "n", "z_spearman", "z_pearson", "P_spearman", "P_pearson", "P_negative_pearson"]].round(4).to_string(index=False))
for rd in ["b", "a"]:
    for meth in ["spearman", "pearson"]:
        g_ = K2S[K2S.reading == rd]
        print(f"reading ({rd}), {meth}: z {g_[f'z_{meth}'].min():.2f} to {g_[f'z_{meth}'].max():.2f}, one-sided P {g_[f'P_{meth}'].min():.3f} to {g_[f'P_{meth}'].max():.3f}; "
              f"significantly positive at n = 5 and 10 under {sum(bool((gg[f'P_{meth}'] < 0.05).all()) for _, gg in g_.groupby('seed_offset'))} of 4 seeds")
criterion's null, dLight peak values shuffled within mouse and segment, 1000 shuffles:
reading  n  nshuf     rho       r  null_r_mean  z_spearman  z_pearson  P_spearman  P_pearson  P_negative_spearman  P_negative_pearson
      b  5   1000 -0.0759 -0.0641      -0.0183     -2.2679    -2.4539       1.000      1.000                0.001               0.001
      b 10   1000 -0.0536 -0.0558      -0.0353     -1.4709    -1.5697       0.997      0.999                0.004               0.002
      a  5   1000 -0.3571 -0.3795      -0.4274      1.2117     1.2430       0.006      0.003                0.995               0.998
      a 10   1000 -0.4613 -0.5172      -0.5541      2.1134     1.9315       0.001      0.001                1.000               1.000
reading (b), spearman: significantly positive at n = 5 and 10: False
reading (b), pearson: significantly positive at n = 5 and 10: False
reading (a), spearman: significantly positive at n = 5 and 10: True
reading (a), pearson: significantly positive at n = 5 and 10: True
seed range, seeds plus 1000 to 4000, 200 shuffles each:
 seed_offset reading  n  z_spearman  z_pearson  P_spearman  P_pearson  P_negative_pearson
        1000       b  5     -2.3074    -2.5010      1.0000     1.0000              0.0050
        1000       b 10     -1.5460    -1.6254      1.0000     1.0000              0.0050
        1000       a  5      1.1391     1.1541      0.0050     0.0100              0.9950
        1000       a 10      2.0715     1.9144      0.0050     0.0050              1.0000
        2000       b  5     -2.1487    -2.3195      1.0000     1.0000              0.0050
        2000       b 10     -1.5551    -1.6033      1.0000     1.0000              0.0050
        2000       a  5      1.1150     1.1567      0.0050     0.0050              1.0000
        2000       a 10      2.1278     1.9450      0.0050     0.0050              1.0000
        3000       b  5     -2.1826    -2.3920      1.0000     1.0000              0.0050
        3000       b 10     -1.4774    -1.6105      1.0000     1.0000              0.0050
        3000       a  5      1.2793     1.3153      0.0100     0.0100              0.9950
        3000       a 10      2.1429     1.9613      0.0050     0.0050              1.0000
        4000       b  5     -2.3269    -2.5438      1.0000     1.0000              0.0050
        4000       b 10     -1.5174    -1.6462      1.0000     1.0000              0.0050
        4000       a  5      1.0758     1.1099      0.0149     0.0199              0.9851
        4000       a 10      2.1622     1.9481      0.0050     0.0050              1.0000
reading (b), spearman: z -2.33 to -1.48, one-sided P 1.000 to 1.000; significantly positive at n = 5 and 10 under 0 of 4 seeds
reading (b), pearson: z -2.54 to -1.60, one-sided P 1.000 to 1.000; significantly positive at n = 5 and 10 under 0 of 4 seeds
reading (a), spearman: z 1.08 to 2.16, one-sided P 0.005 to 0.015; significantly positive at n = 5 and 10 under 4 of 4 seeds
reading (a), pearson: z 1.11 to 1.96, one-sided P 0.005 to 0.020; significantly positive at n = 5 and 10 under 4 of 4 seeds
In [27]:
# Variant: the code's null (dlight_06, randomize_cols), destinations permuted within each row of every
# experiment-level transition matrix; n = 5 and 10, 200 shuffles per reading to keep the run short.
t0 = time.time()
K2C = pd.DataFrame([dict(reading=rd, nshuf=200, **fig2k_run(rd, n, rng_for("fig2k-dlight-predicts-sequence-variability", k), 200))
                    for rd, k in [("b", 2), ("a", 3)] for n in [5, 10]])
print("variant, the code's null (randomize_cols), 200 shuffles, computed in", round(time.time() - t0), "s")
print(K2C.round(4).to_string(index=False))
variant, the code's null (randomize_cols), 200 shuffles, computed in 80 s
reading  nshuf  n  groups     rho       r  z_spearman  z_pearson  P_spearman  P_pearson
      b    200  5    1135 -0.0759 -0.0641      2.4078     2.9897       0.005      0.005
      b    200 10    1167 -0.0536 -0.0558      3.5092     3.0216       0.005      0.005
      a    200  5     962 -0.3571 -0.3795      3.7304     6.0173       0.005      0.005
      a    200 10    1120 -0.4613 -0.5172      5.0724     4.2043       0.005      0.005

Result: reproduced under reading (a); reading (b) goes the other way. Against the amended criterion's null, dLight values shuffled within mouse and segment (1,000 shuffles), the correlation of the dLight bin with the entropy of the following transitions is significantly positive at n = 5 and 10 under reading (a), the Methods' bins per mouse and syllable (Pearson z 1.24 and 1.93, one-sided P = 0.003 and 0.001; Spearman z 1.21 and 2.11, P = 0.006 and 0.001), and stays so under all four other seeds (Pearson P 0.005 to 0.020, 200 shuffles each). Under reading (b), the code's equal-count bins per mouse, it is significantly negative (Pearson z -2.45 and -1.57, P = 0.001 and 0.002 for a negative correlation), under all five seeds. The criterion takes a result under either reading, so the claim is reproduced. The raw correlations are negative under both readings (Pearson -0.380 and -0.517 under (a), -0.064 and -0.056 under (b)); under (a) they are less negative than the shuffles' mean (-0.427 and -0.554), which is what the positive z measures. Against the code's null, now a variant (200 shuffles), both readings are significantly positive (Pearson z 2.99 to 6.02, P = 0.005 each). The reader's answer changed the null from the code's to the Methods'; the outcome is the same as before it, now resting on reading (a) alone.

fig1e-velocity-timescales¶

In [28]:
BS = np.arange(0.25, 59.76, 0.5)
def exp_z_noslide(i):
    """Variant: the re-referenced dLight z-scored over the whole experiment, without the 20-s sliding window."""
    z = SESS[i]["rr"].astype(float)
    return (z - np.nanmean(z)) / np.nanstd(z)

def fig1e_exp(i, thr, BS=BS, zfun=None):
    z = (zfun or exp_z)(i); v = SESS[i]["speed"].astype(float)
    t = np.arange(len(z)) / M.FS
    cross = np.r_[False, (z[:-1] < thr) & (z[1:] >= thr)].astype(float)
    out = []
    for bs in BS:
        b = np.floor(t / bs).astype(int)
        cnt = np.bincount(b)
        mode = np.bincount(cnt[cnt > 0]).argmax()
        keep = cnt[b] == mode
        bb = b[keep]
        n = np.bincount(bb)
        ok = n > 0
        out.append((np.bincount(bb, z[keep])[ok] / n[ok], np.bincount(bb, cross[keep])[ok] / bs,
                    np.bincount(bb, v[keep])[ok] / n[ok]))
    return out

def zs1(a):
    return (a - a.mean()) / a.std()

def fig1e_run(thr, rng, nshuf, BS=BS, zfun=None, kinds=("amp", "rate")):
    mice = sorted(DLS.mouse.unique())
    R = {k: np.full((len(DLS), len(BS)), np.nan) for k in kinds}
    SHR = {k: np.zeros((nshuf, len(mice), len(BS))) for k in kinds}
    cnt = {k: np.zeros((len(mice), len(BS))) for k in kinds}   # experiments entering each mouse's mean
    for e, (_, r) in enumerate(DLS.iterrows()):
        mi = mice.index(r.mouse)
        for b, (amp, rate, v) in enumerate(fig1e_exp(r.i, thr, BS, zfun)):
            zv = zs1(v)
            for k, x in [("amp", amp), ("rate", rate)]:
                if k not in kinds or x.std() == 0 or len(x) < 3:
                    continue
                zx = zs1(x)
                R[k][e, b] = np.mean(zx * zv)
                cnt[k][mi, b] += 1
                P = rng.permuted(np.tile(zx, (nshuf, 1)), axis=1)
                SHR[k][:, mi, b] += P @ zv / len(zv)
    out = {}
    for k in kinds:
        per_mouse = pd.DataFrame(R[k]).groupby(DLS.mouse.to_numpy()).mean()
        obs = per_mouse.mean(0).to_numpy()
        with np.errstate(invalid="ignore"):
            sh = np.nanmean(SHR[k] / cnt[k][None], 1)
        out[k] = (obs, sh)
        out[k + "_skipped"] = int(len(DLS) * len(BS) - cnt[k].sum())
    return out

t0 = time.time()
FE = {thr: fig1e_run(thr, rng_for("fig1e-velocity-timescales", j), NSHUF) for j, thr in enumerate([1.96, 1.0])}
print("computed in", round(time.time() - t0), "s;", len(DLS), "experiments,", DLS.mouse.nunique(), "mice;", len(BS), "bin sizes")
print("experiment-bin size pairs left out for zero s.d.:", {f"{thr}/{k}": FE[thr][k + "_skipped"] for thr in FE for k in ["amp", "rate"]})
def verdict(obs, sh, BS=BS):
    lo, hi = np.percentile(sh, [2.5, 97.5], axis=0)
    neg_a = obs < lo; pos_a = obs > hi
    # two-sided P from the z of the observed mean r against the shuffles (normal approximation: with
    # 1,000 shuffles an empirical P cannot pass Holm over 120 bin sizes)
    p2 = 2 * stats.norm.sf(np.abs((obs - sh.mean(0)) / sh.std(0)))
    ph = M.holm(p2) < 0.05
    run = np.zeros(len(ph), bool)                     # only runs of 5 or more consecutive bin sizes
    k = 0
    while k < len(ph):
        if ph[k]:
            j = k
            while j < len(ph) and ph[j]:
                j += 1
            if j - k >= 5:
                run[k:j] = True
            k = j
        else:
            k += 1
    short, long_ = BS < 10, BS >= 10
    res = {}
    for name, sig in [("(a) legend, P < 0.05 per bin size", None), ("(b) code, Holm, runs of 5", run)]:
        neg = neg_a if sig is None else (sig & (obs < 0))
        pos = pos_a if sig is None else (sig & (obs > 0))
        holds = bool(neg[short].any() and not pos[short].any() and pos[long_].any())
        res[name] = holds
        print(f"   {name}: significantly negative at {neg[short].sum()} of {short.sum()} bin sizes < 10 s, "
              f"positive at {pos[short].sum()} of them; significantly positive at {pos[long_].sum()} of {long_.sum()} bin sizes >= 10 s -> {holds}")
    return res
for thr in FE:
    for k in ["amp", "rate"]:
        obs, sh = FE[thr][k]
        if k == "amp" and thr == 1.0:
            continue
        print(f"{'amplitude' if k == 'amp' else f'transient rate, threshold {thr}'}: mean r at 0.25 s {obs[0]:.3f}, 5.25 s {obs[10]:.3f}, "
              f"9.75 s {obs[19]:.3f}, 20.25 s {obs[40]:.3f}, 59.75 s {obs[-1]:.3f}; sign change near {BS[np.flatnonzero(np.diff(np.sign(obs)))].round(2).tolist()} s")
        verdict(obs, sh)
# Variant: bin sizes cast to whole seconds, as the code does (pairs of bin sizes pooled; 0.25 s and
# 0.75 s become 0 and are left out); the 59 distinct sizes from 1 to 59 s.
BSI = np.arange(1.0, 60.0)
FEI = fig1e_run(1.96, rng_for("fig1e-velocity-timescales", 2), NSHUF, BS=BSI)
for k in ["amp", "rate"]:
    obs, sh = FEI[k]
    print(f"integer bin sizes, {'amplitude' if k == 'amp' else 'transient rate, threshold 1.96'}: mean r at 1 s {obs[0]:.3f}, "
          f"5 s {obs[4]:.3f}, 9 s {obs[8]:.3f}, 20 s {obs[19]:.3f}, 59 s {obs[-1]:.3f}")
    verdict(obs, sh, BSI)
# Variant: without the 20-s sliding z-score of the Methods' pre-processing, which removes slow variation;
# the re-referenced dLight z-scored over the whole experiment.
FEN = fig1e_run(1.96, rng_for("fig1e-velocity-timescales", 3), NSHUF, zfun=exp_z_noslide)
for k in ["amp", "rate"]:
    obs, sh = FEN[k]
    print(f"no sliding window, {'amplitude' if k == 'amp' else 'transient rate, threshold 1.96'}: mean r at 0.25 s {obs[0]:.3f}, "
          f"5.25 s {obs[10]:.3f}, 9.75 s {obs[19]:.3f}, 20.25 s {obs[40]:.3f}, 59.75 s {obs[-1]:.3f}")
    verdict(obs, sh)
fig, ax = plt.subplots(figsize=(5, 3))
for thr, k, lab_ in [(1.96, "amp", "amplitude"), (1.96, "rate", "rate (1.96)"), (1.0, "rate", "rate (1 s.d.)")]:
    ax.plot(BS, FE[thr][k][0], label=lab_)
ax.axhline(0, c="0.5", ls=":"); ax.set_xlabel("bin size (s)"); ax.set_ylabel("mean r with velocity"); ax.legend(fontsize=7)
plt.tight_layout(); plt.show()
/tmp/ipykernel_2623/3819471214.py:47: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  obs = per_mouse.mean(0).to_numpy()
/tmp/ipykernel_2623/3819471214.py:47: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  obs = per_mouse.mean(0).to_numpy()
computed in 139 s; 164 experiments, 14 mice; 120 bin sizes
experiment-bin size pairs left out for zero s.d.: {'1.96/amp': 0, '1.96/rate': 0, '1.0/amp': 0, '1.0/rate': 0}
amplitude: mean r at 0.25 s -0.119, 5.25 s -0.205, 9.75 s -0.187, 20.25 s -0.150, 59.75 s -0.051; sign change near [] s
   (a) legend, P < 0.05 per bin size: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 100 bin sizes >= 10 s -> False
   (b) code, Holm, runs of 5: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 100 bin sizes >= 10 s -> False
transient rate, threshold 1.96: mean r at 0.25 s -0.064, 5.25 s -0.115, 9.75 s -0.069, 20.25 s 0.010, 59.75 s 0.111; sign change near [15.75, 16.25, 17.75] s
   (a) legend, P < 0.05 per bin size: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 73 of 100 bin sizes >= 10 s -> True
   (b) code, Holm, runs of 5: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 27 of 100 bin sizes >= 10 s -> True
transient rate, threshold 1.0: mean r at 0.25 s -0.061, 5.25 s -0.129, 9.75 s -0.086, 20.25 s -0.042, 59.75 s -0.013; sign change near [35.75, 36.25, 38.75, 39.25, 56.25, 57.25] s
   (a) legend, P < 0.05 per bin size: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 100 bin sizes >= 10 s -> False
   (b) code, Holm, runs of 5: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 100 bin sizes >= 10 s -> False
/tmp/ipykernel_2623/3819471214.py:47: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  obs = per_mouse.mean(0).to_numpy()
integer bin sizes, amplitude: mean r at 1 s -0.156, 5 s -0.205, 9 s -0.203, 20 s -0.148, 59 s -0.075
   (a) legend, P < 0.05 per bin size: significantly negative at 9 of 9 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 50 bin sizes >= 10 s -> False
   (b) code, Holm, runs of 5: significantly negative at 9 of 9 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 50 bin sizes >= 10 s -> False
integer bin sizes, transient rate, threshold 1.96: mean r at 1 s -0.104, 5 s -0.115, 9 s -0.088, 20 s 0.010, 59 s 0.078
   (a) legend, P < 0.05 per bin size: significantly negative at 9 of 9 bin sizes < 10 s, positive at 0 of them; significantly positive at 38 of 50 bin sizes >= 10 s -> True
   (b) code, Holm, runs of 5: significantly negative at 9 of 9 bin sizes < 10 s, positive at 0 of them; significantly positive at 36 of 50 bin sizes >= 10 s -> True
no sliding window, amplitude: mean r at 0.25 s -0.135, 5.25 s -0.294, 9.75 s -0.313, 20.25 s -0.319, 59.75 s -0.274
   (a) legend, P < 0.05 per bin size: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 100 bin sizes >= 10 s -> False
   (b) code, Holm, runs of 5: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 100 bin sizes >= 10 s -> False
no sliding window, transient rate, threshold 1.96: mean r at 0.25 s -0.073, 5.25 s -0.206, 9.75 s -0.214, 20.25 s -0.215, 59.75 s -0.166
   (a) legend, P < 0.05 per bin size: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 100 bin sizes >= 10 s -> False
   (b) code, Holm, runs of 5: significantly negative at 20 of 20 bin sizes < 10 s, positive at 0 of them; significantly positive at 0 of 100 bin sizes >= 10 s -> False
/tmp/ipykernel_2623/3819471214.py:47: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  obs = per_mouse.mean(0).to_numpy()
No description has been provided for this image

Result: partially reproduced. The transient rate (upward crossings of 1.96) holds under both readings of significance: significantly negative at all 20 bin sizes below 10 s and significantly positive at 73 (legend's test) or 27 (code's test) of 100 bin sizes of 10 s or more, with the sign changing near 16 s; also with integer bin sizes (38 or 36 of 50). The binned amplitude is negative at every bin size (from -0.205 at 5.25 s to -0.051 at 59.75 s) and never significantly positive, as is the 1-s.d. rate. Without the 20-s sliding z-score neither measure is significantly positive at any bin size (amplitude -0.274 and rate -0.166 at 59.75 s), so the window does not hide a positive amplitude correlation.

fig2g-usage-crosscorrelation¶

In [29]:
def fig2g_run(step, rng, nshuf, circular=False):
    """3-min windows (non-overlapping, or sliding by `step` s); per syllable and experiment mean
    syllable-associated dLight and count per window, correlated at lags; averaged over syllables and
    experiments; null from dLight permuted across windows within experiment and syllable, or, with
    `circular`, the window series of dLight shifted circularly by a random number of windows, which
    keeps its autocorrelation. P is given at the peak lag and against the shuffles' maximum z over lags."""
    W = 180.0
    lags_s = np.arange(-450, 451, 30) if step < W else np.arange(-2, 3) * 180.0   # within +-7.5 min
    obs_acc, sh_acc, n_acc = 0, 0, 0
    for e, x in Ic[Ic.label.isin(SYL37)].groupby("exp"):
        t = x.onset.to_numpy() - SESS[e]["t"][0]
        starts = np.arange(0, 1800 - W + 1e-9, step)
        for lab, g in x.groupby("label"):
            tt = g.onset.to_numpy() - SESS[e]["t"][0]; da = g.da.to_numpy()
            cnt = np.array([np.sum((tt >= s0) & (tt < s0 + W)) for s0 in starts])
            dm = np.array([da[(tt >= s0) & (tt < s0 + W)].mean() if c > 0 else np.nan for s0, c in zip(starts, cnt)])
            if np.isnan(dm).any() or dm.std() == 0 or cnt.std() == 0:
                continue
            if circular:
                P = np.vstack([dm, np.array([np.roll(dm, rng.integers(1, len(dm))) for _ in range(nshuf)])])
            else:
                P = np.vstack([dm, np.array([rng.permutation(dm) for _ in range(nshuf)])])
            row = []
            for L in lags_s:
                k = int(round(L / step))
                if k >= 0:
                    a, b = P[:, :len(dm) - k], cnt[k:]
                else:
                    a, b = P[:, -k:], cnt[:len(dm) + k]
                if a.shape[1] < 3 or b.std() == 0:
                    row.append(np.full(nshuf + 1, np.nan)); continue
                za = (a - a.mean(1, keepdims=True)) / a.std(1, keepdims=True)
                row.append(za @ ((b - b.mean()) / b.std()) / len(b))
            row = np.array(row).T                         # (1 + nshuf) x lags
            ok = np.isfinite(row)
            obs_acc = obs_acc + np.where(ok, row, 0)
            n_acc = n_acc + ok
    R_ = obs_acc / n_acc
    obs, sh = R_[0], R_[1:]
    z = (obs - sh.mean(0)) / sh.std(0)
    p = (1 + (sh >= obs).sum(0)) / (1 + len(sh))
    zsh_max = np.nanmax((sh - sh.mean(0)) / sh.std(0), 1)
    fig2g_run.p_max = (1 + (zsh_max >= np.nanmax(z)).sum()) / (1 + len(sh))   # corrected for the choice of lag
    return lags_s, obs, z, p

for name, step, k in [("(a) non-overlapping 3-min windows", 180.0, 0), ("(b) windows sliding by 30 s", 30.0, 1)]:
    lags_s, obs, z, p = fig2g_run(step, rng_for("fig2g-usage-crosscorrelation", k), NSHUF)
    j = np.nanargmax(z)
    print(f"{name}: peak z {z[j]:.2f} at lag {lags_s[j] / 60:+.1f} min (mean r {obs[j]:.3f}), one-sided P = {p[j]:.4f}; "
          f"against the maximum over lags P = {fig2g_run.p_max:.4f}")
    print("   z by lag (min):", dict(zip((lags_s / 60).round(1).tolist(), np.round(z, 2).tolist())))
    pk = []
    for off in [1000, 2000, 3000, 4000]:
        _, _, z2, p2 = fig2g_run(step, rng_for("fig2g-usage-crosscorrelation", k + off), NSHUF)
        pk.append((round(float(np.nanmax(z2)), 2), round(float(p2[np.nanargmax(z2)]), 4)))
    print("   peak z and P under seeds +1000..+4000:", pk)
# Variant for reading (b): circular shifts of the dLight window series, which keep its autocorrelation
for k, circ_seed in enumerate([2, 1002, 2002, 3002, 4002]):
    lags_s, obs, z, p = fig2g_run(30.0, rng_for("fig2g-usage-crosscorrelation", circ_seed), NSHUF, circular=True)
    j = np.nanargmax(z)
    if k == 0:
        print(f"(b) with circular shifts: peak z {z[j]:.2f} at lag {lags_s[j] / 60:+.1f} min, one-sided P = {p[j]:.4f}; "
              f"against the maximum over lags P = {fig2g_run.p_max:.4f}")
        print("   z by lag (min):", dict(zip((lags_s / 60).round(1).tolist(), np.round(z, 2).tolist())))
    else:
        print(f"   seed +{circ_seed - 2}: peak z {z[j]:.2f}, P = {p[j]:.4f}, against the maximum over lags P = {fig2g_run.p_max:.4f}")
(a) non-overlapping 3-min windows: peak z 1.73 at lag +0.0 min (mean r 0.014), one-sided P = 0.0390; against the maximum over lags P = 0.1938
   z by lag (min): {-6.0: -0.28, -3.0: -0.49, 0.0: 1.73, 3.0: -0.32, 6.0: -2.16}
   peak z and P under seeds +1000..+4000: [(1.67, 0.044), (1.76, 0.044), (1.82, 0.04), (1.71, 0.041)]
(b) windows sliding by 30 s: peak z 2.05 at lag -7.5 min (mean r 0.009), one-sided P = 0.0240; against the maximum over lags P = 0.3037
   z by lag (min): {-7.5: 2.05, -7.0: 1.37, -6.5: 0.54, -6.0: 0.02, -5.5: -0.16, -5.0: -0.1, -4.5: 0.18, -4.0: 0.0, -3.5: -0.14, -3.0: -0.17, -2.5: -0.14, -2.0: -0.16, -1.5: -0.57, -1.0: 0.06, -0.5: 0.7, 0.0: 1.59, 0.5: 1.61, 1.0: 1.35, 1.5: 1.83, 2.0: 0.87, 2.5: -0.0, 3.0: -1.12, 3.5: -1.73, 4.0: -2.55, 4.5: -3.5, 5.0: -3.41, 5.5: -3.33, 6.0: -3.65, 6.5: -3.61, 7.0: -2.83, 7.5: -2.09}
   peak z and P under seeds +1000..+4000: [(2.25, 0.012), (2.1, 0.015), (2.1, 0.014), (2.18, 0.015)]
(b) with circular shifts: peak z 1.12 at lag -7.5 min, one-sided P = 0.1299; against the maximum over lags P = 0.7113
   z by lag (min): {-7.5: 1.12, -7.0: 0.76, -6.5: 0.3, -6.0: 0.04, -5.5: -0.04, -5.0: -0.02, -4.5: 0.11, -4.0: 0.01, -3.5: -0.07, -3.0: -0.09, -2.5: -0.09, -2.0: -0.09, -1.5: -0.31, -1.0: 0.03, -0.5: 0.35, 0.0: 0.78, 0.5: 0.83, 1.0: 0.7, 1.5: 0.95, 2.0: 0.46, 2.5: 0.04, 3.0: -0.52, 3.5: -0.84, 4.0: -1.26, 4.5: -1.79, 5.0: -1.81, 5.5: -1.77, 6.0: -2.01, 6.5: -1.87, 7.0: -1.37, 7.5: -0.96}
   seed +1000: peak z 1.08, P = 0.1309, against the maximum over lags P = 0.7323
   seed +2000: peak z 1.06, P = 0.1449, against the maximum over lags P = 0.7443
   seed +3000: peak z 1.12, P = 0.1359, against the maximum over lags P = 0.7183
   seed +4000: peak z 1.08, P = 0.1349, against the maximum over lags P = 0.7223

Result: not reproduced, resting on the reading of "the peak correlation exceeds all shuffles" as a comparison with the shuffles' peaks. At the peak lag the permutation test gives P = 0.039 (reading (a), z 1.73 at lag 0; 0.040 to 0.044 under the four further seeds) and P = 0.024 (reading (b), z 2.05 at -7.5 min, the edge of the lag range; 0.012 to 0.015 under the four further seeds). Compared with the shuffles' maximum over lags, P is 0.194 and 0.304. With circular shifts of the dLight windows, which keep their autocorrelation, reading (b) gives z 1.12 at -7.5 min, P = 0.130 at that lag (0.131 to 0.145 over seeds) and 0.711 against the maximum over lags (0.718 to 0.744). At positive lags of 4 to 7 min z falls to -3.65 under the permutation null and -2.01 under circular shifts.

ed3c-keypoint-velocity¶

"In keypoint-tracked mice, 2D velocity is negatively correlated with dLight in 400-ms bins (r = -0.16), and forelimb velocity, with other kinematics partialled out, correlates only negligibly (r = -0.02)."

In [30]:
KP = M.load_many(M.load_keypoint, [r for _, r in A[A.kind == "keypoint"].iterrows()], 5)
rng = rng_for("ed3c-keypoint-velocity")
def vel2(p):                       # difference over 2 frames divided by 2 (Methods), in mm per frame
    v = np.full(len(p), np.nan)
    v[2:] = np.linalg.norm(p[2:] - p[:-2], axis=1) / 2
    return v * M.FS
def kp_bins(zkey):
    B = []
    for d in KP:
        spine = np.mean([d["rostral_spine"], d["medial_spine"], d["caudal_spine"]], 0)
        v2 = vel2(spine[:, :2]); v3 = vel2(spine); h = spine[:, 2]
        fl = np.mean([vel2(d["left_forepaw"]), vel2(d["right_forepaw"])], 0)
        n = min(len(d[zkey]), len(v2)) // 12 * 12
        df = pd.DataFrame(dict(z=d[zkey][:n], v2=v2[:n], v3=v3[:n], h=h[:n], fl=fl[:n])).groupby(np.arange(n) // 12).mean().dropna()
        X = np.c_[np.ones(len(df)), df.v2, df.v3, df.h]
        df["zpart"] = df.z - X @ np.linalg.lstsq(X, df.z, rcond=None)[0]
        df["mouse"] = d["subject"]
        B.append(df)
        if zkey == "z":
            print(f"{d['subject']}: {len(d['z'])} photometry samples ({len(d['z']) / M.FS / 60:.1f} min), first and last "
                  f"timestamps {d['t'][0]:.3f} and {d['t'][-1]:.3f} s (median step {np.median(np.diff(d['t'])):.4f} s); "
                  f"{len(spine)} keypoint frames from starting_time {d['kp_start']:.3f} s at {d['rate']} Hz; "
                  f"dLight-reference r {d['refcorr']:.3f}, 400-ms bins {len(df)}; 2D speed median {np.nanmedian(v2):.1f} mm/s")
    return pd.concat(B)
# The criterion (as amended after the reader's answer): dLight processed as in the claims file's definitions,
# with the Methods' RANSAC fit with slope and bias; the fig_s03 notebook's fit without intercept (cell 15) is a variant.
def shuf_p(x, y, rng, n=1000):
    r = np.corrcoef(x, y)[0, 1]
    null = np.array([np.corrcoef(rng.permutation(x), y)[0, 1] for _ in range(n)])
    return r, (1 + np.sum(null <= r)) / (1 + n)          # one-sided, negative direction
EXP3C = {"2D velocity and dLight": (-0.16, 0.016), "forelimb velocity and partialled dLight": (-0.02, 0.002)}
for zkey, label, k in [("z", "fit with slope and bias (criterion)", 0), ("z_noint", "variant, fit without intercept (fig_s03)", 1)]:
    B = kp_bins(zkey)
    for name, a, b in [("2D velocity and dLight", "v2", "z"), ("forelimb velocity and partialled dLight", "fl", "zpart")]:
        r, p = shuf_p(B[a].to_numpy(), B[b].to_numpy(), rng_for("ed3c-keypoint-velocity", k))
        pm = B.groupby("mouse").apply(lambda g: np.corrcoef(g[a], g[b])[0, 1], include_groups=False)
        e, tol = EXP3C[name]
        print(f"{label}, {name}: pooled r = {r:.3f} (one-sided shuffle P = {p:.4f}); per-mouse mean r = {pm.mean():.3f} "
              f"(per mouse {pm.round(3).to_dict()}); within {e} +- {tol}: pooled {abs(r - e) <= tol}, per-mouse {abs(pm.mean() - e) <= tol}; "
              f"rounds to {e}: pooled {round(r, 2) == e}, per-mouse {round(pm.mean(), 2) == e}")
        if k == 0:   # seed range of the shuffle P under the criterion's processing
            ps = [shuf_p(B[a].to_numpy(), B[b].to_numpy(), rng_for("ed3c-keypoint-velocity", off))[1] for off in [1000, 2000, 3000, 4000]]
            print(f"   P under the seeds plus 1000 to 4000: {[round(float(x), 4) for x in ps]}")
dls-dlight-10: 44920 photometry samples (25.0 min), first and last timestamps 0.000 and 1497.300 s (median step 0.0333 s); 44920 keypoint frames from starting_time 0.000 s at 30.0 Hz; dLight-reference r 0.314, 400-ms bins 3743; 2D speed median 19.7 mm/s
dls-dlight-12: 44919 photometry samples (25.0 min), first and last timestamps 0.000 and 1497.267 s (median step 0.0333 s); 44919 keypoint frames from starting_time 0.000 s at 30.0 Hz; dLight-reference r 0.360, 400-ms bins 3743; 2D speed median 21.3 mm/s
dls-dlight-9: 44921 photometry samples (25.0 min), first and last timestamps 0.000 and 1497.333 s (median step 0.0333 s); 44921 keypoint frames from starting_time 0.000 s at 30.0 Hz; dLight-reference r 0.330, 400-ms bins 3743; 2D speed median 24.4 mm/s
dls-dlight-13: 44915 photometry samples (25.0 min), first and last timestamps 0.000 and 1497.133 s (median step 0.0333 s); 44915 keypoint frames from starting_time 0.000 s at 30.0 Hz; dLight-reference r 0.255, 400-ms bins 3742; 2D speed median 20.8 mm/s
dls-dlight-11: 44920 photometry samples (25.0 min), first and last timestamps 0.000 and 1497.300 s (median step 0.0333 s); 44920 keypoint frames from starting_time 0.000 s at 30.0 Hz; dLight-reference r 0.368, 400-ms bins 3743; 2D speed median 21.1 mm/s
fit with slope and bias (criterion), 2D velocity and dLight: pooled r = -0.170 (one-sided shuffle P = 0.0010); per-mouse mean r = -0.169 (per mouse {'dls-dlight-10': -0.128, 'dls-dlight-11': -0.22, 'dls-dlight-12': -0.182, 'dls-dlight-13': -0.131, 'dls-dlight-9': -0.185}); within -0.16 +- 0.016: pooled True, per-mouse True; rounds to -0.16: pooled False, per-mouse False
   P under the seeds plus 1000 to 4000: [0.001, 0.001, 0.001, 0.001]
fit with slope and bias (criterion), forelimb velocity and partialled dLight: pooled r = -0.026 (one-sided shuffle P = 0.0010); per-mouse mean r = -0.027 (per mouse {'dls-dlight-10': -0.022, 'dls-dlight-11': -0.053, 'dls-dlight-12': -0.039, 'dls-dlight-13': -0.019, 'dls-dlight-9': -0.003}); within -0.02 +- 0.002: pooled False, per-mouse False; rounds to -0.02: pooled False, per-mouse False
   P under the seeds plus 1000 to 4000: [0.001, 0.001, 0.002, 0.001]
variant, fit without intercept (fig_s03), 2D velocity and dLight: pooled r = -0.167 (one-sided shuffle P = 0.0010); per-mouse mean r = -0.165 (per mouse {'dls-dlight-10': -0.113, 'dls-dlight-11': -0.205, 'dls-dlight-12': -0.203, 'dls-dlight-13': -0.121, 'dls-dlight-9': -0.184}); within -0.16 +- 0.016: pooled True, per-mouse True; rounds to -0.16: pooled False, per-mouse False
variant, fit without intercept (fig_s03), forelimb velocity and partialled dLight: pooled r = -0.019 (one-sided shuffle P = 0.0020); per-mouse mean r = -0.020 (per mouse {'dls-dlight-10': -0.016, 'dls-dlight-11': -0.042, 'dls-dlight-12': -0.025, 'dls-dlight-13': -0.011, 'dls-dlight-9': -0.003}); within -0.02 +- 0.002: pooled True, per-mouse True; rounds to -0.02: pooled True, per-mouse True

Result: partially reproduced. With dLight processed as the amended criterion says (the Methods' RANSAC fit with slope and bias), in 400-ms bins of the 5 keypoint mice 2D velocity and dLight correlate at r = -0.170 (pooled; per-mouse mean -0.169; one-sided shuffle P = 0.001, 0.001 under all five seeds), within -0.16 +- 0.016. Forelimb velocity and partialled dLight correlate at r = -0.026 (pooled; per-mouse mean -0.027; P = 0.001, 0.001 to 0.002 over the five seeds), outside -0.02 +- 0.002 under both readings, and it rounds to -0.03, so the second expected value is missed. With the fig_s03 notebook's fit without intercept, now a variant, the values are -0.167 and -0.019, both within tolerance. Photometry and keypoints start at 0 s, have equal lengths in every session and share the 30-Hz rate. The reader's answer changed which fit decides: before it the criterion named the fig_s03 processing and the outcome was reproduced. The round-3 verifier agreed with the change to partially reproduced.

fig2a-food-reward-transients (blocked): the spontaneous half¶

The food-reward experiments are not in the dandiset, so the claim is blocked. The criterion's reading (b) of the spontaneous peaks can be computed on the DLS baseline experiments: peaks of the z-scored dLight above 1.5 z (the detection line drawn in the fig_2a notebook, as the claims file gives it), found with scipy's find_peaks (a standard choice).

In [31]:
from scipy.signal import find_peaks
pk_h = []
for _, r in DLS.iterrows():
    pk_h.append(find_peaks(exp_z(r.i), height=1.5)[1]["peak_heights"])
pk_h = np.concatenate(pk_h)
print(f"spontaneous peaks above 1.5 z in {len(DLS)} DLS baseline experiments: n = {len(pk_h)}, mean {pk_h.mean():.2f} "
      f"+- {pk_h.std():.2f} z (paper 2.12 +- 0.80, n = 5,247); the reward peaks cannot be computed")
spontaneous peaks above 1.5 z in 164 DLS baseline experiments: n = 232152, mean 2.25 +- 0.69 z (paper 2.12 +- 0.80, n = 5,247); the reward peaks cannot be computed

Result: blocked (data missing). The spontaneous peaks average 2.25 +- 0.69 z, within 2.12 +- 0.80, but there are 232,152 of them against the paper's 5,247 (whose selection is not given), and the reward peaks cannot be computed.

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
ed2a-syllable-repertoire reproduced
fig1e-velocity-timescales partially reproduced (rate yes, amplitude no)
ed3c-keypoint-velocity partially reproduced (2D velocity r within tolerance; forelimb r -0.026 misses under the Methods' fit with intercept)
fig1f-syllable-vs-movement-onset partially reproduced (count-matched, reading (b) favours syllables, reading (a) favours movement; assumed)
fig1f-dip-then-peak reproduced (assumed window)
fig1h-syllable-dlight-differs partially reproduced (H above tolerance)
fig1j-weak-kinematic-correlation reproduced (assumed bound)
fig2b-dlight-usage-across-syllables, fig2i-dlight-entropy-across-syllables, fig2b-across-experiments reproduced
fig2e-dlight-predicts-future-usage reproduced
fig2e-not-autocorrelation partially reproduced (the amended criterion's partial case; reproduced under two of the four other seeds)
fig2g-usage-crosscorrelation not reproduced (peak against the shuffles' peaks)
fig2h-specific-to-syllable not reproduced
fig2k-dlight-predicts-sequence-variability reproduced under reading (a) against the Methods' null (amended criterion); reading (b) significantly negative
ed7-dms-fewer-transients reproduced
ed7b-dms-transient-shape, ed7d-dms-smaller-peaks not reproduced
fig1l, fig2a, ed6b, ed6e, ed7-dms-no-usage-prediction, ed7e, fig3c, Fig. 4, Fig. 5 blocked (see the attempt record)

How the analysis differs from the paper's: the DLS baseline set is the code's (stimulation mice's pure post days and the two 2-s excitation sessions dropped; files that are the baseline of one target and the post day of another kept), 164 experiments where the paper counts 216 in Fig. 1b; quality control follows the Methods (reading (a)), with the code's rule (b) run for fig1f, fig1h, ed7, ed7b and ed7d (157 DLS and 64 DMS experiments, the paper's DMS count); the files' dF/F is taken as the Methods' dF/F0; the 37 syllables are those above 1% mean usage over the 14 photometry mice; movement initiations take the changepoint derivative per second, with a variant kept when preceded by relative stillness, and syllable onsets are also drawn down to the initiation count; fig1j uses 5 repeats of cross-validation and a Pearson shuffle null; fig2e drops index instances without 390 following syllables; fig2k is run at n = 5 and 10 only, with 200 shuffles for the code's null and for the seed range; seed ranges were computed for ed3c, fig1f's count-matched check, fig2e-not-autocorrelation, fig2g and fig2k.

What was found about the dataset: the two dLight-only DLS mice without photometry (dls-dlight-6 and -8) and two DMS mice without photometry (dms-dlight-7 and -9) match the paper's exclusions in DLS but leave 10 DMS mice in the dandiset for the paper's 8; 32 DLS photometry-session files (22 dLight-only, 10 dLight+ChrimsonR) and 92 DMS files have behaviour but no photometry; one dLight+ChrimsonR file has a dF/F of up to 10,804% and a dLight-reference correlation of 0.998 and fails quality control, and one dLight-only file has a raw dF/F of 228 (22,798%); 38 dLight+ChrimsonR files are the baseline of one target and the post day of another, and two 2-s excitation sessions carry baseline and post-day session numbers. The syllable-associated dLight contrast is largest with the labels shifted 3 samples earlier in 19 of 22 mice (6 earlier in one, unshifted in two DMS mice), in both DLS groups and in DMS alike (H 941 at -6 and 888 at 0 samples pooled, 79 at +60), consistent with a clock shared by all groups; even so, the syllable-onset averages of the dLight+ChrimsonR mice peak later and lower than the dLight-only mice's, which is not explained here. The food-reward and calibration sessions are not in the dandiset.