Reproducing Martel et al. (2025) from dandiset 001174: sequences of calcium events (Figure 4)¶

Paper. Martel A-C et al. (2025), iScience 28, 112767, doi:10.1016/j.isci.2025.112767; claims file claims/001174/10.1016-j.isci.2025.112767.yaml, written from the version of record (Europe PMC, PMC12192352) without the supplement.

Dandiset. DANDI:001174, version 0.250331.2218, the version the paper cites and the only published one (see the first notebook, reproduce_martel_2025.ipynb, for the data check and the choice of version).

Method. Method S of the claims file, a port of the paper's identify_sequences.m (Zenodo doi:10.5281/zenodo.14963234) in sequences.py, run on the dandiset's deconvolved events. Events are 2 to 5 events of different cells, each within 2 s of the one before (Methods, "Determination of precisely timed sequences"); kept when repeated at least 4 times in 10 min (Methods), above the 0.95 centile of 1000 circularly shifted shuffles (Methods; the code's centile). The claims file names the readings the paper leaves open, all run here:

  • the two 0.05 s rules, reading (a) both, (b) a 0.05 s minimum between successive events of a sequence only, (c) a 0.05 s minimum between the starts of repetitions only;
  • which 10 min of the task: (i) the first 10 min, (ii) the last 10 min (spontaneous: the first 10 min, and the next 10 min where it lasts 20 min);
  • variants: the code's rule of more than 4 repetitions, single-cell repeats included, every ordering of the cells (reading a only, for the example sessions), and the double-counting step as its comments describe it.

To see whether any setting of the detection gives the paper's own outputs, the port is also run under a sweep of the window's upper bound (0.25 to 2 s) and of the separation of repetitions (0.05 to 2 s), with both double-counting steps, and compared with the paper's Figure 4D table session by session.

The main count uses the double-counting step as the code runs it: the step marks used events by writing 2 into a logical array, which MATLAB stores as true, so its test for 2 never succeeds and no repetition is removed (see sequences.py). The claims file says "double counting removed as the code does"; the documented step is shown as a variant.

Claim Tested here
fig4a-example-sequences-q tested; blocked: methods underspecified
fig4b-example-three-segments-q tested; blocked: methods underspecified
fig4d-sequence-measures-vary tested
fig4c-sequence-cells-not-clustered tested
In [1]:
import time
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import sma_m1 as h
import sequences as sq

pd.set_option("display.width", 200)
print("dandiset", h.DANDISET, "version", h.VERSION)
files = h.load_all()
files = [x for x in files if not (x["subject"] == "F" and x["date"] == "2024-03-19")]
print(len(files), "files (F 2024-03-19, one cell, is left out, as the Jaccard code leaves it out)")
dandiset 001174 version 0.250331.2218
44 files (F 2024-03-19, one cell, is left out, as the Jaccard code leaves it out)

Data check¶

Per file, the events the sequence search uses: cells with any event, events, and the 10-min slices.

In [2]:
rows = []
for x in files:
    times, keep = sq.event_times(x)
    for tr in (["i", "ii"] if x["condition"] == "task" else ["i"]):
        for name, ts in sq.segments(x, tr):
            n_ev = sum(((t > ts[0]) & (t <= ts[1])).sum() for t in times)
            rows.append({"subject": x["subject"], "region": x["region"], "date": x["date"], "condition": x["condition"],
                         "task_reading": tr, "segment": name, "start_s": round(ts[0], 1), "end_s": round(ts[1], 1),
                         "cells": x["events"].shape[1], "cells_with_events": len(keep), "events": int(n_ev)})
seg = pd.DataFrame(rows)
print(seg.to_string())
print("segments:", len(seg), "| shorter than 10 min:", int(((seg.end_s - seg.start_s) < 599).sum()))
   subject region        date    condition task_reading segment  start_s   end_s  cells  cells_with_events  events
0        F    SMA  2024-02-13  spontaneous            i      S1      0.0   600.0      6                  6     144
1        F    SMA  2024-02-20  spontaneous            i      S1      0.0   600.0     16                 16    1459
2        F    SMA  2024-02-20  spontaneous            i      S2    600.0  1200.0     16                 16    1376
3        F    SMA  2024-02-23  spontaneous            i      S1      0.0   600.0     15                 15    1320
4        F    SMA  2024-02-23  spontaneous            i      S2    600.0  1200.0     15                 15    1426
5        F    SMA  2024-02-27  spontaneous            i      S1      0.0   600.0     14                 14    1083
6        F    SMA  2024-02-27  spontaneous            i      S2    600.0  1200.0     14                 14    1061
7        F    SMA  2024-02-29  spontaneous            i      S1      0.0   600.0     14                 14    1414
8        F    SMA  2024-02-29  spontaneous            i      S2    600.0  1200.0     14                 14    1446
9        F    SMA  2024-03-05  spontaneous            i      S1      0.0   600.0     12                 12     713
10       F    SMA  2024-03-05  spontaneous            i      S2    600.0  1200.0     12                 12     599
11       F    SMA  2024-03-07  spontaneous            i      S1      0.0   600.0      6                  6     352
12       F    SMA  2024-03-07  spontaneous            i      S2    600.0  1200.0      6                  6     499
13       F    SMA  2024-03-12  spontaneous            i      S1      0.0   600.0      4                  4     181
14       Q    SMA  2022-09-15  spontaneous            i      S1      0.0   600.0     40                 36    1418
15       Q    SMA  2022-09-15         task            i      RT      0.0   600.0     40                 39    1472
16       Q    SMA  2022-09-15         task           ii      RT    303.7   903.7     40                 39    1305
17       Q    SMA  2022-09-22  spontaneous            i      S1      0.0   600.0     38                 36    1826
18       Q    SMA  2022-09-22         task            i      RT      0.0   600.0     38                 36    1289
19       Q    SMA  2022-09-22         task           ii      RT    608.3  1208.3     38                 36    1191
20       Q    SMA  2022-10-03  spontaneous            i      S1      0.0   600.0     18                 15     165
21       Q    SMA  2022-10-03  spontaneous            i      S2    600.0  1200.0     18                 15     338
22       Q    SMA  2022-10-03         task            i      RT      0.0   600.0     18                 16     384
23       Q    SMA  2022-10-03         task           ii      RT    605.3  1205.3     18                 16     362
24       Q    SMA  2022-10-28  spontaneous            i      S1      0.0   600.0     21                 20     356
25       Q    SMA  2022-10-28  spontaneous            i      S2    600.0  1200.0     21                 20     286
26       Q    SMA  2022-10-28         task            i      RT      0.0   600.0     21                 21     471
27       Q    SMA  2022-10-28         task           ii      RT    261.3   861.3     21                 21     496
28       Q    SMA  2022-12-01  spontaneous            i      S1      0.0   600.0     13                 10     673
29       Q    SMA  2022-12-01  spontaneous            i      S2    600.0  1200.0     13                 10     964
30       Q    SMA  2022-12-01         task            i      RT      0.0   600.0     13                 12     792
31       Q    SMA  2022-12-01         task           ii      RT     44.7   644.7     13                 12     776
32       Q    SMA  2022-12-02  spontaneous            i      S1      0.0   600.0     12                 12    1280
33       Q    SMA  2022-12-02  spontaneous            i      S2    600.0  1200.0     12                 12     537
34       Q    SMA  2022-12-02         task            i      RT      0.0   600.0     12                 12     661
35       Q    SMA  2022-12-02         task           ii      RT    101.0   701.0     12                 12     636
36       Q    SMA  2022-12-06  spontaneous            i      S1      0.0   600.0     18                 18    2360
37       Q    SMA  2022-12-06  spontaneous            i      S2    600.0  1200.0     18                 18    2238
38       Q    SMA  2022-12-06         task            i      RT      0.0   600.0     18                 14    2221
39       Q    SMA  2022-12-06         task           ii      RT     93.7   693.7     18                 14    2190
40       U     M1  2023-02-24  spontaneous            i      S1      0.0   600.0      8                  8    2542
41       U     M1  2023-02-24  spontaneous            i      S2    600.0  1200.0      8                  8    1542
42       U     M1  2023-02-24         task            i      RT      0.0   474.4      8                  8    1298
43       U     M1  2023-02-24         task           ii      RT      0.0   474.4      8                  8    1298
44       U    SMA  2023-02-27  spontaneous            i      S1      0.0   600.0     16                 14     466
45       U    SMA  2023-02-27  spontaneous            i      S2    600.0  1200.0     16                 14     378
46       U    SMA  2023-02-27         task            i      RT      0.0   600.0     16                 14     401
47       U    SMA  2023-02-27         task           ii      RT    131.3   731.3     16                 14     402
48       U     M1  2023-03-01  spontaneous            i      S1      0.0   600.0     21                 21    3514
49       U     M1  2023-03-01  spontaneous            i      S2    600.0  1200.0     21                 21    2393
50       U     M1  2023-03-01         task            i      RT      0.0   599.5     21                 20    2732
51       U     M1  2023-03-01         task           ii      RT      0.0   599.5     21                 20    2732
52       U    SMA  2023-03-07  spontaneous            i      S1      0.0   600.0     10                  8      34
53       U    SMA  2023-03-07  spontaneous            i      S2    600.0  1200.0     10                  8       0
54       U    SMA  2023-03-07         task            i      RT      0.0   600.0     10                 10     233
55       U    SMA  2023-03-07         task           ii      RT    330.4   930.4     10                 10     266
56       U    SMA  2023-03-14  spontaneous            i      S1      0.0   600.0     20                 17     108
57       U    SMA  2023-03-14  spontaneous            i      S2    600.0  1200.0     20                 17      28
58       U    SMA  2023-03-14         task            i      RT      0.0   600.0     20                 13      54
59       U    SMA  2023-03-14         task           ii      RT    235.6   835.6     20                 13      48
60       U     M1  2023-03-16  spontaneous            i      S1      0.0   301.7      8                  6     311
61       U     M1  2023-03-16         task            i      RT      0.0   600.0      8                  8    1114
62       U     M1  2023-03-16         task           ii      RT    556.4  1156.4      8                  8     945
63       U    SMA  2023-03-21  spontaneous            i      S1      0.0   600.0     25                 22     289
64       U    SMA  2023-03-21  spontaneous            i      S2    600.0  1200.0     25                 22     261
65       U    SMA  2023-03-21         task            i      RT      0.0   600.0     25                 22     345
66       U    SMA  2023-03-21         task           ii      RT     76.7   676.7     25                 22     324
67       U     M1  2023-03-23  spontaneous            i      S1      0.0   600.0      6                  6     877
68       U     M1  2023-03-23  spontaneous            i      S2    600.0  1200.0      6                  6     843
69       U     M1  2023-03-23         task            i      RT      0.0   600.0      6                  6     742
70       U     M1  2023-03-23         task           ii      RT    170.6   770.6      6                  6     614
71       U    SMA  2023-03-28  spontaneous            i      S1      0.0   600.0     14                 12      73
72       U    SMA  2023-03-28  spontaneous            i      S2    600.0  1200.0     14                 12     154
73       U    SMA  2023-03-28         task            i      RT      0.0   600.0     14                 14     142
74       U    SMA  2023-03-28         task           ii      RT    149.3   749.3     14                 14     124
75       V     M1  2023-03-09  spontaneous            i      S1      0.0   600.0     11                 11     678
76       V     M1  2023-03-09  spontaneous            i      S2    600.0  1200.0     11                 11     465
77       V     M1  2023-03-09         task            i      RT      0.0   518.2     11                  9     455
78       V     M1  2023-03-09         task           ii      RT      0.0   518.2     11                  9     455
79       V     M1  2023-03-16  spontaneous            i      S1      0.0   600.0     14                 13    1787
80       V     M1  2023-03-16  spontaneous            i      S2    600.0  1200.0     14                 13    2047
81       V     M1  2023-03-16         task            i      RT      0.0   498.1     14                 11    1358
82       V     M1  2023-03-16         task           ii      RT      0.0   498.1     14                 11    1358
segments: 83 | shorter than 10 min: 7
In [3]:
# The double-counting step of identify_sequences.m (Zenodo doi:10.5281/zenodo.14963234), printed so
# that the port's reading of it can be checked. DA is created as a logical array (false), the step
# marks used events by writing 2 into it and drops an occurrence when an event already holds 2.
# MATLAB converts a value assigned into a logical array to logical, so 2 is stored as true (1), the
# test == 2 is never met, and no occurrence is dropped (sequences.py, dedupe="code").
import hashlib, urllib.request
with urllib.request.urlopen("https://zenodo.org/api/records/14963234/files/identify_sequences.m/content") as r:
    msrc = r.read()
print("identify_sequences.m md5", hashlib.md5(msrc).hexdigest())
mlines = msrc.decode("latin-1").splitlines()
for a, b in ((174, 174), (351, 356), (360, 360), (975, 975), (1019, 1040)):
    for i in range(a, b + 1):
        print(f"{i:5d}  {mlines[i - 1]}")
    print("  ...")
identify_sequences.m md5 6fe2a4f0f36ec29b78683d71aed0ef34
  174  NDC = eliminate_double_counting_v2(TA,SA,Q.data.converted_array,min_num_reps);     % this step eliminates double counting of sequences
  ...
  351  DA = false(num_chan,diff(ts));
  352  for i = 1:num_chan
  353      DA(i,data(i).time) = true;
  354  end
  355  
  356  [R.sequence_times,R.sequences] = find_sequences_2_3_4_5(DA,tc,msl,cd,min_num_reps,num_shuffle,ns);       % the find_sequences_2_3_v2 function identifies actual sequences
  ...
  360  R.data.converted_array = DA;
  ...
  975  function NDC = eliminate_double_counting_v2(T,S,DA,num_rep)
  ...
 1019  if ~isempty(ind)
 1020      for i = 1:length(ind)          % for all sequences in descending order of length and recurrence rates ...
 1021          for j = 1:len(ind(i))      % for all individual member of the sequence ...    
 1022              valid_time = ones(size(T{ind(i)}(:,j),1),1);                    % helper variable that refers to recurrence times within T
 1023              if ~isempty(T{ind(i)}(:,j))                                     % should never be empty, but just in case ...    
 1024                  for k = 1:size(T{ind(i)}(:,j),1)                            % for all entries into the relevant T entry
 1025                      % the following steps will identify events that are part of
 1026                      % sequences to '2' and label times that are already identified as part of a
 1027                      % longer sequences as invalid (valid_time is set to 0
 1028                      % for such events)
 1029                      try    
 1030                      if DA(S(ind(i),j),round(T{ind(i)}(k,j)*1000)) == 2
 1031                          valid_time(k) = 0;
 1032                      else
 1033                          DA(S(ind(i),j),round(T{ind(i)}(k,j)*1000)) = 2;
 1034                      end
 1035                      catch
 1036                      end
 1037                  end
 1038              end
 1039              T{ind(i)} = T{ind(i)}(valid_time == 1,:);       % we keep only those time entries that are valid
 1040          end
  ...

Detection on every slice¶

One run per slice and reading of the 0.05 s rules, each with its own seeded generator. The task's reading (ii) reuses reading (i) where the file is 10 min or shorter.

In [4]:
t0 = time.time()
RES = {}
for x in files:
    for tr in (["i", "ii"] if x["condition"] == "task" else ["i"]):
        for name, ts in sq.segments(x, tr):
            for rd in sq.READINGS:
                key = (x["subject"], x["region"], x["date"], x["condition"], tr, name, rd)
                prev = (x["subject"], x["region"], x["date"], x["condition"], "i", name, rd)
                if tr == "ii" and sq.segments(x, "i")[0][1] == ts:
                    RES[key] = RES[prev]
                    continue
                seed = int(pd.util.hash_pandas_object(pd.Series([str(key)])).iloc[0] % 2**32)
                RES[key] = sq.run_segment(x, ts, rd, np.random.default_rng(seed))
print("runs:", len(RES), "in %.0f s" % (time.time() - t0))
runs: 249 in 353 s
In [5]:
def measures(key, **kw):
    sig, info = RES[key]
    x = [f for f in files if (f["subject"], f["region"], f["date"], f["condition"]) == key[:4]][0]
    seqs = sq.finalize(sig, **kw)
    s = sq.summary(seqs, x["events"].shape[1])
    s.update({"candidates": info["candidates"], "passing_reps": info["passing_reps"], "significant": info["significant"]})
    return s, seqs

VARIANTS = {"main": {}, "rule >": {"rule": ">"}, "single-cell": {"single_cell": True}, "documented dedupe": {"dedupe": "documented"}}
allrows = []
for key in RES:
    for vname, kw in VARIANTS.items():
        s, _ = measures(key, **kw)
        allrows.append(dict(zip(["subject", "region", "date", "condition", "task_reading", "segment", "reading"], key), variant=vname, **s))
ALL = pd.DataFrame(allrows)
print(ALL[ALL.variant == "main"].groupby(["reading", "task_reading", "segment"]).agg(
    slices=("n_seq", "size"), median_n_seq=("n_seq", "median"), max_n_seq=("n_seq", "max"),
    median_significant=("significant", "median")).to_string())
                              slices  median_n_seq  max_n_seq  median_significant
reading task_reading segment                                                     
a       i            RT           18          12.5       1423                12.5
                     S1           26          17.0       1048                17.0
                     S2           21           9.0        665                 9.0
        ii           RT           18          14.5       1423                14.5
b       i            RT           18          14.0       1774                15.0
                     S1           26          20.5       1203                21.5
                     S2           21           9.0        813                 9.0
        ii           RT           18          17.0       1774                17.5
c       i            RT           18          15.0       1875                16.0
                     S1           26          19.0       1432                19.0
                     S2           21           9.0        840                 9.0
        ii           RT           18          17.0       1875                18.5

fig4a-example-sequences-q¶

In an example session of monkey Q's SMA with 40 cells, 13 sequences were detected in the spontaneous condition and 17 during the task, and the specific sequences differed between the two even where they involved the same cells.

The sessions of Q's SMA with 40 accepted cells are the candidates (Figure 4A legend).

In [6]:
cand = sorted({(x["date"]) for x in files if x["subject"] == "Q" and x["events"].shape[1] == 40})
print("Q SMA sessions with 40 accepted cells:", cand)
out = []
for d in cand:
    for rd in sq.READINGS:
        for tr in ("i", "ii"):
            for vname, kw in VARIANTS.items():
                ks = ("Q", "SMA", d, "spontaneous", "i", "S1", rd)
                kt = ("Q", "SMA", d, "task", tr, "RT", rd)
                (ms, ss), (mt, st) = measures(ks, **kw), measures(kt, **kw)
                a, b = {s for s, _ in ss}, {s for s, _ in st}
                out.append({"date": d, "reading": rd, "task_reading": tr, "variant": vname, "spont": ms["n_seq"], "task": mt["n_seq"],
                            "shared": len(a & b), "sets_differ": a != b,
                            "within_tol": abs(ms["n_seq"] - 13) <= 1.3 and abs(mt["n_seq"] - 17) <= 1.7})
F4A = pd.DataFrame(out)
print(F4A.to_string())
print("main variant, readings within tolerance:", int(F4A[F4A.variant == "main"].within_tol.sum()), "of", int((F4A.variant == "main").sum()))
Q SMA sessions with 40 accepted cells: ['2022-09-15']
          date reading task_reading            variant  spont  task  shared  sets_differ  within_tol
0   2022-09-15       a            i               main    157   211      10         True       False
1   2022-09-15       a            i             rule >    113   174       9         True       False
2   2022-09-15       a            i        single-cell    157   211      10         True       False
3   2022-09-15       a            i  documented dedupe      5     5       0         True       False
4   2022-09-15       a           ii               main    157   176       4         True       False
5   2022-09-15       a           ii             rule >    113   156       4         True       False
6   2022-09-15       a           ii        single-cell    157   176       4         True       False
7   2022-09-15       a           ii  documented dedupe      5     2       0         True       False
8   2022-09-15       b            i               main    185   311      11         True       False
9   2022-09-15       b            i             rule >    155   260      10         True       False
10  2022-09-15       b            i        single-cell    185   311      11         True       False
11  2022-09-15       b            i  documented dedupe      5     3       0         True       False
12  2022-09-15       b           ii               main    185   237       5         True       False
13  2022-09-15       b           ii             rule >    155   214       5         True       False
14  2022-09-15       b           ii        single-cell    185   237       5         True       False
15  2022-09-15       b           ii  documented dedupe      5     2       0         True       False
16  2022-09-15       c            i               main    196   252      11         True       False
17  2022-09-15       c            i             rule >    138   210       9         True       False
18  2022-09-15       c            i        single-cell    196   252      11         True       False
19  2022-09-15       c            i  documented dedupe      5     4       0         True       False
20  2022-09-15       c           ii               main    196   207       5         True       False
21  2022-09-15       c           ii             rule >    138   181       5         True       False
22  2022-09-15       c           ii        single-cell    196   207       5         True       False
23  2022-09-15       c           ii  documented dedupe      5     3       0         True       False
main variant, readings within tolerance: 0 of 6
In [7]:
# Variant: every ordering of distinct cells (reading a, task reading i).
t0 = time.time()
ALLORD = {}
for d, segs in [("2022-09-15", [("spontaneous", "S1"), ("task", "RT")]),
                ("2022-10-03", [("spontaneous", "S1"), ("spontaneous", "S2"), ("task", "RT")]),
                ("2022-12-06", [("spontaneous", "S1"), ("spontaneous", "S2"), ("task", "RT")])]:
    for c, name in segs:
        x = [f for f in files if (f["subject"], f["date"], f["condition"]) == ("Q", d, c)][0]
        ts = dict(sq.segments(x, "i"))[name]
        sig, info = sq.run_segment(x, ts, "a", np.random.default_rng(7), orders="all")
        ALLORD[(d, c, name)] = {"significant": info["significant"], "main": len(sq.finalize(sig)),
                                "documented dedupe": len(sq.finalize(sig, dedupe="documented"))}
print(pd.DataFrame(ALLORD).T.to_string())
print("in %.0f s" % (time.time() - t0))
                           significant   main  documented dedupe
2022-09-15 spontaneous S1          979    979                  2
           task        RT         1856   1856                  0
2022-10-03 spontaneous S1            3      3                  1
                       S2            6      6                  1
           task        RT           14     14                  1
2022-12-06 spontaneous S1         5173   5169                  5
                       S2        11782  11782                  6
           task        RT         2183   2183                  5
in 136 s

fig4b-example-three-segments-q¶

In another Q SMA session with 18 cells and 20 min of spontaneous recording, 8, 13 and 9 sequences were found in the two spontaneous halves and the task, and the sequences differed between all three segments.

In [8]:
durs = {x["date"]: (x["events"].shape[0] - 1) / x["rate_ea"] / 60 for x in files if x["subject"] == "Q" and x["condition"] == "spontaneous"}
cand_b = sorted(x["date"] for x in files if x["subject"] == "Q" and x["condition"] == "spontaneous" and x["events"].shape[1] == 18 and durs[x["date"]] >= 19.9)
print("Q SMA sessions with 18 cells and 20 min or more of spontaneous recording:", {d: round(durs[d], 1) for d in cand_b})
out = []
for d in cand_b:
    for rd in sq.READINGS:
        for tr in ("i", "ii"):
            for vname, kw in VARIANTS.items():
                r = [measures(("Q", "SMA", d, c, t, s, rd), **kw) for c, t, s in
                     [("spontaneous", "i", "S1"), ("spontaneous", "i", "S2"), ("task", tr, "RT")]]
                sets = [{s for s, _ in q[1]} for q in r]
                n = [q[0]["n_seq"] for q in r]
                out.append({"date": d, "reading": rd, "task_reading": tr, "variant": vname, "S1": n[0], "S2": n[1], "RT": n[2],
                            "shared_S1_S2": len(sets[0] & sets[1]), "shared_S1_RT": len(sets[0] & sets[2]), "shared_S2_RT": len(sets[1] & sets[2]),
                            "shared_all": len(sets[0] & sets[1] & sets[2]),
                            "all_differ": sets[0] != sets[1] and sets[0] != sets[2] and sets[1] != sets[2],
                            "within_tol": abs(n[0] - 8) <= 0.8 and abs(n[1] - 13) <= 1.3 and abs(n[2] - 9) <= 0.9})
F4B = pd.DataFrame(out)
print(F4B.to_string())
print("main variant, readings within tolerance:", int(F4B[F4B.variant == "main"].within_tol.sum()), "of", int((F4B.variant == "main").sum()))
Q SMA sessions with 18 cells and 20 min or more of spontaneous recording: {'2022-10-03': 21.8, '2022-12-06': 20.4}
          date reading task_reading            variant   S1   S2   RT  shared_S1_S2  shared_S1_RT  shared_S2_RT  shared_all  all_differ  within_tol
0   2022-10-03       a            i               main    3    4   12             1             0             0           0        True       False
1   2022-10-03       a            i             rule >    1    3    9             0             0             0           0        True       False
2   2022-10-03       a            i        single-cell    3    4   12             1             0             0           0        True       False
3   2022-10-03       a            i  documented dedupe    1    1    2             0             0             0           0        True       False
4   2022-10-03       a           ii               main    3    4   12             1             1             1           1        True       False
5   2022-10-03       a           ii             rule >    1    3   10             0             0             1           0        True       False
6   2022-10-03       a           ii        single-cell    3    4   12             1             1             1           1        True       False
7   2022-10-03       a           ii  documented dedupe    1    1    3             0             0             0           0        True       False
8   2022-10-03       b            i               main    3    4   12             1             0             0           0        True       False
9   2022-10-03       b            i             rule >    3    4   10             1             0             0           0        True       False
10  2022-10-03       b            i        single-cell    3    4   12             1             0             0           0        True       False
11  2022-10-03       b            i  documented dedupe    1    1    2             0             0             0           0        True       False
12  2022-10-03       b           ii               main    3    4   13             1             1             1           1        True       False
13  2022-10-03       b           ii             rule >    3    4   12             1             1             1           1        True       False
14  2022-10-03       b           ii        single-cell    3    4   13             1             1             1           1        True       False
15  2022-10-03       b           ii  documented dedupe    1    1    3             0             0             0           0        True       False
16  2022-10-03       c            i               main    3    4   13             1             0             0           0        True       False
17  2022-10-03       c            i             rule >    1    3   11             0             0             0           0        True       False
18  2022-10-03       c            i        single-cell    3    4   13             1             0             0           0        True       False
19  2022-10-03       c            i  documented dedupe    1    1    2             0             0             0           0        True       False
20  2022-10-03       c           ii               main    3    4   12             1             1             1           1        True       False
21  2022-10-03       c           ii             rule >    1    3   11             0             0             1           0        True       False
22  2022-10-03       c           ii        single-cell    3    4   12             1             1             1           1        True       False
23  2022-10-03       c           ii  documented dedupe    1    1    4             0             0             0           0        True       False
24  2022-12-06       a            i               main  331  613  111           120             9             4           2        True       False
25  2022-12-06       a            i             rule >  263  510  105            85             9             4           2        True       False
26  2022-12-06       a            i        single-cell  335  613  111           120             9             4           2        True       False
27  2022-12-06       a            i  documented dedupe    5   10   12             1             2             0           0        True       False
28  2022-12-06       a           ii               main  331  613  142           120             9             9           1        True       False
29  2022-12-06       a           ii             rule >  263  510  129            85             8             9           1        True       False
30  2022-12-06       a           ii        single-cell  335  613  142           120             9             9           1        True       False
31  2022-12-06       a           ii  documented dedupe    5   10   10             1             1             0           0        True       False
32  2022-12-06       b            i               main  386  731  134           143            21             8           1        True       False
33  2022-12-06       b            i             rule >  315  656  128           106            21             7           1        True       False
34  2022-12-06       b            i        single-cell  390  731  134           143            21             8           1        True       False
35  2022-12-06       b            i  documented dedupe    3   10   13             0             2             0           0        True       False
36  2022-12-06       b           ii               main  386  731  150           143            20            12           1        True       False
37  2022-12-06       b           ii             rule >  315  656  147           106            20            12           1        True       False
38  2022-12-06       b           ii        single-cell  390  731  150           143            20            12           1        True       False
39  2022-12-06       b           ii  documented dedupe    3   10   11             0             2             0           0        True       False
40  2022-12-06       c            i               main  362  746  134           154            15            10           2        True       False
41  2022-12-06       c            i             rule >  311  657  122           131            14            10           2        True       False
42  2022-12-06       c            i        single-cell  363  746  134           154            15            10           2        True       False
43  2022-12-06       c            i  documented dedupe   10    9   11             1             2             0           0        True       False
44  2022-12-06       c           ii               main  362  746  174           154            17            18           4        True       False
45  2022-12-06       c           ii             rule >  311  657  158           131            16            18           3        True       False
46  2022-12-06       c           ii        single-cell  363  746  174           154            17            18           4        True       False
47  2022-12-06       c           ii  documented dedupe   10    9   12             1             2             1           0        True       False
main variant, readings within tolerance: 0 of 12

fig4a and fig4b: the port against the paper's own counts¶

The paper's Figure 4D table (Zenodo doi:10.5281/zenodo.14976005) gives the sequence count of every session and segment, from the paper's own run of identify_sequences.m, including the two example sessions. If the claims file's method S were the paper's pipeline, the port would give these counts where the dandiset's events agree with the paper's. The port is run on every slice the table has, under a sweep of the window's upper bound t2 (0.25, 0.5, 1 and 2 s) and the separation of repetitions (0.05, 0.5, 1 and 2 s), with the 0.05 s lower bound, both double-counting steps and the first 10 min of the task. The slices are also split by how well the dandiset's events match the paper's per-cell table in that session (share of cells whose rate is within 1%, first notebook's link claim).

