Markowitz et al. (2023): Opto-DA claims, on dandiset 000559¶

Paper: doi:10.1038/s41586-022-05611-2; claims file claims/markowitz-2023.yaml, written from the version of record. Dataset: DANDI:000559, version 0.261113.1911, the most recent published version (the paper cites none); its release notes say earlier versions lacked the catch trials and mislabelled the light source and groups, which the claims below need. Files are streamed.

This notebook tests the closed-loop Opto-DA claims (Fig. 3, Extended Data Fig. 10) on the reinforcement experiments of the 20 DAT-IRES-cre::Ai32 mice and 12 no-opsin controls, with the online MoSeq labels (Methods, Offline variant: the Opto-DA experiments of Figs. 3 and 4 use the online variant).

claim here
fig3e-optoda-learning tested
fig3f-cumulative-counts tested
fig3e-learner-count tested
fig3h-stim-post-correlation tested
fig3i-optoda-entropy tested
fig3l-no-kinematic-effect tested
fig3m-long-stim-velocity tested
ed10e-no-duration-change tested
ed10i-no-place-preference tested
fig3jk-post-predictable tested
ed10d-optoda-vigour tested: the direction is stated for 4 of 9 mice (sanity cell); the section ed10d recovers it from the data and runs the test
ed10-target-specific blocked (other): not run
In [1]:
import zlib, time
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)

T0 = time.time()
A = M.list_assets()
rows = [r for _, r in A[A.kind.isin(["reinforcement", "velocity-modulation"])].iterrows()]
SESS = M.load_many(M.load_opto, rows)
print(len(SESS), "files loaded in", round(time.time() - T0), "s")
1434 files loaded in 124 s
In [2]:
OPTO = {"snc-dls-ai32", "snc-dls-ai32-jrcamp1a"}
CTRL = {"ctrl", "snc-dls-ctrl", "vta-nacc-ctrl"}
R = []
for i, d in enumerate(SESS):
    tg = d.get("ts_target_syllable", [])
    for k in range(len(tg)):
        R.append(dict(i=i, mouse=d["subject"], group=d["group"], kind="velmod" if "velocity-modulation" in d["path"] else "reinf",
                      target=int(tg[k]), sn=d["ts_session_number"][k], stim=d["ts_stim_duration"][k],
                      etype=d["ts_experiment_type"][k], exclude=bool(d["ts_exclude"][k]), start=d["start"],
                      n_det=len(d["det_time"]), n_stimdet=int(d["det_stim"].sum()), n_on=len(d["stim_on"]),
                      dur=d["t_last"] - d["t_first"]))
R = pd.DataFrame(R)
R["arm"] = np.where(R.group.isin(OPTO), "Opto-DA", np.where(R.group.isin(CTRL), "control", "other"))
R["day"] = R.start.map(lambda t: t.date())
In [3]:
print("files by group and kind:"); print(R.drop_duplicates("i").groupby(["group", "kind"]).size().to_string())
print("\nmice per arm:", R.drop_duplicates("mouse").groupby("arm").size().to_dict())
print("\nrows (file x target) by experiment type and stimulation duration:")
print(R.groupby(["arm", "etype", "stim"], dropna=False).size().to_string())
print("\nsession numbers of 0.25-s reinforcement rows:", R[(R.stim == 0.25) & (R.kind == "reinf")].sn.value_counts().sort_index().to_dict())
print("excluded rows:", R[R.exclude][["mouse", "sn", "target"]].to_dict("records"))
st = R[R.sn.isin([1, 2]) & (R.kind == "reinf")].drop_duplicates("i")
print("\nstimulation files: detections per file median", st.n_det.median(), "; stimulated share",
      round(st.n_stimdet.sum() / st.n_det.sum(), 3), "(the Methods give 75%)")
print("stimulated detections equal light onsets in", (st.n_stimdet == st.n_on).sum(), "of", len(st), "files")
lat = []
for i in st.i:
    d = SESS[i]
    if len(d["stim_on"]) and d["det_stim"].sum():
        dt = np.subtract.outer(d["stim_on"], d["det_time"][d["det_stim"]])
        lat.append(np.median(np.min(np.abs(dt), 1)))
lat = np.array(lat)
print("per file, median time from a light onset to the nearest stimulated detection (s): 0 in",
      int(np.sum(lat < 1e-3)), "of", len(lat), "files; largest", lat.max().round(3))
print("experiment length (s): median", R.drop_duplicates("i").dur.median().round(1), "range",
      R.drop_duplicates("i").dur.min().round(1), "to", R.drop_duplicates("i").dur.max().round(1))
print("online labels sorted in time in every file:", all(d["syl_sorted"] for d in SESS))
# clock check: the online target detections must fall on instances of the target syllable
hit = []
for i in st.i[:200]:
    d = SESS[i]; inst = d["inst"]
    k = np.searchsorted(inst.onset.to_numpy(), d["det_time"], side="right") - 1
    ok = k >= 0
    lab = inst.label.to_numpy()[k[ok]]
    hit.append(np.mean(lab == d["det_target"][ok]))
print("share of detections that fall inside an instance of the target label: median", np.median(hit).round(3))
for sh in [-30, -10, 10, 30]:
    hh = []
    for i in st.i[:50]:
        d = SESS[i]; inst = d["inst"]
        k = np.searchsorted(inst.onset.to_numpy(), d["det_time"] + sh / 30, side="right") - 1
        ok = k >= 0
        hh.append(np.mean(inst.label.to_numpy()[k[ok]] == d["det_target"][ok]))
    print(f"   with detections shifted by {sh} frames: {np.median(hh):.3f}")
vm = pd.DataFrame([dict(mouse=d["subject"], description=d["session_description"], seconds=round(d["t_last"] - d["t_first"]),
                        stimulated=int(d["det_stim"].sum())) for d in SESS if "velocity-modulation" in d["path"]])
vm["direction"] = vm.description.str.extract(r"-(up|down)")[0].fillna("not stated")
print("\nvelocity-modulation files by mouse and the direction their session description states:")
print(vm.groupby(["mouse", "direction"]).size().unstack(fill_value=0).to_string())
# ed10d's inclusion rule needs at least 50 stimulations in the experiment
vm["50_or_more_stimulations"] = vm.stimulated >= 50
print("velocity-modulation files with stimulated detections, by mouse and direction: count, and how many have 50 or more")
print(vm[vm.stimulated > 0].groupby(["mouse", "direction"]).agg(files=("stimulated", "size"), median_stimulated=("stimulated", "median"),
      with_50=("50_or_more_stimulations", "sum")).to_string())
v = pd.concat([d["inst"] for d in SESS[:100] if "vel" in d["inst"]])
print("instance mean 2D speed (mm/s) percentiles 1, 50, 99:", np.nanpercentile(v.vel, [1, 50, 99]).round(1))
files by group and kind:
group                  kind  
ctrl                   reinf      30
snc-dls-ai32           reinf     646
                       velmod     44
snc-dls-ai32-jrcamp1a  reinf     159
                       velmod     50
snc-dls-ctrl           reinf     220
snc-eyfp               reinf      36
vta-nacc-ctrl          reinf     249

mice per arm: {'Opto-DA': 24, 'control': 12, 'other': 1}

rows (file x target) by experiment type and stimulation duration:
arm      etype              stim
Opto-DA                     0.25     94
         excitation         2.00    101
         excitation_pulsed  3.00    108
         reinforcement      0.25    719
control  excitation         2.00     71
         excitation_pulsed  3.00     72
         reinforcement      0.25    440
other    excitation         2.00     40

session numbers of 0.25-s reinforcement rows: {-1.0: 194, 0.0: 194, 1.0: 194, 2.0: 194, 3.0: 192, 4.0: 191}
excluded rows: [{'mouse': '1527', 'sn': 2.0, 'target': 8}, {'mouse': '211', 'sn': 4.0, 'target': 1}, {'mouse': '1561', 'sn': 2.0, 'target': 3}, {'mouse': '209', 'sn': 2.0, 'target': 3}]

stimulation files: detections per file median 76.5 ; stimulated share 0.707 (the Methods give 75%)
stimulated detections equal light onsets in 462 of 522 files
per file, median time from a light onset to the nearest stimulated detection (s): 0 in 456 of 516 files; largest 1.48
experiment length (s): median 1796.7 range 1795.9 to 5400.0
online labels sorted in time in every file: True
share of detections that fall inside an instance of the target label: median 0.997
   with detections shifted by -30 frames: 0.073
   with detections shifted by -10 frames: 0.091
   with detections shifted by 10 frames: 0.395
   with detections shifted by 30 frames: 0.107

velocity-modulation files by mouse and the direction their session description states:
direction     down  not stated  up
mouse                             
5891             2           6   3
5892             2           6   3
5893             2           6   3
5894             2           6   3
dls-ai32jr-1     0          10   0
dls-ai32jr-2     0          10   0
dls-ai32jr-3     0          10   0
dls-ai32jr-4     0          10   0
dls-ai32jr-5     0          10   0
velocity-modulation files with stimulated detections, by mouse and direction: count, and how many have 50 or more
                         files  median_stimulated  with_50
mouse        direction                                    
5891         down            2                4.0        0
             not stated      2                3.0        0
             up              1               15.0        0
5892         down            2               12.5        0
             not stated      2               35.5        1
             up              3               23.0        0
5893         down            2               21.0        0
             not stated      2               46.0        1
             up              2               75.5        2
5894         down            2               79.5        2
             not stated      2              123.5        2
             up              3              117.0        2
dls-ai32jr-1 not stated      6                4.0        0
dls-ai32jr-2 not stated      6               26.0        0
dls-ai32jr-3 not stated      6               70.5        5
dls-ai32jr-4 not stated      6               23.5        2
dls-ai32jr-5 not stated      6               98.0        5
instance mean 2D speed (mm/s) percentiles 1, 50, 99: [  5.9  37.1 247.7]
In [4]:
# Target counts: run-length instances of the target in the first 30 min of each experiment.
def tcount(i, target, tmax=1800):
    d = SESS[i]; inst = d["inst"]
    t = inst.onset.to_numpy() - d["t_first"]
    return int(np.sum((inst.label.to_numpy() == target) & (t < tmax)))