In [9]:
Z4s, _ = h.read_zenodo_csv("14976005", "Sequence parameters box plots (fig 4D)_Tidy version.csv")
Z4s.columns = ["monkey", "file", "total_cells", "structure", "segment", "n_seq", "seq_per_cell", "median_reps", "pct_cells"]
Z4s["subject"] = Z4s.monkey.str[0]
Z4s["date"] = Z4s.file.str.extract(r"(\d{4}_\d{2}_\d{2})")[0].str.replace("_", "-")
Z4s["segment"] = Z4s.segment.replace({"wRT": "RT"})
print("the paper's table for the example sessions:")
print(Z4s[(Z4s.subject == "Q") & Z4s.date.isin(["2022-09-15", "2022-12-06"])][["date", "total_cells", "segment", "n_seq", "median_reps", "pct_cells"]].to_string())
for c in ("n_seq", "median_reps"):
    Z4s[c] = pd.to_numeric(Z4s[c], errors="coerce")
# how well each session's events match the paper's per-cell table (rate within 1%)
zd, _ = h.zenodo_descriptors()
Dd = h.descriptor_table(files)
md_ = zd.merge(Dd, on=["subject", "region", "date", "condition", "cell"])
rr = (md_["Event Rate"] - md_["rate"]).abs() / md_["Event Rate"].abs()
md_["ok"] = (rr < 0.01) | ((md_["Event Rate"] == 0) & (md_["rate"] == 0))
match = md_.groupby(["subject", "date", "condition"]).ok.mean()
t0 = time.time()
SW = []
for x in files:
    for name, ts in sq.segments(x, "i"):
        if not ((Z4s.subject == x["subject"]) & (Z4s.date == x["date"]) & (Z4s.segment == name)).any():
            continue
        times, keep = sq.event_times(x)
        cells, L = sq.to_grid(times, ts)
        for t2 in (0.25, 0.5, 1.0, 2.0):
            for sep in (0.05, 0.5, 1.0, 2.0):
                key = (x["subject"], x["region"], x["date"], x["condition"], "i", name, "a")
                if t2 == 2.0 and sep == 0.05:
                    sig = RES[key][0]          # the main run, reading (a)
                else:
                    seed = int(pd.util.hash_pandas_object(pd.Series([str(key + (t2, sep))])).iloc[0] % 2**32)
                    sig, _ = sq.detect(cells, L, t1=0.05, t2=t2, sep=sep, rng=np.random.default_rng(seed))
                for dd in ("code", "documented"):
                    SW.append({"subject": x["subject"], "date": x["date"], "condition": x["condition"], "segment": name,
                               "t2": t2, "sep": sep, "dedupe": dd, "n_seq": len(sq.finalize(sig, dedupe=dd))})