def target_table(stim_dur=0.25, etypes=("reinforcement",), tcount=tcount, monday=False):
    rr = R[(R.kind == "reinf") & (R.stim == stim_dur) & R.etype.isin(etypes) & R.arm.isin(["Opto-DA", "control"]) & ~R.exclude]
    out = []
    for (m, tg), g in rr.groupby(["mouse", "target"]):
        sti = g[g.sn.isin([1, 2])]
        if sti.sn.nunique() < 2:
            continue
        stim_day = sti.day.min()
        base = g[g.sn.isin([-1, 0]) & (g.day < stim_day)]
        if len(base) == 0:
            continue
        bday = base.day.max()                          # most recent previous baseline day
        if monday:                                     # variant: a Monday baseline day within 5 days before, if any
            mon = [dd for dd in base.day.unique() if dd.weekday() == 0 and (stim_day - dd).days <= 5]
            if mon:
                bday = max(mon)
        base = base[base.day == bday]
        post = g[g.sn.isin([3, 4])]
        c_stim = sum(tcount(i, tg) for i in sti.i)
        c_base = np.mean([tcount(i, tg) for i in base.i]) * 2
        c_post = sum(tcount(i, tg) for i in post.i) if post.sn.nunique() == 2 else np.nan
        out.append(dict(mouse=m, arm=g.arm.iloc[0], target=tg, stim=c_stim, base=c_base, post=c_post,
                        n_base=len(base), days_before=(stim_day - bday).days,
                        base_i=list(base.i), post_i=list(post.i), stim_i=list(sti.i)))
    T = pd.DataFrame(out)
    T["lfc"] = np.log2((T.stim + 2) / (T.base + 2))
    T["dc"] = T.stim - T.base
    T["dc_post"] = T.post - T.base
    ntg = T.groupby("mouse").target.transform("size")
    return T[ntg >= 2]

T3 = target_table()
PMS = T3.groupby(["mouse", "arm"]).agg(lfc=("lfc", "mean"), dc=("dc", "mean"), dc_post=("dc_post", "mean"),
                                         n_targets=("target", "size")).reset_index()
print("mouse-target pairs:", len(T3), "; mice per arm:", PMS.groupby("arm").size().to_dict())
print("targets per mouse:", PMS.n_targets.value_counts().to_dict(), "; baseline experiments per pair:",
      T3.n_base.value_counts().to_dict(), "; days from baseline to stimulation:", T3.days_before.value_counts().to_dict())

def mwu(a, b, alt):
    u = stats.mannwhitneyu(a, b, alternative=alt)
    return u.statistic, u.statistic / (len(a) * len(b)), u.pvalue
mouse-target pairs: 191 ; mice per arm: {'Opto-DA': 20, 'control': 12}
targets per mouse: {6: 27, 5: 3, 7: 2} ; baseline experiments per pair: {2: 191} ; days from baseline to stimulation: {1: 189, 2: 2}

fig3e-optoda-learning¶

In [5]:
a = PMS[PMS.arm == "Opto-DA"].lfc; b = PMS[PMS.arm == "control"].lfc
U, f, p = mwu(a, b, "greater")
print(f"log2 fold change per mouse: Opto-DA median {a.median():.3f} (n={len(a)}), control median {b.median():.3f} (n={len(b)})")
print(f"one-sided Mann-Whitney U = {U:.0f}, f = {f:.2f}, P = {p:.4f}")
print(PMS.sort_values("lfc").round(3).to_string(index=False))
# variant: counts from the offline labels of the same experiments (whole files)
def tcount_off(i, target):
    oi = SESS[i].get("off_inst")
    return int((oi.label == target).sum()) if oi is not None else np.nan
T3off = target_table(tcount=lambda i, target: tcount_off(i, target))
PMoff = T3off.groupby(["mouse", "arm"]).agg(lfc=("lfc", "mean"), dc=("dc", "mean")).reset_index()
for col in ["lfc", "dc"]:
    U, f, p = mwu(PMoff[PMoff.arm == "Opto-DA"][col], PMoff[PMoff.arm == "control"][col], "greater")
    print(f"variant, offline labels, {col}: U = {U:.0f}, f = {f:.2f}, P = {p:.4f}")
# variant: the code's preference for a Monday baseline day within 5 days before stimulation
T3mon = target_table(monday=True)
PMmon = T3mon.groupby(["mouse", "arm"]).agg(lfc=("lfc", "mean"), dc=("dc", "mean")).reset_index()
print("Monday variant: pairs whose baseline day changes", int((T3mon.set_index(["mouse", "target"]).base_i.map(tuple)
      != T3.set_index(["mouse", "target"]).base_i.map(tuple)).sum()), "of", len(T3))
for col in ["lfc", "dc"]:
    U, f, p = mwu(PMmon[PMmon.arm == "Opto-DA"][col], PMmon[PMmon.arm == "control"][col], "greater")
    print(f"variant, Monday baseline, {col}: U = {U:.0f}, f = {f:.2f}, P = {p:.4f}")
thr_m = PMmon[PMmon.arm == "control"].dc.max()
print("variant, Monday baseline: learners", int(((PMmon.arm == "Opto-DA") & (PMmon.dc > thr_m)).sum()),
      sorted(PMmon[(PMmon.arm == "Opto-DA") & (PMmon.dc > thr_m)].mouse))
log2 fold change per mouse: Opto-DA median 0.215 (n=20), control median 0.175 (n=12)
one-sided Mann-Whitney U = 152, f = 0.63, P = 0.1101
          mouse     arm    lfc      dc  dc_post  n_targets
            209 control -0.469 -56.200  -84.400          5
           1527 control -0.357 -61.000   -3.800          5
           1546 Opto-DA  0.012   9.667   -6.667          6
            241 Opto-DA  0.039  26.833  -29.833          6
           3440 Opto-DA  0.106   4.500   -6.500          6
            197 control  0.109  36.167    8.833          6
   dls-ai32jr-5 Opto-DA  0.113  13.167  -50.333          6
 snc-dls-ctrl-6 control  0.125   1.000  -11.500          7
           1529 Opto-DA  0.128  65.333   54.500          6
   dls-ai32jr-2 Opto-DA  0.129  10.167  -22.600          6
          15847 Opto-DA  0.140  16.833  -19.333          6
           1561 control  0.166  13.200   15.800          5
vta-nacc-ctrl-6 control  0.171  31.000   40.833          7
            410 Opto-DA  0.175  32.167   -3.000          6
   dls-ai32jr-4 Opto-DA  0.176  -2.833  -29.500          6
 snc-dls-ctrl-7 control  0.179  60.500   24.667          6
            208 control  0.187   2.000  -12.667          6
            242 Opto-DA  0.206  27.500    4.167          6
            200 control  0.213  45.333  -18.000          6
            239 Opto-DA  0.224  36.333  -11.667          6
vta-nacc-ctrl-7 control  0.253  18.333   10.833          6
           3441 Opto-DA  0.293  32.333   46.833          6
   dls-ai32jr-3 Opto-DA  0.305  64.000   15.333          6
            211 control  0.400  50.333    9.200          6
   dls-ai32jr-1 Opto-DA  0.403  19.667   15.500          6
            240 Opto-DA  0.460  99.500   27.167          6
             10 control  0.478  28.000   -3.667          6
           3442 Opto-DA  0.490  48.500   -8.167          6
           1544 Opto-DA  0.497 157.167  122.500          6
          15823 Opto-DA  0.524  64.000   45.667          6
          15822 Opto-DA  0.715  77.667   46.667          6
           1528 Opto-DA  0.763 163.833  105.500          6
variant, offline labels, lfc: U = 129, f = 0.54, P = 0.3701
variant, offline labels, dc: U = 153, f = 0.64, P = 0.1025
Monday variant: pairs whose baseline day changes 0 of 191
variant, Monday baseline, lfc: U = 152, f = 0.63, P = 0.1101
variant, Monday baseline, dc: U = 160, f = 0.67, P = 0.0621
variant, Monday baseline: learners 7 ['1528', '1529', '1544', '15822', '15823', '240', 'dls-ai32jr-3']

Result: not reproduced. The log2 fold change in target counts is not significantly larger in the 20 Opto-DA mice than in the 12 controls (medians 0.215 and 0.175; one-sided U = 152, f = 0.63, P = 0.110); with offline labels P = 0.370. The code's Monday-baseline rule changes the baseline of none of the 191 pairs, so its variant gives the same U.

fig3f-cumulative-counts and fig3e-learner-count¶

In [6]:
a = PMS[PMS.arm == "Opto-DA"].dc; b = PMS[PMS.arm == "control"].dc
U, f, p = mwu(a, b, "greater")
print(f"change in counts per mouse: Opto-DA median {a.median():.1f}, control median {b.median():.1f}; U = {U:.0f}, f = {f:.2f}, P = {p:.4f}")
change in counts per mouse: Opto-DA median 32.2, control median 23.2; U = 160, f = 0.67, P = 0.0621

Result: not reproduced. The change in counts above baseline is larger in Opto-DA mice than in controls, but not significantly (medians 32.2 and 23.2; U = 160, f = 0.67, P = 0.062).

In [7]:
thr = PMS[PMS.arm == "control"].dc.max()
LEARN = PMS[(PMS.arm == "Opto-DA") & (PMS.dc > thr)].mouse.tolist()
print(f"largest mean change among controls: {thr:.1f}; Opto-DA mice above it: {len(LEARN)} of {(PMS.arm == 'Opto-DA').sum()}")
print("learners:", LEARN)
# The nine learners the paper's notebook prints (fig_3e ... optoda learning, cell 78 output), read from
# the paper's repository at commit 14ed714c (outside input, used only to report the overlap)
import json, re, requests
URL = ("https://raw.githubusercontent.com/dattalab/dopamine-reinforces-spontaneous-behavior/"
       "14ed714c4f49be1f4728a080eb65c4ee42f74c23/notebooks_panels/"
       "fig_3e, 3f, 3g, 3h, 4d, 4e, s9g, s9h-optoda learning.ipynb")
nbp = requests.get(URL.replace(" ", "%20"), timeout=60).json()
out78 = [c for c in nbp["cells"] if c.get("execution_count") == 71][0]
txt = "".join("".join(o.get("text", "")) for o in out78["outputs"])
PAPER_LEARN = re.findall(r"\('snc \(axon\)', '([^']+)'\)", txt)
print("paper's learners:", PAPER_LEARN)
print("in both:", sorted(set(LEARN) & set(PAPER_LEARN)), "; only here:", sorted(set(LEARN) - set(PAPER_LEARN)),
      "; only in the paper:", sorted(set(PAPER_LEARN) - set(LEARN)))
print("the paper-only learners here: mean change", PMS[PMS.mouse.isin(set(PAPER_LEARN) - set(LEARN))][["mouse", "dc", "n_targets"]].round(1).to_dict("records"),
      "against the control maximum", round(thr, 1))