SW = pd.DataFrame(SW).merge(Z4s[["subject", "date", "segment", "n_seq"]], on=["subject", "date", "segment"], suffixes=("", "_paper"))
SW["events_match"] = [match.get((s, d, c), np.nan) for s, d, c in zip(SW.subject, SW.date, SW.condition)]
SW = SW.dropna(subset=["n_seq_paper"])
print("sweep in %.0f s" % (time.time() - t0))
def agree(g):
    return pd.Series({"slices": len(g), "median_ratio": (g.n_seq / g.n_seq_paper.replace(0, np.nan)).median(),
                      "within_10pct": (np.abs(g.n_seq - g.n_seq_paper) <= 0.1 * g.n_seq_paper).mean(),
                      "spearman": stats.spearmanr(g.n_seq, g.n_seq_paper)[0]})
SWS = SW.groupby(["t2", "sep", "dedupe"]).apply(agree).reset_index()
print(SWS.round(3).to_string())
print("best setting: %.3f of slices within 10%% of the paper's count" % SWS.within_10pct.max())
good = SW[SW.events_match >= 0.8]
print("slices where at least 80% of the cells' rates match the paper's table:", sorted(set(zip(good.subject, good.date, good.segment))))
print(good.pivot_table(index=["t2", "sep", "dedupe"], columns=["date", "segment"], values="n_seq").astype(int).to_string())
print("the paper's counts there:", good.drop_duplicates(["date", "segment"]).set_index(["date", "segment"]).n_seq_paper.to_dict())
ex = SW[(SW.subject == "Q") & SW.date.isin(["2022-09-15", "2022-12-06"])]
print("example sessions under every setting (S1, S2, RT; the paper's in the last row):")
exw = ex.pivot_table(index=["t2", "sep", "dedupe"], columns=["date", "segment"], values="n_seq").astype(int)
exw.loc[("paper", "", ""), :] = ex.drop_duplicates(["date", "segment"]).set_index(["date", "segment"]).n_seq_paper
print(exw.to_string())
the paper's table for the example sessions:
          date  total_cells segment n_seq median_reps pct_cells