largest mean change among controls: 60.5; Opto-DA mice above it: 7 of 20
learners: ['1528', '1529', '1544', '15822', '15823', '240', 'dls-ai32jr-3']
paper's learners: ['1528', '1529', '1544', '15822', '15823', '240', '3442', 'dls-ai32jr-1', 'dls-ai32jr-3']
in both: ['1528', '1529', '1544', '15822', '15823', '240', 'dls-ai32jr-3'] ; only here: [] ; only in the paper: ['3442', 'dls-ai32jr-1']
the paper-only learners here: mean change [{'mouse': '3442', 'dc': 48.5, 'n_targets': 6}, {'mouse': 'dls-ai32jr-1', 'dc': 19.7, 'n_targets': 6}] against the control maximum 60.5

Result: not reproduced. 7 of 20 Opto-DA mice exceed the largest mean change among controls (60.5), where the paper reports 9. All 7 are among the paper's nine learners; the other two, 3442 and dls-ai32jr-1, have mean changes of 48.5 and 19.7 here, below the control maximum.

fig3h-stim-post-correlation¶

In [8]:
rng = rng_for("fig3h-stim-post-correlation")
for name, sub in [("learners", PMS[PMS.mouse.isin(LEARN)]), ("controls", PMS[PMS.arm == "control"])]:
    sub = sub.dropna(subset=["dc", "dc_post"])
    r = np.corrcoef(sub.dc, sub.dc_post)[0, 1]
    null = np.array([np.corrcoef(rng.permutation(sub.dc.to_numpy()), sub.dc_post)[0, 1] for _ in range(1000)])
    p = (1 + np.sum(null >= r)) / 1001
    print(f"{name}: n = {len(sub)}, Pearson r = {r:.3f}, one-sided shuffle P = {p:.4f}")
seeds_r = []
for k in [1000, 2000, 3000, 4000]:
    rg = rng_for("fig3h-stim-post-correlation", k)
    sub = PMS[PMS.mouse.isin(LEARN)].dropna(subset=["dc", "dc_post"])
    r = np.corrcoef(sub.dc, sub.dc_post)[0, 1]
    null = np.array([np.corrcoef(rg.permutation(sub.dc.to_numpy()), sub.dc_post)[0, 1] for _ in range(1000)])
    seeds_r.append((1 + np.sum(null >= r)) / 1001)
print("learners' P under seeds +1000..+4000:", np.round(seeds_r, 4))
seeds_c = []
for k in [1000, 2000, 3000, 4000]:
    rg = rng_for("fig3h-stim-post-correlation", k)
    sub = PMS[PMS.arm == "control"].dropna(subset=["dc", "dc_post"])
    r = np.corrcoef(sub.dc, sub.dc_post)[0, 1]
    null = np.array([np.corrcoef(rg.permutation(sub.dc.to_numpy()), sub.dc_post)[0, 1] for _ in range(1000)])
    seeds_c.append((1 + np.sum(null >= r)) / 1001)
print("controls' P under seeds +1000..+4000:", np.round(seeds_c, 4))
learners: n = 7, Pearson r = 0.868, one-sided shuffle P = 0.0310
controls: n = 12, Pearson r = 0.633, one-sided shuffle P = 0.0250
learners' P under seeds +1000..+4000: [0.038 0.031 0.035 0.025]
controls' P under seeds +1000..+4000: [0.041 0.036 0.03  0.031]

Result: partially reproduced. In the 7 learners the change during stimulation predicts the change after it (r = 0.868, within 0.89 +- 0.089; one-sided P = 0.031, and from 0.025 to 0.038 under the further seeds), but the controls' correlation is also significant (r = 0.633, P = 0.025, from 0.030 to 0.041 under the further seeds), where the paper reports P = 0.082.

Trial-aligned measures for fig3i, fig3l, fig3m and ed10e¶

Stimulation trials are online detections with light; catch trials detections without (TargetDetections). Each trial is aligned to the instance it falls in.

In [9]:
NB = 10                                               # five-syllable bins up to 50 syllables
def trial_measures(i):
    d = SESS[i]; inst = d["inst"]
    on = inst.onset.to_numpy(); lab = inst.label.to_numpy()
    k = np.searchsorted(on, d["det_time"], side="right") - 1
    rows_ = []
    vars_ = {v: inst[v].to_numpy() for v in ["vel", "angvel", "hvel", "acc"] if v in inst}
    if "angvel" in vars_:
        vars_["angvel"] = np.abs(vars_["angvel"])
    for kk, stim_ in zip(k, d["det_stim"]):
        if kk - 5 < 0 or kk + 5 * NB >= len(lab):
            continue
        r = dict(stim=bool(stim_), k=kk, dur=inst.dur.iloc[kk])
        for v, x in vars_.items():
            pre = np.nanmean(x[kk - 5:kk])
            for b in range(NB):
                r[f"{v}_{b}"] = np.nanmean(x[kk + 5 * b:kk + 5 * b + 5]) - pre
                r[f"{v}raw_{b}"] = np.nanmean(x[kk + 5 * b:kk + 5 * b + 5])
        rows_.append(r)
    return pd.DataFrame(rows_), lab

def cond_entropy(seqs, K):
    """Conditional entropy (bits) of transitions pooled over sequences, Perks prior 1/K."""
    C = np.zeros((K, K))
    for s in seqs:
        if len(s) > 1:
            np.add.at(C, (s[:-1], s[1:]), 1)
    rows_ = C.sum(1) > 0
    Cp = C[rows_] + 1 / K
    P = Cp / Cp.sum(1, keepdims=True)
    w = C[rows_].sum(1) / C.sum()
    return float(np.sum(w * -(P * np.log2(P)).sum(1)))

def experiment_table(rr, match_rng=None):
    """Per experiment and trial type, the trial measures. With `match_rng`, stimulation trials are
    drawn at random down to the number of catch trials (check of the entropy's sample-size bias)."""
    out = []
    for _, r in rr.drop_duplicates("i").iterrows():
        tm, lab = trial_measures(r.i)
        if len(tm) == 0 or tm.stim.sum() < 1 or (~tm.stim).sum() < 1:
            continue
        if match_rng is not None:
            st_i = np.flatnonzero(tm.stim.to_numpy())
            keep = match_rng.choice(st_i, min(len(st_i), int((~tm.stim).sum())), replace=False)
            tm = tm[(~tm.stim) | np.isin(np.arange(len(tm)), keep)]
        K = lab.max() + 1
        for cond, g in tm.groupby("stim"):
            row = dict(i=r.i, mouse=r.mouse, arm=r.arm, sn=r.sn, target=r.target, stim=cond, n=len(g), dur=g.dur.mean())
            row.update(g.drop(columns=["stim", "k", "dur"]).mean().to_dict())
            ks = g.k.to_numpy()
            pre = cond_entropy([lab[k - 5:k] for k in ks], K)
            for b in range(NB):
                row[f"ent_{b}"] = cond_entropy([lab[k + 5 * b:k + 5 * b + 5] for k in ks], K) - pre
            out.append(row)
    return pd.DataFrame(out)

t0 = time.time()
E25 = experiment_table(R[(R.kind == "reinf") & (R.stim == 0.25) & (R.etype == "reinforcement") & R.sn.isin([1, 2])
                         & R.arm.isin(["Opto-DA", "control"]) & ~R.exclude])
E3 = experiment_table(R[(R.kind == "reinf") & (R.stim == 3.0) & R.sn.isin([1, 2]) & R.arm.isin(["Opto-DA", "control"]) & ~R.exclude])
print("250-ms experiments with both trial types:", E25.i.nunique(), "; 3-s pulsed:", E3.i.nunique(), "; in", round(time.time() - t0), "s")
print("3-s pulsed experiments by arm and mice:", E3.drop_duplicates("i").groupby("arm").mouse.nunique().to_dict())

def catch_z(E, col):
    """Values z-scored with the mean and s.d. of catch trials (Methods), per arm."""
    c = E[~E.stim][col]
    return (E[col] - c.mean()) / c.std()

def stim_vs_catch(E, var, alt, nb=NB):
    res = {}
    for arm, g in E.groupby("arm"):
        ps, us = [], []
        for b in range(nb):
            col = f"{var}_{b}"
            z = catch_z(g, col)
            s, c = z[g.stim].dropna(), z[~g.stim].dropna()
            u = stats.mannwhitneyu(s, c, alternative=alt)
            ps.append(u.pvalue); us.append(u.statistic / (len(s) * len(c)))
        res[arm] = (np.array(ps), M.holm(ps), np.array(us))
    return res
250-ms experiments with both trial types: 377 ; 3-s pulsed: 60 ; in 89 s
3-s pulsed experiments by arm and mice: {'Opto-DA': 3, 'control': 2}

fig3i-optoda-entropy¶

In [10]:
res = stim_vs_catch(E25, "ent", "two-sided")
for arm, (p, ph, f) in res.items():
    g = E25[E25.arm == arm]
    med = [(g[g.stim][f"ent_{b}"].median() - g[~g.stim][f"ent_{b}"].median()) for b in range(NB)]
    print(f"{arm}: experiments {g.i.nunique()}; stim minus catch, median entropy change per bin {np.round(med, 3).tolist()}")
    print(f"   f per bin {np.round(f, 2).tolist()}")
    print(f"   P (Holm) per bin {np.round(ph, 4).tolist()}")
# check of the plug-in entropy's sample-size bias: stimulation trials outnumber catch trials about 3:1;
# the same test with stimulation trials drawn down to the catch count in each experiment
E25m = experiment_table(R[(R.kind == "reinf") & (R.stim == 0.25) & (R.etype == "reinforcement") & R.sn.isin([1, 2])
                          & R.arm.isin(["Opto-DA", "control"]) & ~R.exclude], match_rng=rng_for("fig3i-optoda-entropy", 1))
print("trials per experiment, stimulation and catch, before matching:", E25.groupby("stim").n.median().to_dict(),
      "; after:", E25m.groupby("stim").n.median().to_dict())
for arm, (p, ph, f) in stim_vs_catch(E25m, "ent", "two-sided").items():
    print(f"matched counts, {arm}: f per bin {np.round(f, 2).tolist()}; P (Holm) per bin {np.round(ph, 4).tolist()}")
for k in [1000, 2000, 3000, 4000]:
    E_ = experiment_table(R[(R.kind == "reinf") & (R.stim == 0.25) & (R.etype == "reinforcement") & R.sn.isin([1, 2])
                            & R.arm.isin(["Opto-DA", "control"]) & ~R.exclude], match_rng=rng_for("fig3i-optoda-entropy", 1 + k))
    r_ = stim_vs_catch(E_, "ent", "two-sided")
    print(f"matched counts, seed +{k}: Opto-DA first-bin f {r_['Opto-DA'][2][0]:.2f}, Holm P {r_['Opto-DA'][1][0]:.4f}, "
          f"smallest Holm P over bins {r_['Opto-DA'][1].min():.4f}; control smallest Holm P {r_['control'][1].min():.4f}")
# Variant: stimulation minus catch per experiment, compared between the arms (Opto-DA against control), which
# share the imbalance of trial counts; two-sided Mann-Whitney U per bin, Holm over bins; all trials and matched counts
for nm, E_ in [("all trials", E25), ("matched counts, claim seed", E25m)]:
    ps, fs, meds = [], [], []
    for b in range(NB):
        P_ = E_.pivot_table(index=["i", "arm"], columns="stim", values=f"ent_{b}").dropna().reset_index()
        P_["d"] = P_[True] - P_[False]
        a = P_[P_.arm == "Opto-DA"].d; c = P_[P_.arm == "control"].d
        U, f, p = mwu(a, c, "two-sided")
        ps.append(p); fs.append(f); meds.append(a.median() - c.median())
    print(f"between arms, {nm} ({len(a)} Opto-DA and {len(c)} control experiments): f per bin {np.round(fs, 2).tolist()}; "
          f"P (Holm) per bin {np.round(M.holm(ps), 4).tolist()}")
Opto-DA: experiments 236; stim minus catch, median entropy change per bin [0.07, 0.026, 0.022, 0.052, 0.034, 0.045, 0.054, 0.029, 0.052, 0.039]
   f per bin [0.57, 0.57, 0.57, 0.61, 0.58, 0.6, 0.62, 0.58, 0.61, 0.59]
   P (Holm) per bin [0.0171, 0.0165, 0.0171, 0.0002, 0.0165, 0.0024, 0.0, 0.0165, 0.0005, 0.0029]
control: experiments 141; stim minus catch, median entropy change per bin [0.04, 0.03, 0.016, -0.003, 0.01, 0.041, 0.017, 0.022, 0.018, 0.021]
   f per bin [0.53, 0.57, 0.55, 0.51, 0.55, 0.58, 0.56, 0.54, 0.56, 0.57]
   P (Holm) per bin [0.781, 0.4414, 0.6808, 0.781, 0.6808, 0.2219, 0.6808, 0.6808, 0.6808, 0.3655]