20  2022-12-06           18      S1     8          46        50
21  2022-09-15           40      S1  n.a.        n.a.      n.a.
23  2022-09-15           40      S2    13           4        40
29  2022-12-06           18      S2    13          67        56
30  2022-09-15           40      RT    17           5        43
36  2022-12-06           18      RT     9          77        50
sweep in 397 s
      t2   sep      dedupe  slices  median_ratio  within_10pct  spearman
0   0.25  0.05        code    56.0         0.333         0.089     0.807
1   0.25  0.05  documented    56.0         0.250         0.089     0.816
2   0.25  0.50        code    56.0         0.286         0.071     0.800
3   0.25  0.50  documented    56.0         0.250         0.089     0.805
4   0.25  1.00        code    56.0         0.250         0.107     0.827
5   0.25  1.00  documented    56.0         0.250         0.125     0.829
6   0.25  2.00        code    56.0         0.250         0.107     0.823
7   0.25  2.00  documented    56.0         0.200         0.089     0.818
8   0.50  0.05        code    56.0         1.182         0.107     0.851
9   0.50  0.05  documented    56.0         0.333         0.161     0.857
10  0.50  0.50        code    56.0         0.500         0.196     0.862
11  0.50  0.50  documented    56.0         0.353         0.125     0.875
12  0.50  1.00        code    56.0         0.375         0.214     0.895
13  0.50  1.00  documented    56.0         0.294         0.143     0.899
14  0.50  2.00        code    56.0         0.400         0.196     0.872
15  0.50  2.00  documented    56.0         0.357         0.125     0.873
16  1.00  0.05        code    56.0         1.750         0.125     0.870
17  1.00  0.05  documented    56.0         0.429         0.161     0.854
18  1.00  0.50        code    56.0         0.875         0.125     0.877
19  1.00  0.50  documented    56.0         0.500         0.196     0.905
20  1.00  1.00        code    56.0         0.600         0.125     0.905
21  1.00  1.00  documented    56.0         0.500         0.179     0.907
22  1.00  2.00        code    56.0         0.571         0.143     0.900
23  1.00  2.00  documented    56.0         0.500         0.125     0.907
24  2.00  0.05        code    56.0         3.125         0.054     0.871
25  2.00  0.05  documented    56.0         0.400         0.125     0.852
26  2.00  0.50        code    56.0         1.143         0.143     0.880
27  2.00  0.50  documented    56.0         0.500         0.143     0.820
28  2.00  1.00        code    56.0         1.000         0.196     0.890
29  2.00  1.00  documented    56.0         0.545         0.179     0.881
30  2.00  2.00        code    56.0         0.941         0.161     0.896
31  2.00  2.00  documented    56.0         0.500         0.179     0.905
best setting: 0.214 of slices within 10% of the paper's count
slices where at least 80% of the cells' rates match the paper's table: [('Q', '2022-12-01', 'RT'), ('Q', '2022-12-06', 'RT')]
date                 2022-12-01 2022-12-06
segment                      RT         RT
t2   sep  dedupe                          
0.25 0.05 code                4         21
          documented          4         11
     0.50 code                2         15
          documented          2         11
     1.00 code                3         17
          documented          3         13
     2.00 code                2         15
          documented          2         12