trials per experiment, stimulation and catch, before matching: {False: 20.0, True: 58.0} ; after: {False: 20.0, True: 20.0}
matched counts, Opto-DA: f per bin [0.46, 0.51, 0.52, 0.55, 0.51, 0.54, 0.54, 0.49, 0.56, 0.52]; P (Holm) per bin [0.8618, 1.0, 1.0, 0.6367, 1.0, 0.7781, 0.8618, 1.0, 0.3396, 1.0]
matched counts, control: f per bin [0.46, 0.52, 0.52, 0.49, 0.51, 0.52, 0.51, 0.5, 0.52, 0.53]; P (Holm) per bin [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
matched counts, seed +1000: Opto-DA first-bin f 0.50, Holm P 0.9690, smallest Holm P over bins 0.0109; control smallest Holm P 1.0000
matched counts, seed +2000: Opto-DA first-bin f 0.46, Holm P 1.0000, smallest Holm P over bins 0.7440; control smallest Holm P 0.6137
matched counts, seed +3000: Opto-DA first-bin f 0.47, Holm P 1.0000, smallest Holm P over bins 0.1941; control smallest Holm P 1.0000
matched counts, seed +4000: Opto-DA first-bin f 0.48, Holm P 1.0000, smallest Holm P over bins 0.2959; control smallest Holm P 1.0000
between arms, all trials (236 Opto-DA and 141 control experiments): f per bin [0.52, 0.5, 0.51, 0.57, 0.54, 0.52, 0.56, 0.52, 0.56, 0.52]; P (Holm) per bin [1.0, 1.0, 1.0, 0.1599, 1.0, 1.0, 0.5341, 1.0, 0.5341, 1.0]
between arms, matched counts, claim seed (236 Opto-DA and 141 control experiments): f per bin [0.51, 0.49, 0.5, 0.54, 0.5, 0.52, 0.52, 0.5, 0.54, 0.49]; P (Holm) per bin [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

Result: not reproduced, resting on the comparison with matched trial counts. With all trials, entropy after stimulation is higher than after catch trials in the first five-syllable bin in Opto-DA mice (median difference 0.07 bits, f = 0.57, Holm P = 0.017) and in every later bin, and in no control bin (smallest Holm P 0.22). But stimulation trials outnumber catch trials (median 58 against 20 per experiment), and the pooled plug-in entropy depends on the number of trials. With stimulation trials drawn down to the catch count in each experiment, the Opto-DA first bin has f = 0.46 and Holm P = 0.86 (f 0.46 to 0.50 and Holm P 0.97 to 1.0 under the four further seeds); one later bin reaches Holm P = 0.011 under one seed of five. Compared between the arms, which share the imbalance of trial counts, the per-experiment difference of stimulation minus catch does not differ between Opto-DA and control experiments in any bin, with all trials (f 0.50 to 0.57, Holm P 0.16 to 1.0) or with matched counts (f 0.49 to 0.54, Holm P 1.0).

fig3l-no-kinematic-effect¶

In [11]:
anysig = False
for var in ["vel", "angvel", "hvel", "acc"]:
    res = stim_vs_catch(E25, var, "greater")
    for arm, (p, ph, f) in res.items():
        print(f"{var}, {arm}: min P (Holm) {ph.min():.4f} at bin {ph.argmin()}; f range {f.min():.2f} to {f.max():.2f}")
        if arm == "Opto-DA" and (ph < 0.05).any():
            anysig = True
print("any Opto-DA bin significant (Methods form):", anysig)
# variant: the notebook's values without pre-onset subtraction
for var in ["vel", "angvel", "hvel", "acc"]:
    res = stim_vs_catch(E25, var + "raw", "greater")
    print(f"variant without pre-onset subtraction, {var}: Opto-DA min P (Holm) {res['Opto-DA'][1].min():.4f}; control {res['control'][1].min():.4f}")
# variant: per-mouse tests (the legend's "in any of the mice")
sigm = []
for m, g in E25[E25.arm == "Opto-DA"].groupby("mouse"):
    if g.stim.sum() < 3:
        continue
    for var in ["vel", "angvel", "hvel", "acc"]:
        r_ = stim_vs_catch(g, var, "greater")
        if (r_["Opto-DA"][1] < 0.05).any():
            sigm.append((m, var))
print("per-mouse variant, Opto-DA mice and variables with a significant bin:", sigm)
vel, Opto-DA: min P (Holm) 1.0000 at bin 0; f range 0.47 to 0.52
vel, control: min P (Holm) 1.0000 at bin 0; f range 0.46 to 0.52
angvel, Opto-DA: min P (Holm) 1.0000 at bin 0; f range 0.47 to 0.51
angvel, control: min P (Holm) 0.5409 at bin 0; f range 0.46 to 0.56
hvel, Opto-DA: min P (Holm) 1.0000 at bin 0; f range 0.46 to 0.51
hvel, control: min P (Holm) 1.0000 at bin 0; f range 0.45 to 0.50
acc, Opto-DA: min P (Holm) 1.0000 at bin 0; f range 0.48 to 0.53
acc, control: min P (Holm) 0.7598 at bin 1; f range 0.50 to 0.55
any Opto-DA bin significant (Methods form): False
variant without pre-onset subtraction, vel: Opto-DA min P (Holm) 1.0000; control 1.0000
variant without pre-onset subtraction, angvel: Opto-DA min P (Holm) 1.0000; control 0.6816
variant without pre-onset subtraction, hvel: Opto-DA min P (Holm) 0.9222; control 0.7089
variant without pre-onset subtraction, acc: Opto-DA min P (Holm) 0.1346; control 0.2910
per-mouse variant, Opto-DA mice and variables with a significant bin: []

Result: reproduced. No bin of 2D, angular or height velocity or acceleration differs between stimulation and catch trials in Opto-DA mice (smallest Holm P 1.0 in the Methods' form); the variants without pre-onset subtraction and per mouse find none either.

fig3m-long-stim-velocity¶

In [12]:
res = stim_vs_catch(E3, "vel", "greater")
for arm, (p, ph, f) in res.items():
    g = E3[E3.arm == arm]
    print(f"{arm}: {g.i.nunique()} experiments from {g.mouse.nunique()} mice; P (Holm) per bin {np.round(ph, 4).tolist()}; f {np.round(f, 2).tolist()}")
res_raw = stim_vs_catch(E3, "velraw", "greater")
print("variant without pre-onset subtraction:", {a: np.round(v[1], 4).tolist() for a, v in res_raw.items()})
print("3-s pulsed experiments, trials per experiment entering the test (median, by arm and trial type):")
print(E3.groupby(["arm", "stim"]).n.agg(["median", "sum"]).to_string())
f3 = R[(R.kind == "reinf") & (R.stim == 3.0) & R.sn.isin([1, 2]) & R.arm.isin(["Opto-DA", "control"]) & ~R.exclude].drop_duplicates("i")
lat3 = []
for _, r in f3.iterrows():
    d = SESS[r.i]
    on = np.sort(d["stim_on"])
    def first_after(t):
        k = np.searchsorted(on, t - 1e-3)
        return on[k] - t if k < len(on) else np.inf
    def pulses_within(t):                             # light onsets (pulses) in the 3 s after a detection
        return np.sum((on >= t - 1e-3) & (on < t + 3))
    sd, cd = d["det_time"][d["det_stim"]], d["det_time"][~d["det_stim"]]
    lat3.append(dict(arm=r.arm, light_onsets=len(on), stim_det=len(sd), catch_det=len(cd),
                     stim_first_light=np.median([first_after(t) for t in sd]) if len(sd) else np.nan,
                     stim_pulses_3s=np.median([pulses_within(t) for t in sd]) if len(sd) else np.nan,
                     catch_pulses_3s=np.median([pulses_within(t) for t in cd]) if len(cd) else np.nan))
lat3 = pd.DataFrame(lat3)
print("3-s files, per file: light onsets (25-Hz pulses), stimulated and catch detections, the median time from a")
print("stimulated detection to the next light onset (s), and the median number of pulses in the 3 s after a stimulated")
print("and after a catch detection; medians over files by arm:")
print(lat3.groupby("arm").agg(files=("arm", "size"), light_onsets=("light_onsets", "median"), stim_det=("stim_det", "median"),
                              catch_det=("catch_det", "median"), stim_first_light=("stim_first_light", "median"),
                              stim_first_light_max=("stim_first_light", "max"), stim_pulses_3s=("stim_pulses_3s", "median"),
                              catch_pulses_3s=("catch_pulses_3s", "median")).to_string())
Opto-DA: 36 experiments from 3 mice; P (Holm) per bin [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]; f [0.44, 0.55, 0.48, 0.43, 0.43, 0.48, 0.49, 0.44, 0.49, 0.45]
control: 24 experiments from 2 mice; P (Holm) per bin [0.3724, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]; f [0.65, 0.58, 0.54, 0.55, 0.58, 0.55, 0.59, 0.55, 0.49, 0.51]
variant without pre-onset subtraction: {'Opto-DA': [1.0, 0.7712, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.9978, 1.0], 'control': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}
3-s pulsed experiments, trials per experiment entering the test (median, by arm and trial type):
               median   sum
arm     stim               
Opto-DA False    21.5  1568
        True     35.0  2335
control False    18.5   823
        True     33.5  1202
3-s files, per file: light onsets (25-Hz pulses), stimulated and catch detections, the median time from a
stimulated detection to the next light onset (s), and the median number of pulses in the 3 s after a stimulated
and after a catch detection; medians over files by arm:
         files  light_onsets  stim_det  catch_det  stim_first_light  stim_first_light_max  stim_pulses_3s  catch_pulses_3s
arm                                                                                                                       
Opto-DA     36        2662.5      35.5       22.0               0.0                   0.0            75.0              0.0
control     24        2512.5      33.5       18.5               0.0                   0.0            75.0              0.0

Result: not reproduced. In the 36 3-s pulsed experiments of the 3 Opto-DA mice, 2D velocity after stimulation does not exceed catch trials in any bin (Holm P 1.0 in every bin; f 0.43 to 0.55). The light did follow the stimulated detections: the first pulse comes 0 s after a stimulated detection (median and maximum over files), with a median of 75 pulses in the next 3 s, and none after catch detections; a median of 35 stimulation and 21.5 catch trials per experiment entered the test.

fig3jk-post-predictable¶

"In the experiments after stimulation, sequences around the target become more predictable; the most likely transitions into and out of the target become more likely."

In [13]:
def trans_counts(idx, tg, inbound):
    c = {}
    for i in idx:
        lab = SESS[i]["inst"].label.to_numpy()
        if inbound:
            other = lab[:-1][lab[1:] == tg]
        else:
            other = lab[1:][lab[:-1] == tg]
        for k, n in zip(*np.unique(other, return_counts=True)):
            c[k] = c.get(k, 0) + n
    return c

NR = 10                                             # ranks kept (a standard choice; the top rank decides)
def rank_rows(day_col, inbound):
    rows_ = []
    for _, r in T3.iterrows():
        who = "learner" if r.mouse in LEARN else ("control" if r.arm == "control" else None)
        if who is None or len(r[day_col]) == 0:
            continue
        b = trans_counts(r.base_i, r.target, inbound)
        order = sorted(b, key=lambda k: -b[k])[:NR]
        if len(order) < NR:
            continue
        p = trans_counts(r[day_col], r.target, inbound)
        x = np.array([p.get(k, 0) + 1 for k in order], float)
        x = pd.Series(x).rolling(5, center=True, min_periods=1).mean().to_numpy()
        rows_.append((who, x))
    return rows_

rng = rng_for("fig3jk-post-predictable")
for day_col, label in [("post_i", "post-stimulation day"), ("stim_i", "variant, stimulation day")]:
    for inbound in [True, False]:
        rr_ = rank_rows(day_col, inbound)
        L_ = np.array([x for w, x in rr_ if w == "learner"]); C_ = np.array([x for w, x in rr_ if w == "control"])
        ratio = np.log2(L_.mean(0) / C_.mean(0))
        boot = np.array([np.log2(L_[rng.integers(0, len(L_), len(L_))].mean(0)[0] / C_[rng.integers(0, len(C_), len(C_))].mean(0)[0])
                         for _ in range(1000)])
        lo, hi = np.percentile(boot, [2.5, 97.5])
        print(f"{label}, {'inbound' if inbound else 'outbound'}: {len(L_)} learner and {len(C_)} control pairs; "
              f"log2 ratio at the top rank {ratio[0]:.3f} (95% bootstrap {lo:.3f} to {hi:.3f}); ranks 1-5 {np.round(ratio[:5], 3).tolist()}")
for k in [1000, 2000, 3000, 4000]:
    rg = rng_for("fig3jk-post-predictable", k)
    ci = []
    for inbound in [True, False]:
        rr_ = rank_rows("post_i", inbound)
        L_ = np.array([x for w, x in rr_ if w == "learner"]); C_ = np.array([x for w, x in rr_ if w == "control"])
        boot = np.array([np.log2(L_[rg.integers(0, len(L_), len(L_))].mean(0)[0] / C_[rg.integers(0, len(C_), len(C_))].mean(0)[0])
                         for _ in range(1000)])
        ci.append(np.round(np.percentile(boot, [2.5, 97.5]), 3).tolist())
    print(f"post-stimulation day, seed +{k}: 95% intervals inbound {ci[0]}, outbound {ci[1]}")
post-stimulation day, inbound: 42 learner and 68 control pairs; log2 ratio at the top rank 0.374 (95% bootstrap -0.048 to 0.773); ranks 1-5 [0.374, 0.382, 0.369, 0.305, 0.306]
post-stimulation day, outbound: 41 learner and 67 control pairs; log2 ratio at the top rank 0.234 (95% bootstrap -0.127 to 0.546); ranks 1-5 [0.234, 0.249, 0.25, 0.198, 0.289]
variant, stimulation day, inbound: 42 learner and 68 control pairs; log2 ratio at the top rank 0.443 (95% bootstrap 0.043 to 0.809); ranks 1-5 [0.443, 0.438, 0.416, 0.389, 0.37]
variant, stimulation day, outbound: 41 learner and 67 control pairs; log2 ratio at the top rank 0.508 (95% bootstrap 0.180 to 0.820); ranks 1-5 [0.508, 0.453, 0.44, 0.335, 0.372]
post-stimulation day, seed +1000: 95% intervals inbound [-0.049, 0.774], outbound [-0.112, 0.546]
post-stimulation day, seed +2000: 95% intervals inbound [-0.027, 0.764], outbound [-0.069, 0.554]
post-stimulation day, seed +3000: 95% intervals inbound [-0.055, 0.762], outbound [-0.109, 0.566]
post-stimulation day, seed +4000: 95% intervals inbound [-0.045, 0.743], outbound [-0.097, 0.549]

Result: not reproduced. On the post-stimulation day the top-ranked inbound and outbound transitions are more frequent in learners than in controls (log2 ratios 0.374 and 0.234), but both 95% bootstrap intervals include 0 (-0.048 to 0.773 and -0.127 to 0.546), as they do under each of the four further seeds. Only the stimulation-day variant (the Fig. 3k legend's wording) has both intervals above 0 (0.443 and 0.508).

ed10e-no-duration-change¶

In [14]:
D = E25.pivot_table(index=["mouse", "arm", "target", "sn"], columns="stim", values="dur").dropna().reset_index()
D["diff"] = D[True] - D[False]
D["who"] = np.where(D.mouse.isin(LEARN), "learner", np.where(D.arm == "control", "control", "non-learner"))
ps = []
for sn in [1, 2]:
    a = D[(D.who == "learner") & (D.sn == sn)]["diff"]; b = D[(D.who == "control") & (D.sn == sn)]["diff"]
    U, f, p = mwu(a, b, "two-sided"); ps.append(p)
    print(f"stimulation experiment {sn}: learner pairs {len(a)}, control pairs {len(b)}; median stim - catch duration "
          f"{a.median()*1000:.1f} ms against {b.median()*1000:.1f} ms; U = {U:.0f}, f = {f:.2f}, P = {p:.3f}")
print("Holm-corrected:", np.round(M.holm(ps), 3))
stimulation experiment 1: learner pairs 42, control pairs 72; median stim - catch duration 6.4 ms against 3.8 ms; U = 1525, f = 0.50, P = 0.941
stimulation experiment 2: learner pairs 42, control pairs 69; median stim - catch duration -0.8 ms against 23.8 ms; U = 1352, f = 0.47, P = 0.557
Holm-corrected: [1. 1.]

Result: reproduced. The stimulated minus catch duration does not differ between learners and controls in either stimulation experiment (P = 0.941 and 0.557; U = 1525 and 1352).

ed10i-no-place-preference¶

In [15]:
def jsd(p, q):
    if p.sum() == 0 or q.sum() == 0:                  # an empty histogram has no distribution
        return np.nan
    p = p / p.sum(); q = q / q.sum(); m_ = (p + q) / 2
    kl = lambda a, b: np.sum(np.where(a > 0, a * np.log2(np.where(a > 0, a, 1) / np.where(b > 0, b, 1)), 0))
    return 0.5 * kl(p, m_) + 0.5 * kl(q, m_)

rr = R[(R.kind == "reinf") & (R.stim == 0.25) & (R.etype == "reinforcement") & R.arm.isin(["Opto-DA", "control"]) & ~R.exclude]
allxy = pd.concat([SESS[i]["inst"][["x", "y"]] for i in rr.i.unique()])
ex = np.nanpercentile(allxy.x, [0.5, 99.5]); ey = np.nanpercentile(allxy.y, [0.5, 99.5])
EX = np.linspace(*ex, 11); EY = np.linspace(*ey, 11)
J = []
for (m, tg), g in rr.groupby(["mouse", "target"]):
    st_ = g[g.sn.isin([1, 2])]; ot = g[~g.sn.isin([1, 2])]
    if len(st_) == 0 or len(ot) == 0:
        continue
    def hist(idx, shared=True):
        xy = pd.concat([SESS[i]["inst"].query("label == @tg")[["x", "y"]] for i in idx]).dropna()
        if shared:
            return np.histogram2d(xy.x, xy.y, [EX, EY])[0]
        return np.histogram2d(xy.x, xy.y, 10)[0]
    J.append(dict(mouse=m, arm=g.arm.iloc[0], target=tg, jsd=jsd(hist(st_.i.unique()), hist(ot.i.unique())),
                  jsd_own=jsd(hist(st_.i.unique(), False), hist(ot.i.unique(), False))))
J = pd.DataFrame(J)
print("pairs with an empty histogram (JSD undefined, left out):", int(J.jsd.isna().sum()), "shared grid,", int(J.jsd_own.isna().sum()), "own edges")
J = J.dropna(subset=["jsd"])
print("arena coordinates of instance onsets by lab group (percentiles 0.5, 50, 99.5):")
for arm, g in rr.groupby(["arm", "group"]):
    xy = pd.concat([SESS[i]["inst"][["x", "y"]] for i in g.i.unique()]).dropna()
    print(f"   {arm}: x {np.percentile(xy.x, [0.5, 50, 99.5]).round(1).tolist()}, y {np.percentile(xy.y, [0.5, 50, 99.5]).round(1).tolist()}")
for col, name in [("jsd", "shared grid"), ("jsd_own", "variant, own bin edges")]:
    a = J[J.arm == "Opto-DA"][col].dropna(); b = J[J.arm == "control"][col].dropna()
    U, f, p = mwu(a, b, "two-sided")
    print(f"target performance, {name}: pairs {len(a)} + {len(b)} = {len(J)}; median JSD {a.median():.3f} against {b.median():.3f}; U = {U:.0f}, f = {f:.2f}, P = {p:.3f}")
    pm_ = J.groupby(["mouse", "arm"])[col].mean().reset_index()
    a = pm_[pm_.arm == "Opto-DA"][col]; b = pm_[pm_.arm == "control"][col]
    U, f, p = mwu(a, b, "two-sided")
    print(f"   by mouse: {len(a)} + {len(b)} mice; U = {U:.0f}, f = {f:.2f}, P = {p:.3f}")
# Experiment-wide (claims file, as amended after the reader's answer): one JSD per mouse between the
# centroids of stimulation days and of other days. Main reading, the code's (fig_s10h, s10i notebook,
# cells 33 and 34): the centroids at the onsets of all syllables. Variants: the centroids of all frames,
# and each histogram's own bin edges.
def hs(xy, shared=True):
    return np.histogram2d(xy[:, 0], xy[:, 1], [EX, EY] if shared else 10)[0]
onsets_xy = lambda idx: pd.concat([SESS[i]["inst"][["x", "y"]] for i in idx]).dropna().to_numpy()
frames_xy = lambda idx: np.concatenate([SESS[i]["pos_all"] for i in idx])
W = []
for m, g in rr.groupby("mouse"):
    st_ = g[g.sn.isin([1, 2])].i.unique(); ot = g[~g.sn.isin([1, 2])].i.unique()
    a_, b_ = onsets_xy(st_), onsets_xy(ot)
    fa, fb = frames_xy(st_), frames_xy(ot)
    W.append(dict(mouse=m, arm=g.arm.iloc[0], n_st=len(st_), n_ot=len(ot), onsets_st=len(a_), onsets_ot=len(b_),
                  frames_st=len(fa), frames_ot=len(fb),
                  jsd=jsd(hs(a_), hs(b_)), jsd_own=jsd(hs(a_, False), hs(b_, False)),
                  jsd_frames=jsd(hs(fa), hs(fb)), jsd_frames_own=jsd(hs(fa, False), hs(fb, False))))
W = pd.DataFrame(W)
print("experiment-wide, sessions and centroids per mouse (min to max): stimulation sessions", W.n_st.min(), "to", W.n_st.max(),
      "; other sessions", W.n_ot.min(), "to", W.n_ot.max(), "; onsets", W.onsets_st.min(), "to", W.onsets_st.max(), "and",
      W.onsets_ot.min(), "to", W.onsets_ot.max(), "; frames", W.frames_st.min(), "to", W.frames_st.max(), "and",
      W.frames_ot.min(), "to", W.frames_ot.max())
for col, name in [("jsd", "onsets of all syllables, shared grid (main reading)"), ("jsd_own", "variant, onsets of all syllables, own bin edges"),
                  ("jsd_frames", "variant, all frames, shared grid"), ("jsd_frames_own", "variant, all frames, own bin edges")]:
    a = W[W.arm == "Opto-DA"][col].dropna(); b = W[W.arm == "control"][col].dropna()
    U, f, p = mwu(a, b, "two-sided")
    print(f"experiment-wide, {name}: {len(a)} + {len(b)} mice; median JSD {a.median():.4f} against {b.median():.4f}; U = {U:.0f}, f = {f:.2f}, P = {p:.3f}")
pairs with an empty histogram (JSD undefined, left out): 2 shared grid, 2 own edges
arena coordinates of instance onsets by lab group (percentiles 0.5, 50, 99.5):
   ('Opto-DA', 'snc-dls-ai32'): x [-388.6, -253.6, -26.6], y [-318.8, -97.4, 51.6]
   ('Opto-DA', 'snc-dls-ai32-jrcamp1a'): x [-389.9, -238.0, -28.2], y [-322.1, -88.8, 53.2]
   ('control', 'ctrl'): x [-385.8, -249.8, -28.7], y [-317.4, -88.2, 50.6]
   ('control', 'snc-dls-ctrl'): x [-388.0, -264.8, -29.1], y [-317.9, -83.1, 50.0]
   ('control', 'vta-nacc-ctrl'): x [-389.6, -256.9, -28.4], y [-321.2, -89.6, 49.7]
target performance, shared grid: pairs 120 + 72 = 192; median JSD 0.149 against 0.176; U = 3813, f = 0.44, P = 0.174
   by mouse: 20 + 12 mice; U = 99, f = 0.41, P = 0.425
target performance, variant, own bin edges: pairs 120 + 72 = 192; median JSD 0.146 against 0.167; U = 3858, f = 0.45, P = 0.216
   by mouse: 20 + 12 mice; U = 115, f = 0.48, P = 0.861
experiment-wide, sessions and centroids per mouse (min to max): stimulation sessions 11 to 14 ; other sessions 18 to 22 ; onsets 28335 to 53836 and 43666 to 85484 ; frames 593977 to 755014 and 969466 to 1186538
experiment-wide, onsets of all syllables, shared grid (main reading): 20 + 12 mice; median JSD 0.0073 against 0.0120; U = 48, f = 0.20, P = 0.005
experiment-wide, variant, onsets of all syllables, own bin edges: 20 + 12 mice; median JSD 0.0094 against 0.0129; U = 62, f = 0.26, P = 0.025
experiment-wide, variant, all frames, shared grid: 20 + 12 mice; median JSD 0.0080 against 0.0139; U = 44, f = 0.18, P = 0.003
experiment-wide, variant, all frames, own bin edges: 20 + 12 mice; median JSD 0.0087 against 0.0169; U = 50, f = 0.21, P = 0.007

Result: not reproduced. Under the amended criterion both of the paper's tests must give P >= 0.05. The target-performance test does: the Jensen-Shannon divergence of target-onset locations between stimulation and other days does not differ between Opto-DA and control pairs (192 pairs, as in the paper; median 0.149 against 0.176, U = 3813, f = 0.44, P = 0.174) or mice (U = 99, P = 0.425), nor with each histogram's own edges (P = 0.216 and 0.861); 2 pairs with an empty histogram are left out. The experiment-wide test, one JSD per mouse over the centroids at the onsets of all syllables (the main reading), differs: Opto-DA divergences are lower than controls' (20 and 12 mice, median 0.0073 against 0.0120, U = 48, f = 0.20, P = 0.005). The variants agree: own bin edges P = 0.025 (f = 0.26), centroids of all frames P = 0.003 (f = 0.18), all frames with own edges P = 0.007 (f = 0.21). The direction is the opposite of a place preference: the Opto-DA mice's positions on stimulation days are closer to their positions on other days than the controls' are. The cause of the difference is not identified. The arena coordinates have the same ranges in every lab group, so a rig difference does not show in them; session and onset counts were not compared between arms. The reader's answer changed the experiment-wide test from the per-mouse mean of the target-onset JSD (P = 0.425) to all syllable onsets, which turns the outcome from reproduced to not reproduced; the round-3 verifier agreed.

ed10d-optoda-vigour¶

"Opto-DA delivered on the fastest (slowest) quartile of target instances makes later instances faster (slower)." Most velocity-modulation files do not state whether the fastest or the slowest quartile was stimulated (sanity cell). This section checks whether the direction can be read from the velocities of the stimulated instances, as asked in verification, and runs the criterion's test on the result.

In [16]:
import re
# The velocity-modulation files: do the target detections fall on instances of the target syllable?
VM = [i for i, d in enumerate(SESS) if "velocity-modulation" in d["path"] and d["det_stim"].sum() > 0
      and int(d["ts_target_syllable"][0]) >= 0]
def vm_hits(i, shift):
    d = SESS[i]; on = d["inst"].onset.to_numpy(); lab = d["inst"].label.to_numpy()
    t = d["det_time"] + shift
    k = np.searchsorted(on, t, side="right") - 1
    ok = (k >= 0) & (t <= on[-1])
    return (lab[k[ok]] == int(d["ts_target_syllable"][0])).sum(), len(t)
print(len(VM), "velocity-modulation files with stimulated detections of a target syllable")
print("detections after the last syllable onset of the file:",
      int(sum((SESS[i]["det_time"] > SESS[i]["inst"].onset.iloc[-1]).sum() for i in VM)), "of", int(sum(len(SESS[i]["det_time"]) for i in VM)))
h0 = np.array([vm_hits(i, 0) for i in VM])
lag_ = [np.median(np.min(np.abs(np.subtract.outer(SESS[i]["stim_on"], SESS[i]["det_time"][SESS[i]["det_stim"]])), 1))
        for i in VM if len(SESS[i]["stim_on"])]
print(f"light onsets: median time to the nearest stimulated detection 0 s in {sum(np.array(lag_) < 1e-3)} of {len(lag_)} files "
      f"(largest {max(lag_):.3f} s); light onsets after the last syllable onset: "
      f"{int(sum((SESS[i]['stim_on'] > SESS[i]['inst'].onset.iloc[-1]).sum() for i in VM))} of {int(sum(len(SESS[i]['stim_on']) for i in VM))}")
print(f"share of detections on an instance of the target, as recorded: {h0[:, 0].sum() / h0[:, 1].sum():.3f}; "
      f"share of instances that are the target: {np.mean([np.mean(SESS[i]['inst'].label == int(SESS[i]['ts_target_syllable'][0])) for i in VM]):.3f}")
# the offset of the detection clock: the shift that puts the most detections, pooled over files, on target
# instances (1-s grid over +-90 min, then 1/30 s around the best)
grid = np.arange(-5400, 5401, 1.0)
tot = np.array([sum(vm_hits(i, s)[0] for i in VM) for s in grid])
fine = np.arange(grid[np.argmax(tot)] - 1, grid[np.argmax(tot)] + 1, 1 / 30)
totf = np.array([sum(vm_hits(i, s)[0] for i in VM) for s in fine])
VSH = fine[np.argmax(totf)]
print(f"best shift of the detection times {VSH:.3f} s: {totf.max() / h0[:, 1].sum():.3f} of detections on target instances")
far = np.abs(grid - VSH) > 2
print(f"   best 1-s shift more than 2 s away: {grid[far][np.argmax(tot[far])]:.0f} s, {tot[far].max() / h0[:, 1].sum():.3f}")
# with the shift, the direction of each file: mean velocity z (within the target's instances of the file) of the
# stimulated instances, positive for stimulation on the fastest quartile, negative on the slowest
VD = []
for i in VM:
    d = SESS[i]; inst = d["inst"]; on = inst.onset.to_numpy(); lab = inst.label.to_numpy(); tg = int(d["ts_target_syllable"][0])
    t = d["det_time"][d["det_stim"]] + VSH
    k = np.searchsorted(on, t, side="right") - 1
    k = np.unique(k[(k >= 0) & (t <= on[-1])])
    k = k[lab[k] == tg]
    v = inst.vel.to_numpy(); tv = v[lab == tg]
    z = (v[k] - np.nanmean(tv)) / np.nanstd(tv)
    m_ = re.search(r"-(up|down)", d["session_description"])
    VD.append(dict(i=i, mouse=d["subject"], description=d["session_description"].strip(), stated=m_.group(1) if m_ else "",
                   n_stim=len(k), stim_vel_z=np.nanmean(z), share_above_q75=np.mean(v[k] > np.nanpercentile(tv, 75)),
                   share_below_q25=np.mean(v[k] < np.nanpercentile(tv, 25))))
VD = pd.DataFrame(VD)
VD["inferred"] = np.where(VD.stim_vel_z > 0, "up", "down")
print(VD.round(2).to_string())
st_ = VD[VD.stated != ""]
print(f"files with a stated direction: {len(st_)}; inferred direction agrees in {(st_.stated == st_.inferred).sum()}")
print("stimulated instance velocity z, files without a stated direction: positive in", int((VD[VD.stated == ""].stim_vel_z > 0).sum()),
      ", negative in", int((VD[VD.stated == ""].stim_vel_z < 0).sum()))
51 velocity-modulation files with stimulated detections of a target syllable
detections after the last syllable onset of the file: 2845 of 3423
light onsets: median time to the nearest stimulated detection 0 s in 51 of 51 files (largest 0.000 s); light onsets after the last syllable onset: 1901 of 2479
share of detections on an instance of the target, as recorded: 0.010; share of instances that are the target: 0.029
best shift of the detection times -2700.033 s: 0.994 of detections on target instances
   best 1-s shift more than 2 s away: -2698 s, 0.134
      i         mouse         description stated  n_stim  stim_vel_z  share_above_q75  share_below_q25 inferred
0     2          5892    Stim session -up     up      34        0.47             0.29             0.00       up
1     3          5892    Stim session -up     up       1       -0.31             0.00             0.00     down
2     4          5894    Stim session -up     up     205        0.37             0.32             0.03       up
3     6          5893    Stim session -up     up      71        0.46             0.31             0.01       up
4     7          5892      Stim session 1             20        0.82             0.55             0.00       up
5     8          5892    Stim session -up     up      23        0.67             0.52             0.04       up
6     9          5894    Stim session -up     up      35        0.46             0.43             0.00       up
7    10          5891    Stim session -up     up      15        0.89             0.67             0.00       up
8    11          5894  Stim session -down   down     101       -0.30             0.10             0.29     down
9    12          5892  Stim session -down   down       5       -0.36             0.00             0.20     down
10   14          5894    Stim session -up     up     114        0.34             0.30             0.04       up
11   15          5894  Stim session -down   down      51       -0.28             0.18             0.33     down
12   16          5892  Stim session -down   down      18       -0.73             0.06             0.61     down
13   17          5894      Stim session 1            172        0.37             0.28             0.02       up
14   18          5893  Stim session -down   down      40       -0.34             0.08             0.28     down
15   19          5893      Stim session 1             37        0.31             0.19             0.03       up
16   20          5893    Stim session -up     up      79        0.13             0.20             0.13       up
17   21          5891  Stim session -down   down       1       -1.27             0.00             1.00     down
18   22          5891      Stim session 1              1        1.48             1.00             0.00       up
19   24          5891  Stim session -down   down       7       -0.88             0.00             0.57     down
20   25          5893  Stim session -down   down       2       -0.15             0.00             0.00     down
21  140  dls-ai32jr-2      Stim session 2             34        0.45             0.38             0.06       up
22  142  dls-ai32jr-2      Stim session 2             22       -0.49             0.00             0.32     down
23  143  dls-ai32jr-3      Stim session 2             43        0.39             0.33             0.02       up
24  144  dls-ai32jr-3      Stim session 1             66        0.48             0.38             0.02       up
25  148  dls-ai32jr-3      Stim session 1             68       -0.26             0.06             0.26     down
26  150  dls-ai32jr-2      Stim session 1             21        0.44             0.43             0.05       up
27  152  dls-ai32jr-2      Stim session 1             29        0.48             0.45             0.03       up
28  155  dls-ai32jr-1      Stim session 2             16       -0.25             0.00             0.12     down
29  156  dls-ai32jr-1      Stim session 1              2        1.31             0.50             0.00       up
30  158  dls-ai32jr-2      Stim session 1             19       -0.42             0.05             0.42     down
31  159  dls-ai32jr-3      Stim session 2            100       -0.31             0.09             0.31     down
32  160  dls-ai32jr-1      Stim session 2              5        1.06             0.60             0.00       up
33  162  dls-ai32jr-3      Stim session 1             67        0.44             0.30             0.01       up
34  163  dls-ai32jr-1      Stim session 2             29        0.45             0.31             0.07       up
35  165  dls-ai32jr-2      Stim session 2             29        0.51             0.45             0.03       up
36  167  dls-ai32jr-5      Stim session 2            100       -0.42             0.09             0.32     down
37  168  dls-ai32jr-3      Stim session 2             62        0.46             0.32             0.00       up
38  169  dls-ai32jr-5      Stim session 2             85        0.51             0.38             0.01       up
39  172  dls-ai32jr-1      Stim session 1              3       -0.86             0.00             0.67     down
40  173  dls-ai32jr-1      Stim session 1              2        1.22             1.00             0.00       up
41  175  dls-ai32jr-5      Stim session 1            123        0.44             0.34             0.02       up
42  176  dls-ai32jr-4      Stim session 1             10        0.68             0.50             0.00       up
43  180  dls-ai32jr-5      Stim session 1            102       -0.19             0.14             0.24     down
44  183  dls-ai32jr-4      Stim session 2             88       -0.21             0.15             0.25     down
45  184  dls-ai32jr-5      Stim session 2             45        0.88             0.49             0.00       up
46  185  dls-ai32jr-4      Stim session 2             34        0.78             0.50             0.00       up
47  186  dls-ai32jr-4      Stim session 1             11        0.72             0.55             0.00       up
48  188  dls-ai32jr-4      Stim session 1             47       -0.13             0.15             0.28     down
49  193  dls-ai32jr-4      Stim session 2              6        0.24             0.17             0.00       up
50  195  dls-ai32jr-5      Stim session 1             65        0.50             0.35             0.00       up
files with a stated direction: 17; inferred direction agrees in 16
stimulated instance velocity z, files without a stated direction: positive in 24 , negative in 10
In [17]:
# ed10d on the files whose direction is stated or inferred. Inclusion (Methods): at least 50 stimulations,
# and target usage (share of instances) during stimulation above the mean of the mouse's files without
# stimulation (the habituation, baseline and recording sessions of its velocity-modulation set; assumption).
NOSTIM = [i for i, d in enumerate(SESS) if "velocity-modulation" in d["path"] and d["det_stim"].sum() == 0]
VD["direction"] = np.where(VD.stated != "", VD.stated, VD.inferred)
def target_usage(i, tg):
    return float(np.mean(SESS[i]["inst"].label == tg))
rows_ = []
for _, r in VD.iterrows():
    d = SESS[r.i]; tg = int(d["ts_target_syllable"][0])
    b = [target_usage(j, tg) for j in NOSTIM if SESS[j]["subject"] == r.mouse]
    inst = d["inst"]; on = inst.onset.to_numpy(); lab = inst.label.to_numpy()
    vz = inst.groupby("label").vel.transform(lambda v: (v - v.mean()) / v.std()).to_numpy()   # within experiment and syllable
    t = d["det_time"][d["det_stim"]] + VSH
    k = np.searchsorted(on, t, side="right") - 1
    k = np.unique(k[(k >= 0) & (t <= on[-1])])
    k = k[lab[k] == tg]
    x = vz[k]
    ref = (x - np.nanmean(x[:15])) / (np.nanstd(x[:15]) + 0.1)        # re-referenced to the first 15 stimulations
    bins = np.digitize(np.arange(len(x)), [15, 30, 45])
    after = [np.nanmean(ref[bins == b_]) for b_ in [1, 2, 3] if (bins == b_).any()]
    rows_.append(dict(i=r.i, mouse=r.mouse, direction=r.direction, stated=r.stated != "", n_stim=len(k),
                      usage=target_usage(r.i, tg), base_usage=np.mean(b) if b else np.nan, n_base=len(b),
                      value=np.nanmean(after) if after else np.nan))
VX = pd.DataFrame(rows_)
VX["included"] = (VX.n_stim >= 50) & (VX.usage > VX.base_usage)
print(VX.round(3).to_string())
print("included experiments by direction and mouse:")
print(VX[VX.included].groupby(["direction", "mouse"]).size().to_string())
for nm, sel in [("criterion's inclusion", VX.included), ("at least 50 stimulations, usage rule dropped", VX.n_stim >= 50),
                ("criterion's inclusion, stated directions only", VX.included & VX.stated)]:
    a = VX[sel & (VX.direction == "up")].value.dropna(); b = VX[sel & (VX.direction == "down")].value.dropna()
    if len(a) and len(b):
        U, f, p = mwu(a, b, "two-sided")
        print(f"{nm}: {len(a)} up and {len(b)} down experiments ({VX[sel].mouse.nunique()} mice); medians {a.median():.2f} and {b.median():.2f}; "
              f"U = {U:.0f} (max {len(a) * len(b)}), f = {f:.2f}, P = {p:.3f}")
    else:
        print(f"{nm}: {len(a)} up and {len(b)} down experiments, no test")
      i         mouse direction  stated  n_stim  usage  base_usage  n_base  value  included
0     2          5892        up    True      34  0.023       0.018       4  0.075     False
1     3          5892        up    True       1  0.012       0.018       4    NaN     False
2     4          5894        up    True     205  0.066       0.039       4  0.621      True
3     6          5893        up    True      71  0.032       0.019       5  0.419      True
4     7          5892        up   False      20  0.016       0.018       4  1.033     False
5     8          5892        up    True      23  0.015       0.018       4  0.428     False
6     9          5894        up    True      35  0.030       0.039       4 -0.392     False
7    10          5891        up    True      15  0.014       0.008       6    NaN     False
8    11          5894      down    True     101  0.064       0.039       4 -0.083      True
9    12          5892      down    True       5  0.014       0.018       4    NaN     False
10   14          5894        up    True     114  0.045       0.039       4  0.233      True
11   15          5894      down    True      51  0.036       0.039       4  0.246     False
12   16          5892      down    True      18  0.017       0.018       4  0.246     False
13   17          5894        up   False     172  0.069       0.039       4  0.660      True
14   18          5893      down    True      40  0.027       0.019       5  0.634     False
15   19          5893        up   False      37  0.027       0.019       5  0.604     False
16   20          5893        up    True      79  0.033       0.019       5  0.318      True
17   21          5891      down    True       1  0.003       0.008       6    NaN     False
18   22          5891        up   False       1  0.002       0.008       6    NaN     False
19   24          5891      down    True       7  0.006       0.008       6    NaN     False
20   25          5893      down    True       2  0.010       0.019       5    NaN     False
21  140  dls-ai32jr-2        up   False      34  0.024       0.021       4 -0.999     False
22  142  dls-ai32jr-2      down   False      22  0.031       0.021       4 -0.212     False
23  143  dls-ai32jr-3        up   False      43  0.031       0.029       4 -0.030     False
24  144  dls-ai32jr-3        up   False      66  0.035       0.029       4 -0.048      True
25  148  dls-ai32jr-3      down   False      68  0.042       0.029       4 -0.300      True
26  150  dls-ai32jr-2        up   False      21  0.018       0.021       4  0.041     False
27  152  dls-ai32jr-2        up   False      29  0.030       0.021       4 -0.234     False
28  155  dls-ai32jr-1      down   False      16  0.020       0.018       4  0.557     False
29  156  dls-ai32jr-1        up   False       2  0.011       0.018       4    NaN     False
30  158  dls-ai32jr-2      down   False      19  0.019       0.021       4 -0.416     False
31  159  dls-ai32jr-3      down   False     100  0.056       0.029       4 -0.523      True
32  160  dls-ai32jr-1        up   False       5  0.007       0.018       4    NaN     False
33  162  dls-ai32jr-3        up   False      67  0.044       0.029       4 -0.114      True
34  163  dls-ai32jr-1        up   False      29  0.026       0.018       4  0.664     False
35  165  dls-ai32jr-2        up   False      29  0.021       0.021       4  0.396     False
36  167  dls-ai32jr-5      down   False     100  0.050       0.036       4  0.106      True
37  168  dls-ai32jr-3        up   False      62  0.056       0.029       4  0.596      True
38  169  dls-ai32jr-5        up   False      85  0.052       0.036       4 -0.010      True
39  172  dls-ai32jr-1      down   False       3  0.011       0.018       4    NaN     False
40  173  dls-ai32jr-1        up   False       2  0.012       0.018       4    NaN     False
41  175  dls-ai32jr-5        up   False     123  0.048       0.036       4  0.339      True
42  176  dls-ai32jr-4        up   False      10  0.014       0.026       4    NaN     False
43  180  dls-ai32jr-5      down   False     102  0.041       0.036       4 -0.138      True
44  183  dls-ai32jr-4      down   False      88  0.051       0.026       4  1.023      True
45  184  dls-ai32jr-5        up   False      45  0.032       0.036       4  0.594     False
46  185  dls-ai32jr-4        up   False      34  0.028       0.026       4  0.640     False
47  186  dls-ai32jr-4        up   False      11  0.021       0.026       4    NaN     False
48  188  dls-ai32jr-4      down   False      47  0.029       0.026       4 -0.157     False
49  193  dls-ai32jr-4        up   False       6  0.014       0.026       4    NaN     False
50  195  dls-ai32jr-5        up   False      65  0.044       0.036       4 -0.330      True
included experiments by direction and mouse:
direction  mouse       
down       5894            1
           dls-ai32jr-3    2
           dls-ai32jr-4    1
           dls-ai32jr-5    2
up         5893            2
           5894            3
           dls-ai32jr-3    3
           dls-ai32jr-5    3
criterion's inclusion: 11 up and 6 down experiments (5 mice); medians 0.32 and -0.11; U = 47 (max 66), f = 0.71, P = 0.180
at least 50 stimulations, usage rule dropped: 11 up and 7 down experiments (5 mice); medians 0.32 and -0.08; U = 53 (max 77), f = 0.69, P = 0.211
criterion's inclusion, stated directions only: 4 up and 1 down experiments (2 mice); medians 0.37 and -0.08; U = 4 (max 4), f = 1.00, P = 0.400

Result: not reproduced (assumed); the test runs once the detection clock is corrected. In the velocity-modulation files the target detections are not on the clock of the syllable labels: 2,845 of 3,423 fall after the last syllable onset of their file, and only 1.0% fall on an instance of the target (2.9% of instances are the target); the light onsets coincide with the stimulated detections in all 51 files and 1,901 of 2,479 fall after the last syllable onset. Shifted by -2700.03 s, 99.4% of detections fall on target instances (the best shift more than 2 s away reaches 13.4%). With the shift, the stimulated instances are faster than the file's target instances on average in every file whose description says up and slower in every file that says down, except one file with a single stimulation (16 of 17 agree); in the files without a stated direction they are faster in 24 and slower in 10. With the direction stated or read this way, the criterion's inclusion rule (at least 50 stimulations, target usage above the mean of the mouse's sessions without stimulation, an assumption on the baseline) keeps 11 up and 6 down experiments of 5 mice (the paper has 18 and 12 of 5). Up exceeds down in medians (0.32 against -0.11) but not significantly: U = 47 of 66, f = 0.71, P = 0.180 (paper U = 167, f = 0.77, P = 0.013). Without the usage rule, 11 up and 7 down give U = 53, P = 0.211. The outcome rests on the clock shift, on directions inferred for 12 of the 17 included experiments and on the baseline of the usage rule, so it is marked assumed. The claim was blocked (metadata insufficient) until the round-3 verifier agreed with the change to not reproduced.

ed2a-syllable-repertoire, reading (b)¶

The Opto-DA experiments' offline labels (reinforcement files); the photometry experiments are in photometry.ipynb.

In [18]:
OFF = pd.concat([d["off_inst"].assign(mouse=d["subject"]) for d in SESS if d.get("off_inst") is not None])
dur = OFF.dur.dropna() * 1000
print(f"Opto-DA experiments with offline labels: {sum(d.get('off_inst') is not None for d in SESS)}, mice {OFF.mouse.nunique()}, "
      f"instances {len(OFF)}: median {dur.median():.0f} ms, mean {dur.mean():.0f} ms, s.d. {dur.std():.0f} ms")
use_o = OFF.groupby("mouse").label.value_counts(normalize=True).unstack(fill_value=0).mean(0)
print("syllables with mean usage over these mice > 1%:", int((use_o > 0.01).sum()))
Opto-DA experiments with offline labels: 1340, mice 33, instances 2816125: median 467 ms, mean 651 ms, s.d. 697 ms
syllables with mean usage over these mice > 1%: 35
/tmp/ipykernel_3350/3317630684.py:5: Pandas4Warning: Starting with pandas version 4.0 all arguments of mean will be keyword-only.
  use_o = OFF.groupby("mouse").label.value_counts(normalize=True).unstack(fill_value=0).mean(0)

Result: reading (b) only in part, not decided here. The offline labels of the 1,340 Opto-DA experiments give a median duration of 467 ms and a mean of 651 ms, outside the tolerances; 35 syllables pass 1%. The claim is decided in photometry.ipynb under reading (a).

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
fig3e-optoda-learning not reproduced (P = 0.110)
fig3f-cumulative-counts not reproduced (P = 0.062)
fig3e-learner-count not reproduced (7 learners, all among the paper's 9)
fig3h-stim-post-correlation partially reproduced (controls also significant)
fig3i-optoda-entropy not reproduced (no effect with matched trial counts, nor between arms)
fig3l-no-kinematic-effect reproduced
fig3m-long-stim-velocity not reproduced
ed10e-no-duration-change reproduced
ed10i-no-place-preference not reproduced (experiment-wide test over all syllable onsets, P = 0.005, Opto-DA lower)
fig3jk-post-predictable not reproduced (post-day intervals include 0)
ed10d-optoda-vigour not reproduced (P = 0.180; detection clock corrected, direction read from the data for most files; assumed)
ed10-target-specific blocked (not run)

How the analysis differs from the paper's: target counts are run-length instances of the online labels in the first 30 min of each experiment; the baseline is the target's own -1 and 0 sessions on the most recent day before stimulation (the TargetSessions table); trial measures align each online detection to the instance it falls in; sequence entropy is the conditional entropy of pooled transitions with a Perks prior, compared with stimulation trials drawn down to the catch count (an assumption); the place-preference grid spans the 0.5 to 99.5 percentiles of all positions at syllable onsets.

What was found about the dataset: the OptogeneticSeries description says onsets are recorded as 1, but the values are the power, 0.01 W; the stimulated share of detections is 0.707 where the Methods give 75%; the online target detections fall inside an instance of the target label in a median 99.7% of cases, and in 7 to 40% with the detections shifted, consistent with a shared clock; in the 3-s pulsed files each stimulation is a train of 25-Hz pulses whose first pulse coincides with the stimulated detection; the velocity-modulation files state the direction of stimulation (up or down) only in the session descriptions of mice 5891 to 5894, and not for the five dls-ai32jr mice; in the velocity-modulation files the target detections and light onsets are 2700.03 s later than the syllable labels' clock, so that most fall after the end of the session as recorded.