0.50 0.05 code               11         68
          documented          6         20
     0.50 code                5         41
          documented          4         18
     1.00 code                4         44
          documented          3         17
     2.00 code                5         41
          documented          4         16
1.00 0.05 code                9         81
          documented          3         16
     0.50 code                5         45
          documented          3         15
     1.00 code                4         36
          documented          4         17
     2.00 code                4         28
          documented          4         15
2.00 0.05 code               13        111
          documented          2         12
     0.50 code                8         71
          documented          6         12
     1.00 code                6         46
          documented          5         13
     2.00 code                5         39
          documented          4          8
the paper's counts there: {('2022-12-01', 'RT'): 7.0, ('2022-12-06', 'RT'): 9.0}
example sessions under every setting (S1, S2, RT; the paper's in the last row):
date                  2022-09-15 2022-12-06          
segment                       RT         RT   S1   S2
t2    sep  dedupe                                    
0.25  0.05 code               15         21   18   44
           documented          6         11    5   10
      0.5  code                5         15    7   39
           documented          4         11    6   10
      1.0  code                2         17    6   40
           documented          2         13    5   12
      2.0  code                3         15    6   36
           documented          3         12    6    8
0.5   0.05 code               33         68   64  111
           documented          6         20   11   23
      0.5  code               11         41   27   72
           documented          6         18    9   20
      1.0  code                9         44   19   70
           documented          5         17    8   18
      2.0  code                5         41   19   66
           documented          4         16    9   17
1.0   0.05 code               96         81  115  209
           documented          6         16    7   16
      0.5  code               20         45   45  114
           documented          9         15    6   20
      1.0  code                9         36   39  102
           documented          7         17    5   18
      2.0  code               10         28   28  101
           documented          8         15    4   20
2.0   0.05 code              211        111  331  613
           documented          5         12    5   10
      0.5  code               44         71  103  283
           documented          6         12    9    6
      1.0  code               18         46   38  247
           documented          6         13    4    8
      2.0  code               16         39   38  205
           documented          6          8    4    8
paper                         17          9    8   13

Result (fig4a-example-sequences-q): blocked (methods underspecified). The only Q SMA session with 40 accepted cells is 2022-09-15. Under every reading of method S the counts are far from 13 and 17: with the code's double-counting step as it runs, 157 to 196 sequences in the spontaneous slice and 176 to 311 in the task slice; with the code's more-than-4 rule, 113 to 155 and 156 to 260; with the double-counting step as documented, 5 and 2 to 5. No reading or variant is within tolerance (0 of 6 main readings). Every ordering of the cells (reading a) gives 979 and 1856 significant patterns, and 2 and 0 after the documented step. The sets of sequences differ between the two conditions under every reading (for example 10 shared of 157 and 211 under reading a, task reading i), as the statement says.

The analysis ran, but it does not run the paper's pipeline. The paper's own Figure 4D table, from its run of identify_sequences.m, is not matched by the port under any of 32 settings of the window's upper bound, the separation of repetitions and the double-counting step: the best setting has 0.214 of 56 slices within 10% of the paper's count, and the median ratio to the paper's count ranges from 0.200 to 3.125. Where the dandiset's events agree with the paper's per-cell table (Q 2022-12-01 and 2022-12-06 task, at least 80% of cells with the rate within 1%), no setting gives both of the paper's counts (7 and 9): they range from 2 to 13 and from 8 to 111. So the claims file's readings of method S do not include the procedure that produced 13 and 17, and the counts here cannot say whether the paper's numbers hold on the dandiset. The table also gives 13 for this session's second spontaneous 10 min and n.a. for its first, while the dandiset's spontaneous file of 2022-09-15 holds one 10-min slice (data check); the 13 of the claim may not come from the slice tested here. The criterion's own rule gives not reproduced when every reading fails, as here; the outcome departs from that rule, because the readings it lists do not include the paper's procedure, and the departure is recorded as a deviation.

Result (fig4b-example-three-segments-q): blocked (methods underspecified). Two Q SMA sessions have 18 cells and at least 20 min of spontaneous recording (2022-10-03, 21.8 min, and 2022-12-06, 20.4 min). Neither matches 8, 13 and 9 under any reading (0 of 12 main readings within tolerance): 2022-10-03 gives 3, 4 and 12 to 13 sequences, 2022-12-06 gives 331 to 386, 613 to 746 and 111 to 174 (main variant). The documented double-counting step gives 1, 1 and 2 to 4 for 2022-10-03, and 3 to 10, 9 to 10 and 10 to 13 for 2022-12-06. The three slices' sets of sequences differ in every reading, and at most 4 sequences are shared by all three. The paper's Figure 4D table gives 8, 13 and 9 for 2022-12-06. Over the 32 settings of the sweep, 2022-12-06 gives 4 to 331, 6 to 613 and 8 to 111, and no setting gives all three counts within tolerance. As for fig4a, the port does not reproduce the paper's own counts under any setting, even in the task slice of this session, where at least 80% of cells' rates match the paper's table, so the claims file's method S does not fix the procedure behind the numbers. As for fig4a, blocking departs from the criterion's rule, which gives not reproduced when every reading fails.

fig4d-sequence-measures-vary¶

The number of sequences per cell, their repetition and the proportion of cells in sequences varied across conditions and imaging sites.

Per slice: sequences over accepted cells, the median number of repetitions of its sequences, and the percentage of cells in at least one sequence (Figure 4D legend). Per site, the median over sessions of each measure, per segment (S1, S2, RT). The paper's Figure 4D table (Zenodo doi:10.5281/zenodo.14976005) is shown next to this attempt's values, matched by session and segment; it decides nothing.

In [10]:
main = ALL[ALL.variant == "main"].copy()
main["site"] = main.subject + " " + main.region
def site_medians(df):
    return df.groupby(["site", "segment"]).agg(sessions=("n_seq", "size"), seq_per_cell=("seq_per_cell", "median"),
                                              median_reps=("median_reps", "median"), pct_cells=("pct_cells", "median"))
dec = []
for rd in sq.READINGS:
    for tr in ("i", "ii"):
        df = main[(main.reading == rd) & ((main.condition == "spontaneous") | (main.task_reading == tr))]
        sm = site_medians(df)
        if rd == "a" and tr == "i":
            print("reading a, task reading i: per-site medians")
            print(sm.round(3).to_string())
        for meas in ("seq_per_cell", "median_reps", "pct_cells"):
            by_seg = sm[meas].unstack("segment")
            dec.append({"reading": rd, "task_reading": tr, "measure": meas,
                        "differs_across_segments": bool((by_seg.nunique(axis=1, dropna=True) > 1).any()),
                        "differs_across_sites": bool((by_seg.nunique(axis=0, dropna=True) > 1).any()),
                        "range": f"{sm[meas].min():.3f} to {sm[meas].max():.3f}"})
DEC = pd.DataFrame(dec)
print(DEC.to_string())
print("readings where every measure differs across segments and across sites:",
      int(DEC.groupby(["reading", "task_reading"]).apply(lambda g: (g.differs_across_segments & g.differs_across_sites).all()).sum()), "of 6")
reading a, task reading i: per-site medians
               sessions  seq_per_cell  median_reps  pct_cells
site  segment                                                
F SMA S1              8         1.600         7.00     82.500
      S2              6         3.054         7.50     83.482
Q SMA RT              7         2.250         6.00     68.421
      S1              7         3.925         6.00     76.923
      S2              5         0.692         8.00     52.381
U M1  RT              4         2.000        18.25     97.619
      S1              4         2.729        11.50     91.667
      S2              3         1.500         7.00     87.500
U SMA RT              5         0.300         4.00     40.000
      S1              5         0.240         5.00     24.000
      S2              5         0.160         4.00     28.000
V M1  RT              2         1.256         8.00     67.532
      S1              2         6.013        10.75     72.078
      S2              2         1.948        14.00     57.468
   reading task_reading       measure  differs_across_segments  differs_across_sites              range
0        a            i  seq_per_cell                     True                  True     0.160 to 6.013
1        a            i   median_reps                     True                  True    4.000 to 18.250
2        a            i     pct_cells                     True                  True   24.000 to 97.619
3        a           ii  seq_per_cell                     True                  True     0.160 to 6.013
4        a           ii   median_reps                     True                  True    4.000 to 14.000
5        a           ii     pct_cells                     True                  True   24.000 to 91.667
6        b            i  seq_per_cell                     True                  True     0.160 to 8.477
7        b            i   median_reps                     True                  True    4.000 to 18.000
8        b            i     pct_cells                     True                  True  25.000 to 100.000
9        b           ii  seq_per_cell                     True                  True     0.160 to 8.477
10       b           ii   median_reps                     True                  True    4.000 to 15.500
11       b           ii     pct_cells                     True                  True  25.000 to 100.000
12       c            i  seq_per_cell                     True                  True     0.200 to 6.997
13       c            i   median_reps                     True                  True    4.000 to 15.000
14       c            i     pct_cells                     True                  True   24.000 to 97.619
15       c           ii  seq_per_cell                     True                  True     0.200 to 6.997
16       c           ii   median_reps                     True                  True    4.000 to 15.000
17       c           ii     pct_cells                     True                  True   24.000 to 91.667
readings where every measure differs across segments and across sites: 6 of 6
In [11]:
Z4, z4_md5 = h.read_zenodo_csv("14976005", "Sequence parameters box plots (fig 4D)_Tidy version.csv")
Z4.columns = ["monkey", "file", "total_cells", "structure", "segment", "n_seq", "seq_per_cell", "median_reps", "pct_cells"]
Z4["subject"] = Z4.monkey.str[0]
Z4["date"] = Z4.file.str.extract(r"(\d{4}_\d{2}_\d{2})")[0].str.replace("_", "-")
Z4["segment"] = Z4.segment.replace({"wRT": "RT"})
for c in ("n_seq", "seq_per_cell", "median_reps", "pct_cells"):
    Z4[c] = pd.to_numeric(Z4[c], errors="coerce")
print("Zenodo Fig. 4D table", z4_md5, len(Z4), "rows")
mine = main[(main.reading == "a") & ((main.condition == "spontaneous") | (main.task_reading == "i"))]
cmp4 = Z4.merge(mine[["subject", "date", "segment", "n_seq", "median_reps", "pct_cells"]], on=["subject", "date", "segment"],
                how="left", suffixes=("_paper", "_here"))
cells_here = {(x["subject"], x["date"]): x["events"].shape[1] for x in files}
cmp4["cells_here"] = [cells_here.get((s, d)) for s, d in zip(cmp4.subject, cmp4.date)]
print(cmp4[["subject", "date", "segment", "total_cells", "cells_here", "n_seq_paper", "n_seq_here", "median_reps_paper", "median_reps_here",
            "pct_cells_paper", "pct_cells_here"]].to_string())
ok = cmp4.dropna(subset=["n_seq_paper", "n_seq_here"])
print("slices in both: %d; Spearman correlation of the sequence counts %.3f; median ratio here / paper %.2f"
      % (len(ok), stats.spearmanr(ok.n_seq_paper, ok.n_seq_here)[0], (ok.n_seq_here / ok.n_seq_paper.replace(0, np.nan)).median()))
docu = ALL[(ALL.variant == "documented dedupe") & (ALL.reading == "a") & ((ALL.condition == "spontaneous") | (ALL.task_reading == "i"))]
ok2 = Z4.merge(docu[["subject", "date", "segment", "n_seq"]], on=["subject", "date", "segment"], suffixes=("_paper", "_doc")).dropna()
print("documented dedupe variant: Spearman %.3f; median ratio %.2f" % (stats.spearmanr(ok2.n_seq_paper, ok2.n_seq_doc)[0],
      (ok2.n_seq_doc / ok2.n_seq_paper.replace(0, np.nan)).median()))
Zenodo Fig. 4D table md5:4f52af7e3e3d6ba0a9f660932608d4fe 64 rows
   subject        date segment  total_cells  cells_here  n_seq_paper  n_seq_here  median_reps_paper  median_reps_here  pct_cells_paper  pct_cells_here
0        F  2024-02-20      S1           16          16         11.0        83.0              116.0               6.0             50.0       93.750000
1        F  2024-02-23      S1           15          15          8.0        33.0               15.0               7.0             67.0       73.333333
2        F  2024-02-27      S1           14          14         10.0        71.0                6.0               7.0             64.0       92.857143
3        F  2024-02-29      S1           14          14         15.0        60.0               19.0               7.0             86.0       92.857143
4        F  2024-03-05      S1           12          12          7.0        12.0               10.0               8.0             58.0       91.666667
5        F  2024-03-07      S1            6           6          4.0         3.0                3.0               6.0             83.0       66.666667
6        F  2024-02-13      S1            6           6          NaN         0.0                NaN               0.0              NaN        0.000000
7        F  2024-03-12      S1            4           4          NaN         1.0                NaN              13.0              NaN       50.000000
8        F  2024-02-13      S2            6           6          1.0         NaN                3.0               NaN             50.0             NaN
9        F  2024-03-12      S2            4           4          1.0         NaN                3.0               NaN             75.0             NaN
10       F  2024-02-20      S2           16          16         16.0        52.0               38.0               6.0             75.0       81.250000
11       F  2024-02-23      S2           15          15         12.0        73.0               20.0               8.0             87.0       93.333333
12       F  2024-02-27      S2           14          14         12.0        61.0                6.0               7.0             79.0       92.857143
13       F  2024-02-29      S2           14          14         11.0        40.0               27.0               8.5             71.0       85.714286
14       F  2024-03-05      S2           12          12         10.0         5.0                7.0               8.0             58.0       66.666667
15       F  2024-03-07      S2            6           6          4.0         2.0                2.0               4.5             67.0       50.000000
16       Q  2022-10-03      S1           17          18          1.0         3.0                2.0               4.0             18.0       27.777778
17       Q  2022-10-28      S1           21          21          2.0         8.0                2.0               5.0             19.0       42.857143
18       Q  2022-12-01      S1           11          13          4.0        10.0                2.0               6.0             45.0       76.923077
19       Q  2022-12-02      S1           12          12          9.0        82.0               21.0               7.0             67.0       91.666667
20       Q  2022-12-06      S1           18          18          8.0       331.0               46.0               6.0             50.0       94.444444
21       Q  2022-09-15      S1           40          40          NaN       157.0                NaN               6.0              NaN       75.000000
22       Q  2022-09-22      S1           38          38          NaN       659.0                NaN               6.0              NaN       89.473684
23       Q  2022-09-15      S2           40          40         13.0         NaN                4.0               NaN             40.0             NaN
24       Q  2022-09-22      S2           38          38         19.0         NaN               21.0               NaN             45.0             NaN
25       Q  2022-10-03      S2           17          18          3.0         4.0                4.0               8.5             29.0       33.333333
26       Q  2022-10-28      S2           21          21          1.0         9.0                2.0               5.0              5.0       52.380952
27       Q  2022-12-01      S2           11          13          5.0         9.0                2.0              12.0             45.0       46.153846
28       Q  2022-12-02      S2           12          12          7.0        26.0                8.0               8.0             58.0       75.000000
29       Q  2022-12-06      S2           18          18         13.0       613.0               67.0               8.0             56.0       94.444444
30       Q  2022-09-15      RT           40          40         17.0       211.0                5.0               6.0             43.0       87.500000
31       Q  2022-09-22      RT           38          38         17.0       200.0                7.0               6.0             45.0       68.421053
32       Q  2022-10-03      RT           17          18          6.0        12.0                3.0               6.0             35.0       55.555556
33       Q  2022-10-28      RT           21          21          5.0        22.0                6.0               6.5             24.0       47.619048
34       Q  2022-12-01      RT           11          13          7.0        13.0               13.0              11.0             64.0       61.538462
35       Q  2022-12-02      RT           12          12         14.0        27.0                7.0               6.0            100.0       91.666667
36       Q  2022-12-06      RT           18          18          9.0       111.0               77.0              10.0             50.0       72.222222
37       U  2023-02-27      S1           16          16          4.0        22.0                9.0               8.5             31.0       43.750000
38       U  2023-03-07      S1           10          10          1.0         0.0                2.0               0.0             30.0        0.000000
39       U  2023-03-14      S1           20          20          2.0         5.0                2.0               4.0             20.0       25.000000
40       U  2023-03-21      S1           25          25          3.0         6.0                2.0               5.0             16.0       24.000000
41       U  2023-03-28      S1           14          14          0.0         1.0                0.0               5.0              0.0       14.285714
42       U  2023-03-01      S1           21          21         22.0      1048.0              120.0               8.0             67.0      100.000000
43       U  2023-03-23      S1            6           6          3.0         8.0               12.0              16.5             50.0       83.333333
44       U  2023-02-27      S2           16          16          5.0         4.0                5.0              10.0             25.0       37.500000
45       U  2023-03-07      S2           10          10          3.0         0.0                3.0               0.0             40.0        0.000000
46       U  2023-03-14      S2           20          20          0.0         0.0                0.0               0.0              0.0        0.000000
47       U  2023-03-21      S2           25          25          2.0         4.0                2.0               4.0             12.0       28.000000
48       U  2023-03-28      S2           14          14          0.0         7.0                0.0               7.0              0.0       35.714286
49       U  2023-03-01      S2           21          21         19.0       665.0               64.0               7.0             52.0       85.714286
50       U  2023-03-23      S2            6           6          4.0         3.0               61.0               7.0            100.0      100.000000
51       U  2023-02-27      RT           16          16          3.0         9.0                5.0               5.0             31.0       68.750000
52       U  2023-03-07      RT           10          10          2.0         3.0                4.0               4.0             30.0       40.000000
53       U  2023-03-14      RT           20          20          0.0         0.0                0.0               0.0              0.0        0.000000
54       U  2023-03-21      RT           25          25          6.0        12.0                3.0               4.0             28.0       44.000000
55       U  2023-03-28      RT           14          14          0.0         1.0                0.0               6.0              0.0       14.285714
56       U  2023-03-01      RT           21          21         14.0      1423.0               48.0              10.0             43.0       95.238095
57       U  2023-03-23      RT            6           6          4.0         6.0               19.0              13.5             50.0       83.333333
58       V  2023-03-09      S1           11          11          8.0        27.0               11.0               6.0             64.0       72.727273
59       V  2023-03-16      S1           13          14         14.0       134.0               80.0              15.5             54.0       71.428571
60       V  2023-03-09      S2           11          11          3.0         2.0                4.0              17.0             45.0       36.363636
61       V  2023-03-16      S2           13          14          8.0        52.0               92.0              11.0             46.0       78.571429
62       V  2023-03-09      RT           11          11          8.0         8.0                4.0               6.0             73.0       63.636364
63       V  2023-03-16      RT           13          14          8.0        25.0               28.0              10.0             46.0       71.428571
slices in both: 56; Spearman correlation of the sequence counts 0.871; median ratio here / paper 3.12
documented dedupe variant: Spearman 0.852; median ratio 0.40

Result: reproduced. Under all six readings (three of the 0.05 s rules, two of the task slice) each measure's per-site medians differ across segments and across sites: sequences per cell range from 0.160 to 8.477, median repetitions from 4.0 to 18.25 and the percentage of cells in sequences from 24.0 to 100.0. The criterion is met by any measure that is not constant, so this says little. The per-slice counts follow the paper's Figure 4D table in rank (Spearman 0.871 over 56 slices) but are a median 3.12 times larger; with the documented double-counting step they are 0.40 times the table's (Spearman 0.852).

fig4c-sequence-cells-not-clustered¶

Cells involved in sequences were spread across the field of view, with no preferred spatial relation between them.

Reading (i): centroids of cells in sequences against those of all cells, spontaneous slices, Q SMA and U M1, all sessions pooled (Figure 4C legend), each coordinate. Reading (ii): distances between cells that share a sequence against distances between all cell pairs, per session (pairs pooled over its slices, each pair once), pooled over sessions. Tests: two-sample Kolmogorov-Smirnov and Mann-Whitney, two-sided, p < 0.05. Main detection variant, task reading (i), for each 0.05 s reading.

In [12]:
cent = {(x["subject"], x["region"], x["date"]): x["centroid"] for x in files}
F4C = []
for rd in sq.READINGS:
    # (i) centroids, spontaneous, Q SMA and U M1
    for site in [("Q", "SMA"), ("U", "M1")]:
        allc, inseq = [], []
        for x in files:
            if (x["subject"], x["region"]) != site or x["condition"] != "spontaneous":
                continue
            cs = set()
            for name, ts in sq.segments(x, "i"):
                _, seqs = measures((x["subject"], x["region"], x["date"], "spontaneous", "i", name, rd))
                cs |= {c for s, _ in seqs for c in s}
            c0 = x["centroid"]
            allc.append(c0)
            inseq.append(c0[sorted(cs)] if cs else np.zeros((0, 2)))
        allc, inseq = np.vstack(allc), np.vstack(inseq)
        for ax, nm in ((0, "x"), (1, "y")):
            if len(inseq) >= 2:
                F4C.append({"reading": rd, "comparison": f"(i) centroid {nm}, {site[0]} {site[1]}", "n_seq_cells": len(inseq), "n_all": len(allc),
                            "KS_p": stats.ks_2samp(inseq[:, ax], allc[:, ax]).pvalue,
                            "MW_p": stats.mannwhitneyu(inseq[:, ax], allc[:, ax]).pvalue,
                            "median_seq": np.median(inseq[:, ax]), "median_all": np.median(allc[:, ax])})
    # (ii) distances, every session
    dseq, dall = [], []
    for key3, c0 in cent.items():
        pairs = set()
        for k in RES:
            if k[:3] == key3 and k[6] == rd and (k[3] == "spontaneous" or k[4] == "i"):
                _, seqs = measures(k)
                for s, _ in seqs:
                    u = sorted(set(s))
                    pairs |= {(a, b) for i, a in enumerate(u) for b in u[i + 1:]}
        n = len(c0)
        dist = lambda a, b: np.hypot(*(c0[a] - c0[b])) * h.UM_PER_PIXEL
        dall += [dist(a, b) for a in range(n) for b in range(a + 1, n)]
        dseq += [dist(a, b) for a, b in pairs]
    F4C.append({"reading": rd, "comparison": "(ii) pair distance (um), all sessions", "n_seq_cells": len(dseq), "n_all": len(dall),
                "KS_p": stats.ks_2samp(dseq, dall).pvalue, "MW_p": stats.mannwhitneyu(dseq, dall).pvalue,
                "median_seq": np.median(dseq), "median_all": np.median(dall)})
F4C = pd.DataFrame(F4C)
print(F4C.round(4).to_string())
print("tests with p < 0.05: %d of %d" % (((F4C.KS_p < 0.05).sum() + (F4C.MW_p < 0.05).sum()), 2 * len(F4C)))
   reading                             comparison  n_seq_cells  n_all    KS_p    MW_p  median_seq  median_all
0        a                  (i) centroid x, Q SMA          125    160  0.9999  0.6776    141.8234    134.9128
1        a                  (i) centroid y, Q SMA          125    160  1.0000  0.8723    104.6288    103.9246
2        a                   (i) centroid x, U M1           39     43  1.0000  0.9445    155.7408    155.7408
3        a                   (i) centroid y, U M1           39     43  1.0000  0.8128     72.8000     80.0480
4        a  (ii) pair distance (um), all sessions         1447   3825  0.0001  0.0000    285.0185    320.4209
5        b                  (i) centroid x, Q SMA          125    160  0.9999  0.6776    141.8234    134.9128
6        b                  (i) centroid y, Q SMA          125    160  1.0000  0.8723    104.6288    103.9246
7        b                   (i) centroid x, U M1           39     43  1.0000  0.9445    155.7408    155.7408
8        b                   (i) centroid y, U M1           39     43  1.0000  0.8128     72.8000     80.0480
9        b  (ii) pair distance (um), all sessions         1653   3825  0.0020  0.0002    295.9832    320.4209
10       c                  (i) centroid x, Q SMA          127    160  1.0000  0.7527    130.0290    134.9128
11       c                  (i) centroid y, Q SMA          127    160  0.9999  0.7408    106.0013    103.9246
12       c                   (i) centroid x, U M1           39     43  1.0000  0.9445    155.7408    155.7408
13       c                   (i) centroid y, U M1           39     43  1.0000  0.8128     72.8000     80.0480
14       c  (ii) pair distance (um), all sessions         1501   3825  0.0001  0.0000    284.3166    320.4209
tests with p < 0.05: 6 of 30

Pooling pairs over sessions mixes fields of view of different size and shape: a session with many sequence pairs and a large field shifts the pooled distribution. Distances are only comparable within a session, so reading (ii) is also tested within each session (KS and Mann-Whitney per session, Benjamini-Hochberg over sessions) and stratified by session (each distance as its percentile among the session's all-pair distances, then pooled; and a permutation test that relabels the cells of each session at random, keeping each session's sequences, 2000 permutations, statistic the pair-weighted mean over sessions of the sequence-pair mean distance minus the all-pair mean).

In [13]:
rng4c = np.random.default_rng(4)
def pairs_of(key3, rd, kw):
    pairs = set()
    for k in RES:
        if k[:3] == key3 and k[6] == rd and (k[3] == "spontaneous" or k[4] == "i"):
            for s, _ in measures(k, **kw)[1]:
                u = sorted(set(s))
                pairs |= {(a, b) for i, a in enumerate(u) for b in u[i + 1:]}
    return sorted(pairs)
WS, ST = [], []
for rd in sq.READINGS:
    for vname in ("main", "documented dedupe"):
        per, pseq, pall, perm_in = [], [], [], []
        for key3, c0 in cent.items():
            n = len(c0)
            Dm = np.hypot(*(c0[:, None, :] - c0[None, :, :]).transpose(2, 0, 1)) * h.UM_PER_PIXEL
            dall = np.sort(Dm[np.triu_indices(n, 1)])
            pairs = pairs_of(key3, rd, VARIANTS[vname])
            if len(pairs) == 0 or n < 3:
                continue
            dseq = np.array([Dm[a, b] for a, b in pairs])
            pct = lambda v: (np.searchsorted(dall, v, "left") + np.searchsorted(dall, v, "right")) / 2 / len(dall)
            pseq += list(pct(dseq)); pall += list(pct(dall))
            per.append({"reading": rd, "variant": vname, "session": " ".join(key3), "cells": n, "pairs_seq": len(dseq), "pairs_all": len(dall),
                        "median_seq": np.median(dseq), "median_all": np.median(dall),
                        "KS_p": stats.ks_2samp(dseq, dall).pvalue, "MW_p": stats.mannwhitneyu(dseq, dall).pvalue})
            perm_in.append((Dm, np.array(pairs), n))
        per = pd.DataFrame(per)
        per["KS_q"], per["MW_q"] = h.bh(per.KS_p), h.bh(per.MW_p)
        WS.append(per)
        def stat(perms):
            v = [Dm[p[a[:, 0]], p[a[:, 1]]].mean() - Dm[np.triu_indices(n, 1)].mean() for (Dm, a, n), p in zip(perms_in_, perms)]
            return np.average(v, weights=[len(a) for _, a, _ in perms_in_])
        perms_in_ = perm_in
        obs = stat([np.arange(n) for _, _, n in perm_in])
        null = np.array([stat([rng4c.permutation(n) for _, _, n in perm_in]) for _ in range(2000)])
        ST.append({"reading": rd, "variant": vname, "sessions": len(per),
                   "sessions_KS_p<0.05": int((per.KS_p < 0.05).sum()), "sessions_MW_p<0.05": int((per.MW_p < 0.05).sum()),
                   "sessions_q<0.05": int(((per.KS_q < 0.05) | (per.MW_q < 0.05)).sum()),
                   "sessions_seq_closer": int((per.median_seq < per.median_all).sum()),
                   "stratified_KS_p": stats.ks_2samp(pseq, pall).pvalue, "stratified_MW_p": stats.mannwhitneyu(pseq, pall).pvalue,
                   "median_percentile_seq": np.median(pseq),
                   "perm_obs_um": obs, "perm_p": float((np.abs(null - null.mean()) >= abs(obs - null.mean())).mean())})
WS = pd.concat(WS, ignore_index=True)
print("per session, reading (a), main variant:")
print(WS[(WS.reading == "a") & (WS.variant == "main")].drop(columns=["reading", "variant"]).round(4).to_string())
ST = pd.DataFrame(ST)
print(ST.round(4).to_string())
print("within-session tests with p < 0.05, over all readings and variants: %d of %d; smallest stratified p %.4f; smallest permutation p %.4f"
      % (int(ST["sessions_KS_p<0.05"].sum() + ST["sessions_MW_p<0.05"].sum()), 2 * len(WS),
         min(ST.stratified_KS_p.min(), ST.stratified_MW_p.min()), ST.perm_p.min()))
per session, reading (a), main variant:
             session  cells  pairs_seq  pairs_all  median_seq  median_all    KS_p    MW_p  KS_q  MW_q
0   F SMA 2024-02-20     16         69        120    259.0482    256.1783  0.9992  0.8684   1.0   1.0
1   F SMA 2024-02-23     15         51        105    260.6638    260.6638  0.9999  0.9262   1.0   1.0
2   F SMA 2024-02-27     14         63         91    262.9635    277.4814  0.9909  0.8499   1.0   1.0
3   F SMA 2024-02-29     14         62         91    182.9156    191.7700  0.9990  0.9186   1.0   1.0
4   F SMA 2024-03-05     12         23         66    340.6846    300.3756  0.9070  0.4311   1.0   1.0
5   F SMA 2024-03-07      6          7         15    357.6820    307.4107  0.8896  0.3058   1.0   1.0
6   F SMA 2024-03-12      4          1          6    109.3835    120.9444  1.0000  1.0000   1.0   1.0
7   Q SMA 2022-09-15     40        224        780    326.8863    313.2748  0.6641  0.6487   1.0   1.0
8   Q SMA 2022-09-22     38        302        703    357.2290    357.5877  0.6632  0.8951   1.0   1.0
9   Q SMA 2022-10-03     18         21        153    382.3811    359.5468  0.7591  0.4418   1.0   1.0
10  Q SMA 2022-10-28     21         36        210    444.4130    385.1092  0.1670  0.3016   1.0   1.0
11  Q SMA 2022-12-01     13         31         78    298.9845    246.3045  0.5239  0.5635   1.0   1.0
12  Q SMA 2022-12-02     12         45         66    258.3495    271.2100  1.0000  0.8570   1.0   1.0
13  Q SMA 2022-12-06     18        123        153    382.6149    395.1685  0.9998  0.6044   1.0   1.0
14   U M1 2023-02-24      8         27         28    275.6082    271.8146  1.0000  0.8267   1.0   1.0
15  U SMA 2023-02-27     16         23        120    316.9742    319.2568  1.0000  0.9693   1.0   1.0
16   U M1 2023-03-01     21        195        210    230.2024    232.9128  1.0000  0.8424   1.0   1.0
17  U SMA 2023-03-07     10          4         45    196.7086    352.0655  0.3762  0.2654   1.0   1.0
18  U SMA 2023-03-14     20          5        190    410.3987    441.2902  0.7823  0.6130   1.0   1.0
19   U M1 2023-03-16      8         12         28    413.5313    390.0068  0.8210  0.5449   1.0   1.0
20  U SMA 2023-03-21     25         23        300    272.7920    480.6593  0.0889  0.4445   1.0   1.0
21   U M1 2023-03-23      6         14         15    363.9087    345.8008  1.0000  0.7763   1.0   1.0
22  U SMA 2023-03-28     14          7         91    423.6627    470.0322  0.9924  0.8957   1.0   1.0
23   V M1 2023-03-09     11         27         55    221.1750    255.0383  0.5415  0.2755   1.0   1.0
24   V M1 2023-03-16     14         52         91    160.7713    186.9888  0.9087  0.4487   1.0   1.0
  reading            variant  sessions  sessions_KS_p<0.05  sessions_MW_p<0.05  sessions_q<0.05  sessions_seq_closer  stratified_KS_p  stratified_MW_p  median_percentile_seq  perm_obs_um  perm_p
0       a               main        25                   0                   0                0                   14           0.6796           0.9362                 0.5000       0.4555  0.9110
1       a  documented dedupe        22                   0                   0                0                   15           0.0027           0.0033                 0.4281     -31.0675  0.0025
2       b               main        25                   0                   0                0                   12           0.7846           0.5673                 0.5083       4.1762  0.3305
3       b  documented dedupe        22                   0                   1                0                   13           0.0247           0.0215                 0.4586     -26.4579  0.0105
4       c               main        25                   0                   0                0                   14           0.5485           0.7388                 0.5000      -0.6286  0.8985
5       c  documented dedupe        23                   0                   0                0                   14           0.0765           0.0936                 0.4883     -19.4690  0.0740
within-session tests with p < 0.05, over all readings and variants: 1 of 284; smallest stratified p 0.0027; smallest permutation p 0.0025

Result: blocked (methods underspecified). Reading (i), the centroids of cells in sequences against those of all cells (spontaneous, Q SMA and U M1), finds no difference under any 0.05 s reading (smallest p 0.6776 over 24 tests). Reading (ii), distances between cells that share a sequence against all pair distances, finds them shorter when pairs are pooled over sessions (medians 284 to 296 against 320 um, KS p 0.0001 to 0.0020). Pooling mixes fields of view of different geometry, and within sessions that difference goes away. With the code's double-counting step, no session shows a difference (0 of 25 sessions at p < 0.05 by KS or Mann-Whitney, under each 0.05 s reading), and the stratified tests agree (percentile KS p 0.5485 to 0.7846, Mann-Whitney p 0.5673 to 0.9362, permutation p 0.3305 to 0.9110). So, with the code's step, every reading finds no difference when reading (ii) is tested within sessions, while the pooled test of reading (ii) finds sequence pairs closer: the pooled and the within-session tests of reading (ii) disagree. The within-session and stratified tests were chosen after the first verification; the criterion leaves the test open and names neither. With the double-counting step as its comments describe it, the stratified tests find sequence pairs closer under readings (a) and (b) (permutation p 0.0025 and 0.0105, percentile KS p 0.0027 and 0.0247), though no single session reaches q < 0.05. The code's double-counting step removes nothing as the code runs (printed in the data check), so the code's step is the main reading; the documented step is a variant. The claim stays blocked for two reasons: under the code's step the readings disagree when the pooled test of reading (ii) is counted, and which cells enter sequences depends on a detection that the paper's own counts do not pin down (fig4a, fig4b: no setting of the port gives them). The question of which comparison and test the paper meant is put to its authors (findings).

Summary¶

Claim Outcome
fig4a-example-sequences-q blocked: methods underspecified (no setting of the port gives the paper's own counts)
fig4b-example-three-segments-q blocked: methods underspecified (as fig4a)
fig4d-sequence-measures-vary reproduced (a weak criterion)
fig4c-sequence-cells-not-clustered blocked: methods underspecified (with the code's double-counting step, no difference within sessions but a difference when pairs are pooled over sessions; the detection is not tied to the paper's)

Differences from the paper's method. The detection is a port of identify_sequences.m to Python, not the MATLAB code itself. The values the paper passed to it (time window, separation, minimum repetitions, sequence lengths) are not recorded; the readings of the claims file are run. The events are the dandiset's, which differ from the paper's per-cell table (first notebook). The counts follow the paper's table in rank but not in size: about three times larger with the double-counting step as the code runs it, and less than half with the step as its comments describe it. A sweep of 32 settings of the window, the separation and the double-counting step finds none that gives the paper's own counts, so the example counts are blocked, not judged.

What was found about the dataset and code. The double-counting step of identify_sequences.m writes 2 into a logical array, so its test never succeeds and it removes nothing. The paper's Figure 4D table counts 17 cells in Q 2022-10-03, 11 in Q 2022-12-01 and 13 in V 2023-03-16, where the dandiset has 18, 13 and 14 accepted cells. For Q 2022-09-15 the table gives n.a. for the first spontaneous 10 min and 13 for the second, while the dandiset's spontaneous file of that session lasts 10 min.