Reproducing Ghaderi, Crochet & Petersen (2026) from dandiset 001530: behaviour, optogenetics and single-neuron analyses¶

Paper. Ghaderi P, Crochet S, Petersen CCH (2026). Contextual gating of whisker-evoked responses by frontal cortex supports flexible decision making. Nature Communications 17, 5982. doi:10.1038/s41467-026-73622-y. The claims file was written from the version of record in Europe PMC (PMC13346651): main text, legends and Methods; the Supplementary Information was not read by the reader.

Dandiset. DANDI:001530, version 0.260605.0601. The paper cites the dandiset without a version. This is the only published version and the most recent one; the draft has the same 196 assets and the same size (2,595,454,486,752 bytes), and it was last modified within seconds of the publication (2026-06-05), so nothing in the draft is newer than what is pinned here.

What is read. The 35 *-processed-behavior.nwb files (Neuropixels units with Allen CCF labels, trials, DeepLabCut traces) and the 91 *-opto-behavior.nwb files (trials of the optogenetic sessions), streamed from the archive. The *-processed-behavior-raw.nwb files and the videos hold the raw voltage and video of the same sessions and are not needed here.

Outside inputs (Zenodo record doi:10.5281/zenodo.17973874, the paper's data and code, read by range requests into memory): data_helpers/Area_list.mat, the CCF labels that make up each of the five areas, and processed_data/Data_Clustering.mat, the paper's cluster label for each neuron (claims cluster-label-link and fig4b-named-clusters), and data_helpers/Lick_times.mat, the detected lick times and lick mask (claims fig8b-lick-coding-direction and figs18-later-lick-coding), fetched by parallel range requests.

The population decoding claims and the clustering of Figure 4a are in decoding_delay.ipynb and decoding_clusters_whisker.ipynb.

Claim Here
fig1c-lick-probabilities, fig1f-movement-latencies, quiet-trials-half tested
fig2-auditory-window, fig2-delay-window, fig2-whisker-window, fig2-wm2-vs-alm-auditory, fig2-other-trial-types tested
units-recorded, fig3a-activity-maps, fig3b-delay-and-response-psth, fig3c-delay-modulation-wm2-alm, fig3d-wm2-infragranular-delay tested
cluster-label-link, fig4b-named-clusters tested (with the paper's cluster labels)
fig5a-single-neuron-context tested
fig6a-pca-delay-states, fig6b-context-coding-direction, fig6c-temporal-correlation tested
fig7b-early-whisker-response, fig7c-no-whisker-cd-change, fig8a-wm2-lick-divergence tested
fig8b-lick-coding-direction, figs18-later-lick-coding tested (with the lick times of data_helpers/Lick_times.mat)
fig5b-context-decoding-delay, fig5b-decoding-time-course decoding_delay.ipynb
fig4-29-clusters, fig5c-cluster-removal, fig5d-null-space-decoding, fig7d-context-decoding-after-whisker decoding_clusters_whisker.ipynb
In [1]:
import time
import warnings
import collections
from concurrent.futures import ThreadPoolExecutor

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

import ghaderi as g

warnings.filterwarnings("ignore", category=RuntimeWarning)
pd.set_option("display.width", 220)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 300)

started = time.time()
print(f"dandiset {g.DANDISET_ID} version {g.DANDISET_VERSION}: {len(g.assets())} assets")
AREA_LIST = g.area_list()
S = g.load_sessions(workers=4)
print(f"loaded {len(S)} ephys sessions in {time.time() - started:.0f} s")
t0 = time.time()
O = g.load_opto()
print(f"loaded {len(O)} optogenetic sessions in {time.time() - t0:.0f} s")
dandiset 001530 version 0.260605.0601: 196 assets
loaded 35 ephys sessions in 187 s
loaded 91 optogenetic sessions in 65 s

Data check¶

Each check of the metadata against the values is stated under its output.

In [2]:
kinds = collections.Counter()
for path, size, _ in g.assets():
    kind = ("ephys processed" if path.endswith("-processed-behavior.nwb") else
            "ephys raw" if path.endswith("-raw.nwb") else
            "video" if path.endswith(".avi") else
            "optogenetics" if path.endswith("-opto-behavior.nwb") else "other")
    kinds[kind] += 1
print("Assets by kind:", dict(kinds))
print("Subjects with ephys:", sorted({s["subject"] for s in S}), "n =", len({s["subject"] for s in S}))
print("Subjects with optogenetics:", sorted({o["subject"] for o in O}), "n =", len({o["subject"] for o in O}))
print("All subjects:", len({s["subject"] for s in S} | {o["subject"] for o in O}), "(archive summary: 21)")
print("\nCCF labels per area (Area_list.mat):")
for a, labels in AREA_LIST.items():
    print(f"  {a}: {len(labels)} labels, e.g. {labels[0].strip()!r}")

rows = []
for s in S:
    tr, c = s["trials"], s["completed"]
    tt = tr["trial_type"]
    rows.append({"session": s["session"], "subject": s["subject"], "trials": len(tt),
                 "completed": int(c.sum()), "early_lick": int((~c).sum()),
                 **{f"type{k}": int(((tt == k) & c).sum()) for k in range(0, 6)},
                 "units": len(s["units"]["location"]), "analysed_units": len(s["keep"]),
                 "probes": ",".join(sorted(set(s["units"]["location"]))),
                 "video_dt_ms": round(s["beh_info"]["video_dt_median_ms"], 3),
                 "unsorted_units": s["unsorted_units"]})
info = pd.DataFrame(rows)
print(info.to_string(index=False))
print("\nTrial type 0 (not one of the five types) in:", info.loc[info.type0 > 0, "session"].tolist())
print("Sessions without No-tone Whisker trials:", info.loc[info.type5 == 0, "session"].tolist())
print("Units whose spike times are not sorted:", int(info.unsorted_units.sum()))
Assets by kind: {'video': 35, 'ephys raw': 35, 'ephys processed': 35, 'optogenetics': 91}
Subjects with ephys: ['PG019', 'PG027', 'PG028', 'PG030', 'PG032', 'PG038', 'PG061', 'PG062', 'PG064', 'PG076', 'PG082', 'PG083', 'PG084', 'PG085'] n = 14
Subjects with optogenetics: ['PG021', 'PG057', 'PG059', 'PG061', 'PG062', 'PG063', 'PG064', 'PG067', 'PG069', 'PG070'] n = 10
All subjects: 21 (archive summary: 21)

CCF labels per area (Area_list.mat):
  A1: 14 labels, e.g. 'Primary auditory area layer 1'
  wS1: 6 labels, e.g. 'Primary somatosensory area barrel field layer 1'
  wS2: 6 labels, e.g. 'Supplemental somatosensory area layer 1'
  wM2: 6 labels, e.g. 'Secondary motor area layer 1'
  ALM: 4 labels, e.g. 'Secondary motor area layer 1'
                      session subject  trials  completed  early_lick  type0  type1  type2  type3  type4  type5  units  analysed_units               probes  video_dt_ms  unsorted_units
sub-PG019_ses-20200904T224847   PG019     695        674          21      0    135    135    135    135    134     75              73                  wS2         10.0               0
sub-PG019_ses-20200906T175456   PG019     623        582          41      0    119    116    115    116    116    154             154                  wS1         10.0               0
sub-PG027_ses-20210403T115220   PG027     713        582         131      0    117    142    123     67    133    139              42  unassigned_area,wS1          5.0               0
sub-PG027_ses-20210404T111739   PG027     586        467         119      0    104    126     95     50     92    165              79  unassigned_area,wS1          5.0               0
sub-PG028_ses-20210318T163504   PG028     836        750          86      9    153    150    152    136    150    128             126              wS1,wS2          5.0               0
sub-PG028_ses-20210319T135422   PG028     862        791          71      0    171    188    165    108    159    147             147              wS1,wS2          5.0               0
sub-PG030_ses-20210405T163808   PG030     539        511          28      0    104    116    102     87    102    270             226              wS1,wS2          5.0               0
sub-PG030_ses-20210406T164509   PG030     386        380           6      0     76    114     79     36     75    222             208              wS1,wS2          5.0               0
sub-PG030_ses-20210407T211250   PG030     396        372          24      0     82    157     59     17     57    240             117  ALM,unassigned_area          5.0               0
sub-PG030_ses-20210408T223046   PG030     208        193          15      0     41     71     31     17     33    234             234              ALM,wM2          5.0               0
sub-PG030_ses-20210410T012800   PG030     220        206          14      0     43     61     43     18     41    241             104  ALM,unassigned_area          5.0               0
sub-PG032_ses-20210711T175822   PG032     424        419           5      0     96     45    174     32     72    233             232              wS1,wS2          5.0               0
sub-PG032_ses-20210712T185829   PG032     522        491          31      0    100     86    133     88     84    187             180              wS1,wS2          5.0               0
sub-PG032_ses-20210715T223447   PG032     530        506          24      0    100     84    197     41     84    335             335              ALM,wM2          5.0               0
sub-PG038_ses-20210316T152753   PG038     437        423          14      0     91     84     86     77     85    284             119              wS1,wS2          5.0               0
sub-PG038_ses-20210317T180556   PG038     329        300          29      0     63     55     72     56     54    265               0  unassigned_area,wS2          5.0               0
sub-PG061_ses-20220211T222307   PG061     651        630          21      0    126     96    126     96    186    442             322     tjM1,wM2,wS1,wS2          5.0               0
sub-PG061_ses-20220212T233813   PG061     676        635          41      0    128    126    127     67    187    480             331      A1,tjM1,wM2,wS2          5.0               0
sub-PG062_ses-20220206T200225   PG062     328        320           8      0     65     61     64     65     65    398             272         tjM1,wM2,wS2          5.0               0
sub-PG062_ses-20220207T213136   PG062     386        362          24      0     73     73     72     72     72    453             211      A1,tjM1,wM2,wS1          5.0               0
sub-PG064_ses-20220209T222403   PG064     646        631          15      0    126    127    126    126    126    254               0 tjM1,unassigned_area          5.0               0
sub-PG064_ses-20220210T183214   PG064     311        308           3      0     63     61     61     62     61    242               0 tjM1,unassigned_area          5.0               0
sub-PG076_ses-20220502T140636   PG076     660        608          52      0    155    149    148    156      0    102               0      unassigned_area          5.0               0
sub-PG082_ses-20221113T145317   PG082     687        662          25      0    134    132    132    132    132    823             588   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG082_ses-20221114T163239   PG082     307        307           0      0     62     60     61     63     61    620             430   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG082_ses-20221120T182616   PG082     629        622           7      0    122    123    126    126    125    823             596   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG083_ses-20221125T180851   PG083     686        636          50      0    127    129    126    127    127    519             420   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG083_ses-20221129T153120   PG083     476        453          23      0     91     90     91     90     91    753             661   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG083_ses-20221130T230127   PG083     641        600          41      0    120    120    120    120    120    628             507   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG084_ses-20221206T162236   PG084     530        508          22      0    102    102    102    101    101    502             470   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG084_ses-20221207T192711   PG084     776        752          24      0    150    151    150    150    151    511             407   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG084_ses-20221208T224009   PG084     649        630          19      0    126    126    126    126    126    676             621   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG085_ses-20221213T195032   PG085     568        533          35      0    105    107    107    107    107    823             787   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG085_ses-20221214T211712   PG085     586        556          30      0    109    111    112    113    111    636             577   A1,ALM,wM2,wS1,wS2          5.0               0
sub-PG085_ses-20221215T222439   PG085     477        440          37      0     89     89     87     86     89    789             718   A1,ALM,wM2,wS1,wS2          5.0               0

Trial type 0 (not one of the five types) in: ['sub-PG028_ses-20210318T163504']
Sessions without No-tone Whisker trials: ['sub-PG076_ses-20220502T140636']
Units whose spike times are not sorted: 0

The archive lists 21 subjects: 14 mice with recordings and 15 with optogenetics, with overlap. The 35 recording sessions in 14 mice are the paper's (Results; the Methods' list sums to 34). Two sessions break the five trial types: one has 11 trials coded trial_type 0, and one has no No-tone trials; both are kept, with type 0 excluded from every trial type. Video frame intervals are 5 ms (200 frames/s) in every session except the two of PG019, at 10 ms, as the Methods say (100 Hz in PG019).

In [3]:
print("Trial timing (completed trials, all sessions):")
ws = np.concatenate([s["trials"]["whisker_stim_time"] - s["trials"]["start_time"] for s in S])
au = np.concatenate([s["trials"]["auditory_stim_time"] - s["trials"]["start_time"] for s in S])
ws, au = ws[np.isfinite(ws)], au[np.isfinite(au)]
print(f"  whisker_stim_time - start_time: {ws.min():.4f} to {ws.max():.4f} s (median {np.median(ws):.4f})")
print(f"  auditory_stim_time - start_time: {au.min():.4f} to {au.max():.4f} s")
lt = np.concatenate([(s["trials"]["lick_time"] - s["trials"]["start_time"])[s["completed"] & s["trials"]["lick_flag"].astype(bool)] for s in S])
print(f"  first lick - start, completed trials with lick_flag: {np.nanmin(lt):.3f} to {np.nanmax(lt):.3f} s")
ctx = collections.Counter()
for s in S:
    for c_, t_ in zip(s["trials"]["context"], s["trials"]["trial_type"]):
        ctx[(c_, t_)] += 1
print("  context and trial_type pairs:", dict(sorted(ctx.items(), key=lambda x: (x[0][1], x[0][0]))))
freq = collections.Counter()
for s in S:
    for c_, f_ in zip(s["trials"]["context"], s["trials"]["auditory_stim_frequency"]):
        freq[(s["subject"], c_, f_)] += 1
print("  Go/Nogo tone frequencies per mouse:",
      sorted({(k[0], k[1], k[2]) for k in freq if k[1] != "no_tone"}))
wd = np.unique(np.concatenate([s["trials"]["whisker_stim_duration"] for s in S]))
print("  whisker_stim_duration values (s):", wd[np.isfinite(wd)])
Trial timing (completed trials, all sessions):
  whisker_stim_time - start_time: 1.0017 to 1.5011 s (median 1.0021)
  auditory_stim_time - start_time: 0.0000 to 0.0000 s
  first lick - start, completed trials with lick_flag: 1.043 to 2.228 s
  context and trial_type pairs: {('no_tone', np.int64(0)): 11, ('go_tone', np.int64(1)): 4002, ('go_tone', np.int64(2)): 4138, ('nogo_tone', np.int64(3)): 3996, ('nogo_tone', np.int64(4)): 3179, ('no_tone', np.int64(5)): 3650}
  Go/Nogo tone frequencies per mouse: [('PG019', 'go_tone', np.float64(4000.0)), ('PG019', 'nogo_tone', np.float64(8000.0)), ('PG027', 'go_tone', np.float64(8000.0)), ('PG027', 'nogo_tone', np.float64(4000.0)), ('PG028', 'go_tone', np.float64(8000.0)), ('PG028', 'nogo_tone', np.float64(4000.0)), ('PG030', 'go_tone', np.float64(8000.0)), ('PG030', 'nogo_tone', np.float64(4000.0)), ('PG032', 'go_tone', np.float64(4000.0)), ('PG032', 'nogo_tone', np.float64(8000.0)), ('PG038', 'go_tone', np.float64(4000.0)), ('PG038', 'nogo_tone', np.float64(8000.0)), ('PG061', 'go_tone', np.float64(4000.0)), ('PG061', 'nogo_tone', np.float64(8000.0)), ('PG062', 'go_tone', np.float64(8000.0)), ('PG062', 'nogo_tone', np.float64(4000.0)), ('PG064', 'go_tone', np.float64(8000.0)), ('PG064', 'nogo_tone', np.float64(4000.0)), ('PG076', 'go_tone', np.float64(8000.0)), ('PG076', 'nogo_tone', np.float64(4000.0)), ('PG082', 'go_tone', np.float64(4000.0)), ('PG082', 'nogo_tone', np.float64(8000.0)), ('PG083', 'go_tone', np.float64(4000.0)), ('PG083', 'nogo_tone', np.float64(8000.0)), ('PG084', 'go_tone', np.float64(8000.0)), ('PG084', 'nogo_tone', np.float64(4000.0)), ('PG085', 'go_tone', np.float64(8000.0)), ('PG085', 'nogo_tone', np.float64(4000.0))]
  whisker_stim_duration values (s): [0.01]

The whisker stimulus is 1.0 s after start_time in every trial and the first lick falls in the 1 s response window (1 to 2 s), as the Methods describe. whisker_stim_duration is 0.01 s, the 10 ms cosine pulse of the Methods (5 ms at half maximum). Each mouse has one Go and one Nogo frequency (4 or 8 kHz).

In [4]:
rows = []
for s in S:
    b, inf = s["beh"], s["beh_info"]
    rows.append({"session": s["session"], "frames": inf["video_n_frames"],
                 "video_s": f"{inf['video_t0']:.0f}-{inf['video_t1']:.0f}",
                 "trials_s": f"{s['trials']['start_time'][0]:.0f}-{s['trials']['start_time'][-1]:.0f}",
                 "trials_no_video": int(np.isnan(b["whisker_speed"]).all(axis=1).sum()),
                 "angle_deg": f"{inf['whisker_angle_range'][0]:.0f}-{inf['whisker_angle_range'][1]:.0f}",
                 "jaw_px_max": round(float(np.nanmax(b["jaw_movement"])), 1),
                 "quiet_median_%": round(100 * (s["quiet_median"]["whisker_speed"] & s["quiet_median"]["jaw_movement"]).mean(), 1),
                 "quiet_mean_%": round(100 * (s["quiet_mean"]["whisker_speed"] & s["quiet_mean"]["jaw_movement"]).mean(), 1)})
beh_info = pd.DataFrame(rows)
print(beh_info.to_string(index=False))
print("Trials with no video in their -1 to 2 s window:", int(beh_info.trials_no_video.sum()), "of", int(info.trials.sum()))
                      session  frames  video_s trials_s  trials_no_video angle_deg  jaw_px_max  quiet_median_%  quiet_mean_%
sub-PG019_ses-20200904T224847  783657  24-7865  33-7852                3    45-287        52.0            54.7          68.6
sub-PG019_ses-20200906T175456  754689  13-7564  19-7558               10    29-267       222.3            41.7          50.9
sub-PG027_ses-20210403T115220 1646846  40-8548  26-8539                1    91-346       180.6            24.5          31.6
sub-PG027_ses-20210404T111739 1355716 342-7344 329-7335                1     0-360        41.8            43.5          59.4
sub-PG028_ses-20210318T163504 1949936 55-10130 42-10122                6     1-359       106.2            34.2          41.7
sub-PG028_ses-20210319T135422 1942010 84-10119 71-10113                5   222-318        51.5            48.0          62.8
sub-PG030_ses-20210405T163808 1202128  59-6273  46-6254                1     0-360        45.6            46.2          63.3
sub-PG030_ses-20210406T164509  871360  35-4534  22-4519                1   239-345        38.2            35.8          49.0
sub-PG030_ses-20210407T211250  882138  69-4622  56-4617                1   241-344        43.7            29.8          43.2
sub-PG030_ses-20210408T223046  478532  48-2512  35-2504                1   244-351        36.3            38.5          53.4
sub-PG030_ses-20210410T012800  492389  58-2601  45-2594                1   221-342        28.5            52.3          66.4
sub-PG032_ses-20210711T175822 1079120  42-5610  28-5603                1   240-322        48.6            50.5          63.0
sub-PG032_ses-20210712T185829 1196824  49-6226  35-6220                1   248-346        43.7            53.3          67.0
sub-PG032_ses-20210715T223447 1201177  48-6257  35-6250                1     0-359        41.8            51.1          62.6
sub-PG038_ses-20210316T152753  929904 400-5202  87-5194               29     0-360       214.8            41.6          57.2
sub-PG038_ses-20210317T180556  745605  36-3886  23-3879                1   267-293        26.6            53.2          57.8
sub-PG061_ses-20220211T222307 1475942  50-7686  25-7675                2   218-343       101.4            48.1          60.1
sub-PG061_ses-20220212T233813 1010803  60-5277  35-8072              243    83-318        78.3            27.4          32.4
sub-PG062_ses-20220206T200225  759195  50-3968  37-3955                1     1-360        81.9            56.4          68.3
sub-PG062_ses-20220207T213136  859069  95-4533  82-4524                1    84-316       148.9            44.6          55.2
sub-PG064_ses-20220209T222403 1476209  54-7686  41-7647                5   224-331        83.0            29.4          43.0
sub-PG064_ses-20220210T183214  693422  61-3653  25-3645                2   226-317        56.4            33.1          41.2
sub-PG076_ses-20220502T140636 1521064  39-7899  26-7894               11     0-360       126.7            47.4          62.4
sub-PG082_ses-20221113T145317 1556177  38-8074  25-8068                1    64-352        44.6            40.8          64.3
sub-PG082_ses-20221114T163239  689606  39-3599  25-3585                1   227-355        39.9            40.4          69.4
sub-PG082_ses-20221120T182616 1424343  40-7396  27-7387                1     0-360        42.7            44.4          65.8
sub-PG083_ses-20221125T180851 1563890  51-8134  38-8121                1   214-360        54.4            42.4          62.8
sub-PG083_ses-20221129T153120 1070001  46-5569  33-5562                1   218-324        68.9            43.7          67.6
sub-PG083_ses-20221130T230127 1463411  56-7617  42-7612                1   212-326        55.9            43.7          59.4
sub-PG084_ses-20221206T162236 1264786  44-6582  31-6567                1   222-350        98.3            34.5          54.7
sub-PG084_ses-20221207T192711 1754436  54-9121  41-9111                1     0-360        66.1            48.6          66.9
sub-PG084_ses-20221208T224009 1458576  50-7587  37-7582                1     0-360        61.3            46.1          63.0
sub-PG085_ses-20221213T195032 1271681  51-6623  25-6618                2   227-359        59.3            53.2          64.1
sub-PG085_ses-20221214T211712 1323514  96-6937  69-6933                2     0-360        53.3            51.0          66.6
sub-PG085_ses-20221215T222439 1067386  55-5565  42-5556                1     0-360        55.5            50.1          65.6
Trials with no video in their -1 to 2 s window: 343 of 18976

Whisker angle is in degrees and jaw and tongue in pixels, as the files state. Video covers almost every trial: every session has at least one trial without video frames in its -1 to 2 s window (the total is printed above), and two have many, 243 trials in sub-PG061_ses-20220212T233813 and 29 in sub-PG038_ses-20210316T152753. Those trials cannot pass the quiet rule and are counted as not quiet, as the paper's code counts them (a NaN fails its comparison; quiet-trials-half below).

In [5]:
# Shared clock of spikes and trials: whisker-evoked response (1.00 to 1.03 s) in whisker against
# no-whisker trials, in wS1 and wS2, with true and with trial labels shifted by one trial.
rows = []
w, b = g.bin_index(1.01, 1.03), g.bin_index(0.8, 1.0)
for k, s in enumerate(S):
    tt = s["trials"]["trial_type"][s["completed"]]
    whisk = np.isin(tt, [1, 3, 5])
    for a in ("wS1", "wS2", "A1", "all units"):
        cols = np.arange(len(s["keep"])) if a == "all units" else g.area_columns(s, a)
        if len(cols) < 5:
            continue
        x = s["c10"][:, :, cols].astype(float)
        if a == "A1":   # auditory response 0 to 30 ms, tone against no-tone trials
            resp = x[:, g.bin_index(0.01, 0.03)].mean(axis=(1, 2)) - x[:, g.bin_index(-0.2, 0.0)].mean(axis=(1, 2))
            lab = np.isin(tt, [1, 2, 3, 4])
        else:
            resp = x[:, w].mean(axis=(1, 2)) - x[:, b].mean(axis=(1, 2))
            lab = whisk
        rows.append({"session": s["session"], "area": a,
                     "contrast_true": (resp[lab].mean() - resp[~lab].mean()) / g.W10,
                     "contrast_shifted": (resp[np.roll(lab, 1)].mean() - resp[~np.roll(lab, 1)].mean()) / g.W10})
clock = pd.DataFrame(rows)
print("Stimulus-evoked change in rate (Hz per neuron), stimulus minus no-stimulus trials:")
print(clock.groupby("area")[["contrast_true", "contrast_shifted"]].describe().round(2).T.to_string())
print("\nArea-sessions where the true contrast is not above the shifted one:")
print(clock[clock.contrast_true <= clock.contrast_shifted].to_string(index=False))
print("Sessions with no wS1, wS2 or A1 area of 5 units (checked with all units only):",
      sorted(set(clock.session) - set(clock[clock.area != "all units"].session)))
print("Sessions with fewer than 5 analysed units (not checked):", [s["session"] for s in S if len(s["keep"]) < 5])
Stimulus-evoked change in rate (Hz per neuron), stimulus minus no-stimulus trials:
area                       A1  all units    wS1    wS2
contrast_true    count  14.00      31.00  24.00  19.00
                 mean    5.67       3.34   6.63   5.43
                 std     5.95       2.46   2.62   2.15
                 min     0.40      -0.04   0.13   0.23
                 25%     3.20       1.73   5.04   4.21
                 50%     4.56       2.67   6.47   5.80
                 75%     5.19       4.08   8.24   6.60
                 max    25.15      10.16  12.45   9.35
contrast_shifted count  14.00      31.00  24.00  19.00
                 mean   -0.34      -0.19  -0.33  -0.21
                 std     0.81       0.36   0.41   0.48
                 min    -2.53      -1.00  -1.00  -0.92
                 25%    -0.52      -0.26  -0.46  -0.45
                 50%    -0.27      -0.18  -0.31  -0.28
                 75%     0.05      -0.09  -0.18  -0.12
                 max     0.98       1.30   1.10   1.53

Area-sessions where the true contrast is not above the shifted one:
Empty DataFrame
Columns: [session, area, contrast_true, contrast_shifted]
Index: []
Sessions with no wS1, wS2 or A1 area of 5 units (checked with all units only): ['sub-PG030_ses-20210407T211250', 'sub-PG030_ses-20210408T223046', 'sub-PG030_ses-20210410T012800', 'sub-PG032_ses-20210715T223447']
Sessions with fewer than 5 analysed units (not checked): ['sub-PG038_ses-20210317T180556', 'sub-PG064_ses-20220209T222403', 'sub-PG064_ses-20220210T183214', 'sub-PG076_ses-20220502T140636']

In every area-session the whisker-evoked response in wS1 and wS2 and the tone-evoked response in A1 are larger in the trials that had the stimulus than in those that did not, and the contrast vanishes when the labels are shifted by one trial (table above). The sessions with only frontal units are checked with all their units pooled (whisker-evoked response, 1.00 to 1.03 s). Spikes and the trial table share a clock in each session tested this way. sub-PG038_ses-20210317T180556 keeps no unit after the CCF filter, so it is not checked and enters only the behavioural claims.

In [6]:
# Recordings deposited twice: compare unit counts, spike counts and trial start times.
sig = collections.defaultdict(list)
for s in S:
    sig[(len(s["units"]["location"]), s["n_spikes"])].append(s["session"])
    sig[("trials", round(float(s["trials"]["start_time"][0]), 3), len(s["trials"]["start_time"]))].append(s["session"])
dups = {k: v for k, v in sig.items() if len(v) > 1}
print("Sessions sharing a unit and spike count, or trial start times:", dups if dups else "none")
print("Subjects and sessions:", info.groupby("subject").session.count().to_dict())
same_day = info.assign(day=info.session.str[:22]).groupby("day").session.count()
print("More than one file on a day:", same_day[same_day > 1].to_dict() or "none")
Sessions sharing a unit and spike count, or trial start times: none
Subjects and sessions: {'PG019': 2, 'PG027': 2, 'PG028': 2, 'PG030': 5, 'PG032': 3, 'PG038': 2, 'PG061': 2, 'PG062': 2, 'PG064': 2, 'PG076': 1, 'PG082': 3, 'PG083': 3, 'PG084': 3, 'PG085': 3}
More than one file on a day: none

No two files share their unit and spike counts or their trial times; each recording is counted once. Units are not followed across sessions in any claim here.

In [7]:
rows = []
for o in O:
    tr = o["trials"]
    rows.append({"subject": o["subject"], "session": o["path"].split("/")[-1][:30], "area": o["area"],
                 "genotype": o["genotype"], "trials": len(tr["trial_type"]),
                 **{w_: int((tr["opto_window"] == w_).sum()) for w_ in ("nolight", "audio", "delay", "whisker")},
                 "power_mW": ",".join(f"{v:g}" for v in np.unique(tr["opto_stim_amplitude"][np.isfinite(tr["opto_stim_amplitude"])])),
                 "freq_Hz": ",".join(f"{v:g}" for v in np.unique(tr["opto_stim_frequency"][np.isfinite(tr["opto_stim_frequency"])]))})
opto_info = pd.DataFrame(rows)
print(opto_info.groupby("area").agg(sessions=("session", "count"), mice=("subject", "nunique")).to_string())
print("\nGenotype field:", opto_info.genotype.value_counts().to_dict())
print(opto_info[opto_info.genotype != "VGAT_ChR2-eYFP"].to_string(index=False))
print("\nWindows used per session:", collections.Counter(tuple(w_ for w_ in ("audio", "delay", "whisker") if r[w_] > 0) for _, r in opto_info.iterrows()))
print("Light trials, fraction of all:", round(opto_info[["audio", "delay", "whisker"]].sum().sum() / opto_info.trials.sum(), 3))
print("Laser power values (mW):", sorted({p for v in opto_info.power_mW for p in v.split(",") if p}))
print("Pulse frequency values (Hz):", sorted({p for v in opto_info.freq_Hz for p in v.split(",") if p}))
      sessions  mice
area                
A1          19     9
ALM          9     7
fpS1         9     8
wM2         14     9
wS1         20    10
wS2         20    10

Genotype field: {'VGAT_ChR2-eYFP': 79, 'C57BL/6JRj': 12}
subject                        session area   genotype  trials  nolight  audio  delay  whisker power_mW freq_Hz
  PG021 sub-PG021_ses-20200913T000000-  wS1 C57BL/6JRj    1951     1359      0      0      592       12     100
  PG061 sub-PG061_ses-20211203T000000-   A1 C57BL/6JRj     514      345     57     55       57       12     100
  PG061 sub-PG061_ses-20211207T000000-  wM2 C57BL/6JRj     182      121     20     20       21       12     100
  PG061 sub-PG061_ses-20211208T000000-  wM2 C57BL/6JRj     433      286     46     48       53       12     100
  PG061 sub-PG061_ses-20211210T000000-   A1 C57BL/6JRj     832      566     87     87       92       12     100
  PG061 sub-PG061_ses-20211216T000000-  wS1 C57BL/6JRj     485      318     55     54       58       12     100
  PG061 sub-PG061_ses-20211217T000000-  wS1 C57BL/6JRj     428      288     48     45       47       12     100
  PG061 sub-PG061_ses-20211218T000000-  wS2 C57BL/6JRj     494      334     51     53       56       12     100
  PG061 sub-PG061_ses-20211219T000000-  wS2 C57BL/6JRj     400      270     43     43       44       12     100
  PG061 sub-PG061_ses-20211220T000000-   A1 C57BL/6JRj     282      185     29     33       35       12     100
  PG061 sub-PG061_ses-20220106T000000-  ALM C57BL/6JRj     693      460     77     71       85       12     100
  PG061 sub-PG061_ses-20220110T000000- fpS1 C57BL/6JRj     306      206     35     32       33       12     100

Windows used per session: Counter({('audio', 'delay', 'whisker'): 81, ('whisker',): 6, ('audio',): 2, ('delay',): 2})
Light trials, fraction of all: 0.318
Laser power values (mW): ['12']
Pulse frequency values (Hz): ['100']

The 91 optogenetic sessions cover the six areas with 9 to 20 sessions each; mice per area are A1 9, wS1 10, wS2 10, wM2 9, ALM 7 and fpS1 8, where the Methods give 8 mice for ALM. Each session inactivates one area in one window. Twelve sessions (mice PG021 and PG061) give the genotype C57BL/6JRj, which carries no ChR2, although the paper inactivates only VGAT-ChR2 mice; their light trials still reduce licking (see fig2 below), so the genotype field is likely wrong for these mice. The trials table describes opto_area as "laser light duration" and opto_stim_start_time as "Pulse duration in s", which do not fit their values.

fig1c-lick-probabilities¶

Mice lick in the response window on 78 +/- 2% of Go-tone Whisker trials and withhold licking in the other trial types (Go-tone No-Whisker 10 +/- 1%, Nogo-tone Whisker 13 +/- 2%, Nogo-tone No-Whisker 1 +/- 0.3%, No-tone Whisker 15 +/- 2%), mean +/- SEM over 35 recording sessions in 14 mice.

As the criterion (code, Ghaderi2025_Figure1_c_Performance.m): completed trials, lick_flag, mean and SEM over sessions.

In [8]:
P = []
for s in S:
    tr, c = s["trials"], s["completed"]
    tt, L = tr["trial_type"], tr["lick_flag"].astype(bool)
    P.append({"session": s["session"], "subject": s["subject"],
              **{g.TRIAL_NAMES[k]: (100 * L[c & (tt == k)].mean() if (c & (tt == k)).any() else np.nan) for k in range(1, 6)}})
P = pd.DataFrame(P)
expected = {"Go-tone Whisker": (78, 2), "Go-tone No-Whisker": (10, 1), "Nogo-tone Whisker": (13, 2),
            "Nogo-tone No-Whisker": (1, 0.3), "No-tone Whisker": (15, 2)}
rows = []
for name, (v, tol) in expected.items():
    x = P[name].dropna()
    rows.append({"trial type": name, "sessions": len(x), "mean %": round(x.mean(), 2),
                 "SEM": round(x.std(ddof=1) / np.sqrt(len(x)), 2), "paper": f"{v} +/- {tol}",
                 "within": abs(x.mean() - v) <= tol, "min": round(x.min(), 1), "max": round(x.max(), 1)})
fig1c = pd.DataFrame(rows)
print(fig1c.to_string(index=False))
print("\nPer mouse (mean over its sessions):")
print(P.groupby("subject")[list(expected)].mean().round(1).to_string())
          trial type  sessions  mean %  SEM     paper  within  min   max
     Go-tone Whisker        35   78.18 2.08  78 +/- 2    True 34.8 100.0
  Go-tone No-Whisker        35    9.90 1.49  10 +/- 1    True  0.0  31.0
   Nogo-tone Whisker        35   13.08 1.79  13 +/- 2    True  0.0  39.1
Nogo-tone No-Whisker        35    1.05 0.26 1 +/- 0.3    True  0.0   5.9
     No-tone Whisker        34   14.64 1.72  15 +/- 2    True  0.0  41.4

Per mouse (mean over its sessions):
         Go-tone Whisker  Go-tone No-Whisker  Nogo-tone Whisker  Nogo-tone No-Whisker  No-tone Whisker
subject                                                                                               
PG019               47.7                 9.7               24.9                   1.2              6.9
PG027               67.3                14.4               19.1                   2.7             16.6
PG028               78.7                22.3               16.3                   1.9             18.2
PG030               89.3                24.0                8.0                   1.2              9.9
PG032               73.4                 3.5               34.5                   0.4             18.1
PG038               76.1                 4.2                4.6                   4.0             11.9
PG061               73.7                 5.8                4.7                   0.0             39.4
PG062               74.0                 1.5                7.7                   1.4              9.9
PG064              100.0                 6.0                1.6                   0.0              1.2
PG076               75.5                 4.0               33.8                   0.6              NaN
PG082               81.0                 5.4                4.3                   0.0             14.7
PG083               77.4                 8.6               14.6                   0.3             21.0
PG084               86.3                 9.9                9.5                   0.3             15.1
PG085               75.2                 4.0               12.5                   1.7             11.1

Result: reproduced. Over the 35 sessions (34 for No-tone Whisker, which one session lacks), P(lick) is 78.18 +/- 2.08% for Go-tone Whisker, 9.90 +/- 1.49% Go-tone No-Whisker, 13.08 +/- 1.79% Nogo-tone Whisker, 1.05 +/- 0.26% Nogo-tone No-Whisker and 14.64 +/- 1.72% No-tone Whisker: all five means are within tolerance.

fig1f-movement-latencies¶

In quiet Hit trials the whisker deflection is followed by whisker protraction (time to 20% of maximum 58 +/- 8 ms), jaw opening (115 +/- 17 ms) and tongue protrusion (231 +/- 29 ms), and tongue-spout contact at 330 +/- 20 ms.

Traces as code, Ghaderi2025_Figure1_f_Movements_Hit.m (quiet completed Hit trials, 10 ms bins, each trial minus its mean over 0.8 to 1.0 s; NaN tongue values set to 0 as the code does). Readings (a) and (b) of the criterion, with the maximum over 1.0 to 2.0 s, the 1 s response window after the whisker stimulus (Methods, Mouse behavior), as the claims file has it since a reader answered the question on the window. The lick latency as Ghaderi2025_Sup_Figure1_b_SpoutReactionTime.m. A latency is the right edge of the first bin after 1.0 s that reaches 20% of the maximum, minus 1.0 s. As variants the maximum is taken over 1.0 to 1.2 s (the Fig. 1f plot window, the criterion's window before the answer) and 1.0 to 1.5 s, and the quiet rule uses the code's mean absolute deviation.

In [9]:
labels10 = g.PRE + g.W10 * np.arange(1, g.N10 + 1)
base_bins = g.bin_index(0.8, 1.0)


def latency_ms(trace, post):
    seg = trace[post]
    mx = np.nanmax(seg) if np.isfinite(seg).any() else np.nan
    if not np.isfinite(mx) or mx <= 0:
        return np.nan
    hit = np.flatnonzero(seg >= 0.2 * mx)
    hit = hit[labels10[post][hit] > 1.0]
    return (labels10[post][hit[0]] - 1.0) * 1000 if len(hit) else np.nan


def movement_latencies(rule="median", end=2.0):
    post = g.bin_index(1.0, end)
    out = []
    for s in S:
        sel = g.trial_mask(s, 1, True) & g.quiet_mask(s, rule)
        row = {"session": s["session"], "subject": s["subject"], "n_trials": int(sel.sum())}
        for sigl in ("whisker_speed", "jaw_movement", "tongue_movement"):
            x = s["beh"][sigl][s["completed"]][sel].copy()
            if sigl == "tongue_movement":
                x = np.where(np.isnan(x), 0, x)
            x = x - np.nanmean(x[:, base_bins], axis=1, keepdims=True)
            row[f"{sigl}_a"] = latency_ms(np.nanmean(x, axis=0), post) if len(x) else np.nan
            row[f"{sigl}_b"] = np.nanmean([latency_ms(t, post) for t in x]) if len(x) else np.nan
        out.append(row)
    return pd.DataFrame(out)


lick_rows = []
for s in S:
    tr, c = s["trials"], s["completed"]
    rt = tr["lick_time"] - tr["start_time"]
    rt[(rt > 2) | (rt < 1)] = np.nan
    hit = (tr["trial_type"] == 1) & tr["lick_flag"].astype(bool) & c
    lick_rows.append(np.nanmean((rt - 1)[hit]) * 1000)
lick = np.array(lick_rows)
print(f"Lick latency (all completed Hit trials): {lick.mean():.1f} +/- {lick.std(ddof=1) / np.sqrt(len(lick)):.1f} ms "
      f"(n = {len(lick)} sessions; paper 330 +/- 20)")


def summarise(df, label):
    rows = []
    for sigl, (v, tol) in {"whisker_speed": (58, 8), "jaw_movement": (115, 17), "tongue_movement": (231, 29)}.items():
        for r in "ab":
            x = df[f"{sigl}_{r}"].dropna()
            rows.append({"variant": label, "signal": sigl, "reading": r, "sessions": len(x),
                         "mean ms": round(x.mean(), 1), "SEM": round(x.std(ddof=1) / np.sqrt(len(x)), 1),
                         "paper": f"{v} +/- {tol}", "within": abs(x.mean() - v) <= tol})
    return pd.DataFrame(rows)


lat = movement_latencies()
print("\nSessions with no quiet Hit trial:", lat.loc[lat.n_trials == 0, "session"].tolist())
print(summarise(lat, "criterion, max over 1.0-2.0 s").to_string(index=False))
order = {r: [lat[f"{x}_{r}"].mean() for x in ("whisker_speed", "jaw_movement", "tongue_movement")] + [lick.mean()]
         for r in "ab"}
for r, v in order.items():
    print(f"reading ({r}): whisker < jaw < tongue < spout contact: {all(np.diff(v) > 0)} ({', '.join(f'{x:.1f}' for x in v)} ms)")
print("\nCriterion window, latencies (ms) by subject (mean over sessions; reading a / reading b):")
cols = [f"{x}_{r}" for x in ("whisker_speed", "jaw_movement", "tongue_movement") for r in "ab"]
print(lat[lat.n_trials > 0].groupby("subject")[cols].mean().round(1).to_string())
print("\nCriterion window, median over sessions (ms):", lat[cols].median().round(1).to_dict())
for end in (1.2, 1.5):
    print(summarise(movement_latencies(end=end), f"variant, max over 1.0-{end} s").to_string(index=False))
print(summarise(movement_latencies("mean"), "variant, code's MAD, 1.0-2.0 s").to_string(index=False))
Lick latency (all completed Hit trials): 330.1 +/- 20.2 ms (n = 35 sessions; paper 330 +/- 20)

Sessions with no quiet Hit trial: ['sub-PG064_ses-20220210T183214']
                      variant          signal reading  sessions  mean ms  SEM      paper  within
criterion, max over 1.0-2.0 s   whisker_speed       a        34     54.4  4.4   58 +/- 8    True
criterion, max over 1.0-2.0 s   whisker_speed       b        34     94.6  8.6   58 +/- 8   False
criterion, max over 1.0-2.0 s    jaw_movement       a        34    115.3 15.3 115 +/- 17    True
criterion, max over 1.0-2.0 s    jaw_movement       b        34    142.9 11.1 115 +/- 17   False
criterion, max over 1.0-2.0 s tongue_movement       a        34    192.4 18.4 231 +/- 29   False
criterion, max over 1.0-2.0 s tongue_movement       b        34    254.6 21.0 231 +/- 29    True
reading (a): whisker < jaw < tongue < spout contact: True (54.4, 115.3, 192.4, 330.1 ms)
reading (b): whisker < jaw < tongue < spout contact: True (94.6, 142.9, 254.6, 330.1 ms)

Criterion window, latencies (ms) by subject (mean over sessions; reading a / reading b):
         whisker_speed_a  whisker_speed_b  jaw_movement_a  jaw_movement_b  tongue_movement_a  tongue_movement_b
subject                                                                                                        
PG019               60.0            146.2           315.0           160.8              385.0              468.1
PG027               35.0             52.9           115.0           192.8              160.0              265.9
PG028               45.0             73.3           105.0           152.8              180.0              252.4
PG030               44.0             76.1           122.0           186.0              250.0              353.6
PG032              100.0            176.4           156.7           218.6              200.0              293.8
PG038               40.0             60.4            95.0           120.0              205.0              257.4
PG061               50.0             79.9           105.0           137.2              285.0              373.3
PG062               90.0            173.4           105.0           200.9              190.0              292.8
PG064               50.0             55.0            90.0            85.0              150.0              160.0
PG076               70.0            131.4           110.0           127.9              130.0              163.9
PG082               40.0             74.6            83.3            91.0              130.0              139.7
PG083               53.3             82.1            83.3           104.5              126.7              177.6
PG084               43.3             70.4            76.7            86.3              143.3              151.2
PG085               53.3             88.2            76.7            95.2              133.3              153.1

Criterion window, median over sessions (ms): {'whisker_speed_a': 50.0, 'whisker_speed_b': 83.0, 'jaw_movement_a': 95.0, 'jaw_movement_b': 121.1, 'tongue_movement_a': 155.0, 'tongue_movement_b': 204.7}
                    variant          signal reading  sessions  mean ms  SEM      paper  within
variant, max over 1.0-1.2 s   whisker_speed       a        34     48.2  2.9   58 +/- 8   False
variant, max over 1.0-1.2 s   whisker_speed       b        34     65.2  2.7   58 +/- 8    True
variant, max over 1.0-1.2 s    jaw_movement       a        34     81.5  3.6 115 +/- 17   False
variant, max over 1.0-1.2 s    jaw_movement       b        34     83.3  2.4 115 +/- 17   False
variant, max over 1.0-1.2 s tongue_movement       a        27    140.0  5.5 231 +/- 29   False
variant, max over 1.0-1.2 s tongue_movement       b        27    153.6  4.1 231 +/- 29   False
                    variant          signal reading  sessions  mean ms  SEM      paper  within
variant, max over 1.0-1.5 s   whisker_speed       a        34     54.1  4.4   58 +/- 8    True
variant, max over 1.0-1.5 s   whisker_speed       b        34     79.7  6.1   58 +/- 8   False
variant, max over 1.0-1.5 s    jaw_movement       a        34     94.7  5.4 115 +/- 17   False
variant, max over 1.0-1.5 s    jaw_movement       b        34    117.9  6.2 115 +/- 17    True
variant, max over 1.0-1.5 s tongue_movement       a        33    171.5  9.4 231 +/- 29   False
variant, max over 1.0-1.5 s tongue_movement       b        33    218.5 13.5 231 +/- 29    True
                       variant          signal reading  sessions  mean ms  SEM      paper  within
variant, code's MAD, 1.0-2.0 s   whisker_speed       a        35     50.9  4.7   58 +/- 8    True
variant, code's MAD, 1.0-2.0 s   whisker_speed       b        35     93.5  9.5   58 +/- 8   False
variant, code's MAD, 1.0-2.0 s    jaw_movement       a        35    118.0 15.9 115 +/- 17    True
variant, code's MAD, 1.0-2.0 s    jaw_movement       b        35    146.8 10.7 115 +/- 17   False
variant, code's MAD, 1.0-2.0 s tongue_movement       a        35    196.0 18.6 231 +/- 29   False
variant, code's MAD, 1.0-2.0 s tongue_movement       b        35    258.4 21.0 231 +/- 29    True
In [10]:
fig, ax = plt.subplots(figsize=(6, 3.5))
t = labels10[g.bin_index(0.8, 2.0)]
for sigl, col in zip(("whisker_speed", "jaw_movement", "tongue_movement"), ("m", "c", "orange")):
    traces = []
    for s in S:
        sel = g.trial_mask(s, 1, True) & g.quiet_mask(s)
        if sel.sum() == 0:
            continue
        x = s["beh"][sigl][s["completed"]][sel].copy()
        if sigl == "tongue_movement":
            x = np.where(np.isnan(x), 0, x)
        x = x - np.nanmean(x[:, base_bins], axis=1, keepdims=True)
        traces.append(np.nanmean(x, axis=0)[g.bin_index(0.8, 2.0)])
    m = np.nanmean(traces, axis=0)
    ax.plot(t, m / np.nanmax(m), color=col, label=sigl)
    print(f"{sigl}: grand-mean trace, max at {t[np.nanargmax(m)]:.2f} s; normalised range {np.nanmin(m / np.nanmax(m)):.2f} to 1")
ax.axvline(1.0, color="k", lw=0.5)
ax.axvline(1.2, color="grey", ls="--", lw=0.5)  # end of the Fig. 1f plot and of the 1.2 s variant
ax.set_xlabel("time from trial start (s)")
ax.set_ylabel("movement / max")
ax.legend(fontsize=8)
plt.show()
whisker_speed: grand-mean trace, max at 1.19 s; normalised range -0.01 to 1
jaw_movement: grand-mean trace, max at 1.34 s; normalised range -0.00 to 1
tongue_movement: grand-mean trace, max at 1.35 s; normalised range 0.00 to 1
No description has been provided for this image

Result: partially reproduced. The lick latency is 330.1 +/- 20.2 ms, as the paper reports. With the maximum over 1.0 to 2.0 s, as the claims file now has it, reading (a) gives whisker 54.4, jaw 115.3 and tongue 192.4 ms and reading (b) 94.6, 142.9 and 254.6 ms, against 58, 115 and 231 ms. Under reading (a) the whisker and jaw latencies are within tolerance and the tongue latency is 38.6 ms short of 231, outside the 29 ms tolerance; under reading (b) only the tongue latency is within tolerance. The order whisker, jaw, tongue, spout contact holds under both readings, so both give the criterion's partial case. The session means are pulled up by a few late sessions: the medians over sessions under reading (a) are 50.0, 95.0 and 155.0 ms, and the two PG019 sessions average a jaw latency of 315.0 ms and a tongue latency of 385.0 ms. With the maximum over 1.0 to 1.2 s (the window before the reader's answer) no movement latency under reading (a) and only the whisker latency under reading (b) is within tolerance, and with the code's mean absolute deviation for the quiet rule the values are close to the criterion's (50.9, 118.0 and 196.0 ms under reading a).

quiet-trials-half¶

Selecting quiet trials (no whisker or jaw movement in the last 200 ms of the delay) rejects about half of the recorded trials.

In [11]:
rows = []
for rule in ("median", "mean"):
    for reading, use_completed in (("a, completed trials", True), ("b, all trials", False)):
        rej, tot, per = 0, 0, []
        for s in S:
            q = s[f"quiet_{rule}"]
            quiet = q["whisker_speed"] & q["jaw_movement"]
            sel = s["completed"] if use_completed else np.ones(len(quiet), bool)
            rej += int((~quiet[sel]).sum())
            tot += int(sel.sum())
            per.append(100 * (~quiet[sel]).mean())
        rows.append({"MAD": rule, "reading": reading, "trials": tot, "rejected": rej,
                     "pooled %": round(100 * rej / tot, 2), "median over sessions %": round(np.median(per), 2),
                     "range over sessions %": f"{min(per):.1f}-{max(per):.1f}", "within 45-55": abs(100 * rej / tot - 50) <= 5})
quiet_tab = pd.DataFrame(rows)
print(quiet_tab.to_string(index=False))
# Variant: trials without video left out of the denominator.
rej = tot = 0
for s in S:
    q = s["quiet_median"]
    has_video = ~np.isnan(s["beh"]["whisker_speed"]).all(axis=1)
    sel = s["completed"] & has_video
    rej += int((~(q["whisker_speed"] & q["jaw_movement"]))[sel].sum())
    tot += int(sel.sum())
print(f"\nVariant, completed trials with video only (median MAD): {100 * rej / tot:.2f}% rejected of {tot}")
for sigl in ("whisker_speed", "jaw_movement"):
    r_ = np.concatenate([~s["quiet_median"][sigl][s["completed"]] for s in S]).mean()
    print(f"Rejected by {sigl} alone (median MAD, completed): {100 * r_:.1f}%")
   MAD             reading  trials  rejected  pooled %  median over sessions % range over sessions %  within 45-55
median a, completed trials   17840      9823     55.06                   53.33             42.2-75.9         False
median       b, all trials   18976     10764     56.72                   55.64             43.6-75.5         False
  mean a, completed trials   17840      7175     40.22                   35.55             29.4-68.0         False
  mean       b, all trials   18976      8019     42.26                   37.36             30.6-68.4         False

Variant, completed trials with video only (median MAD): 54.22% rejected of 17512
Rejected by whisker_speed alone (median MAD, completed): 38.3%
Rejected by jaw_movement alone (median MAD, completed): 36.3%
In [12]:
# How the paper's code treats trials without video (verifier's question). The code's lines:
print(g.code_lines("functions/nwb_findQuietTrial.m", r"nanmean|TH=|thereshold=TH|ind_quiete=prewhiskvalue<="))
print(g.code_lines("functions/PSTHBehavior.m", r"Mean_Signal\(1:length\(RelativeFrame\),AnchorTimeIndex\)=nan"))
# nanmedian ignores NaN, MATLAB's mad() removes NaN values (its documented behaviour), so the
# threshold is finite; a trial whose pre-stimulus mean is NaN fails "prewhiskvalue <= thereshold".
rows = []
base_bins, pre_bins = g.bin_index(-1.0, 0.0), g.bin_index(0.8, 1.0)
for s in S:
    r = {"session": s["session"], "trials": len(s["completed"])}
    nan_any_base = np.zeros(len(s["completed"]), bool)
    for sig in ("whisker_speed", "jaw_movement"):
        x = s["beh"][sig]
        r[f"NaN baseline {sig}"] = int(np.isnan(x[:, base_bins]).all(axis=1).sum())
        r[f"NaN pre-stimulus {sig}"] = int(np.isnan(x[:, pre_bins]).all(axis=1).sum())
        nan_any_base |= np.isnan(x[:, base_bins]).all(axis=1)
    r["NaN in either"] = int(nan_any_base.sum())
    rows.append(r)
nan_tab = pd.DataFrame(rows)
print(nan_tab[nan_tab["NaN in either"] > 0].to_string(index=False))
print("Sessions with any NaN baseline or pre-stimulus mean:", int((nan_tab["NaN in either"] > 0).sum()), "of", len(nan_tab))
# Under a median without NaN handling one NaN would make the threshold NaN and every trial of the
# session non-quiet; the code calls nanmedian, so this is shown only as the verifier's bound.
rej = tot = 0
for s, (_, r) in zip(S, nan_tab.iterrows()):
    q = s["quiet_median"]
    quiet = q["whisker_speed"] & q["jaw_movement"]
    if r["NaN in either"] > 0:
        quiet = np.zeros_like(quiet)
    rej += int((~quiet[s["completed"]]).sum())
    tot += int(s["completed"].sum())
print(f"Rejected of completed trials if one NaN made a session's threshold NaN (not the code): {100 * rej / tot:.2f}%")
functions/nwb_findQuietTrial.m:17:     baselinevalue=(nanmean((curr_signal(basewin(1):basewin(2),:)),1));
functions/nwb_findQuietTrial.m:18:     prewhiskvalue=(nanmean((curr_signal(prewin(1):prewin(2),:)),1));
functions/nwb_findQuietTrial.m:21:     TH=[nanmedian(baselinevalue),nanmedian(baselinevalue)+mad(baselinevalue),nanmedian(baselinevalue)+2*mad(baselinevalue)]
functions/nwb_findQuietTrial.m:22:     thereshold=TH(2)
functions/nwb_findQuietTrial.m:29:             ind_quiete=prewhiskvalue<=thereshold;
functions/PSTHBehavior.m:35:                 Mean_Signal(1:length(RelativeFrame),AnchorTimeIndex)=nan;
functions/PSTHBehavior.m:43:                 Mean_Signal(1:length(RelativeFrame),AnchorTimeIndex)=nan;
functions/PSTHBehavior.m:54:                 Mean_Signal(1:length(RelativeFrame),AnchorTimeIndex)=nan;
functions/PSTHBehavior.m:59:                 Mean_Signal(1:length(RelativeFrame),AnchorTimeIndex)=nan;
                      session  trials  NaN baseline whisker_speed  NaN pre-stimulus whisker_speed  NaN baseline jaw_movement  NaN pre-stimulus jaw_movement  NaN in either
sub-PG019_ses-20200904T224847     695                           5                               3                          5                              3              5
sub-PG019_ses-20200906T175456     623                          12                              11                         12                             11             12
sub-PG027_ses-20210403T115220     713                           1                               2                        187                            231            187
sub-PG027_ses-20210404T111739     586                           3                               3                          3                              4              5
sub-PG028_ses-20210318T163504     836                           6                               7                        190                            178            190
sub-PG028_ses-20210319T135422     862                           6                               7                          6                              7              6
sub-PG030_ses-20210405T163808     539                           1                               1                          1                              1              1
sub-PG030_ses-20210406T164509     386                           1                               3                          1                              2              1
sub-PG030_ses-20210407T211250     396                           1                               3                          1                              1              1
sub-PG030_ses-20210408T223046     208                           1                               1                          1                              1              1
sub-PG030_ses-20210410T012800     220                           1                               1                          1                              1              1
sub-PG032_ses-20210711T175822     424                           1                               2                          1                              1              1
sub-PG032_ses-20210712T185829     522                           1                               1                          1                              1              1
sub-PG032_ses-20210715T223447     530                           1                               1                          1                              1              1
sub-PG038_ses-20210316T152753     437                          29                              29                         28                             30             29
sub-PG038_ses-20210317T180556     329                           1                               1                          1                              1              1
sub-PG061_ses-20220211T222307     651                           3                               4                          2                              2              3
sub-PG061_ses-20220212T233813     676                         243                             249                        243                            243            243
sub-PG062_ses-20220206T200225     328                           1                               1                          1                              1              1
sub-PG062_ses-20220207T213136     386                           1                              24                          3                              4              3
sub-PG064_ses-20220209T222403     646                           5                               5                          1                              2              5
sub-PG064_ses-20220210T183214     311                           2                               7                          2                              2              2
sub-PG076_ses-20220502T140636     660                          25                              20                          9                              9             26
sub-PG082_ses-20221113T145317     687                           1                               1                          1                              1              1
sub-PG082_ses-20221114T163239     307                           1                               1                          1                              1              1
sub-PG082_ses-20221120T182616     629                           1                               1                          1                              1              1
sub-PG083_ses-20221125T180851     686                           1                               2                          1                              1              1
sub-PG083_ses-20221129T153120     476                           1                               1                          1                              1              1
sub-PG083_ses-20221130T230127     641                           1                               1                          1                              1              1
sub-PG084_ses-20221206T162236     530                           1                               1                         37                             48             37
sub-PG084_ses-20221207T192711     776                           1                               1                          1                              1              1
sub-PG084_ses-20221208T224009     649                           1                               1                          1                              1              1
sub-PG085_ses-20221213T195032     568                           2                               2                          2                              2              2
sub-PG085_ses-20221214T211712     586                           2                               2                          3                              4              3
sub-PG085_ses-20221215T222439     477                           1                               1                          1                              1              1
Sessions with any NaN baseline or pre-stimulus mean: 35 of 35
Rejected of completed trials if one NaN made a session's threshold NaN (not the code): 100.00%

Result: partially reproduced. With the Methods' rule (median absolute deviation) the quiet selection rejects 55.06% of the completed trials (pooled; median over sessions 53.3%) and 56.72% of all trials, just outside the 45 to 55% tolerance under both readings and inside the 30 to 70% band for a partial result. With the code's mean absolute deviation, 40.22% of completed trials are rejected. Leaving out the trials without video gives 54.22%. Counting those trials as not quiet is the code's rule: nwb_findQuietTrial.m takes nanmedian and mad() (which drops NaN) for the threshold and compares the NaN pre-stimulus mean with <=, which fails (lines printed above). Every session has at least one trial with a NaN baseline, so a threshold that kept NaN would reject every trial.

Optogenetic inactivation (Figure 2)¶

Per session, P(lick) over completed Go-tone Whisker trials with no light and with light in the session's window (code, Ghaderi2025_Figure2_d_Plick_Sessions.m). The reduction is the mean over sessions of no-light minus light P(lick), in points (reading a), or as percent of no-light P(lick) (reading b). The test draws 9 sessions with replacement (the smallest session count over areas and windows, computed below), p = (draws on the wrong side + 1) / iterations, two-tailed, Benjamini-Hochberg over the six areas within a window; 1,000 iterations (Methods) and 10,000 (code). The spread is given as SEM and SD over sessions.

In [13]:
def plick(o, window, ttype=1):
    tr = o["trials"]
    sel = ~tr["early_lick"].astype(bool) & (tr["trial_type"] == ttype) & (tr["opto_window"] == window)
    return 100 * tr["lick_flag"][sel].mean() if sel.any() else np.nan


WINDOWS = ["audio", "delay", "whisker"]


def opto_pairs(ttype=1):
    out = {}
    for a in g.OPTO_AREAS:
        sess = [o for o in O if o["area"] == a]
        nl = np.array([plick(o, "nolight", ttype) for o in sess])
        for w_ in WINDOWS:
            op = np.array([plick(o, w_, ttype) for o in sess])
            ok = np.isfinite(op) & np.isfinite(nl)
            out[a, w_] = (nl[ok], op[ok], [sess[i]["subject"] for i in np.flatnonzero(ok)])
    return out


pairs = opto_pairs()
n_draw = min(len(v[0]) for v in pairs.values())
print("Smallest number of sessions over areas and windows:", n_draw)
opto_rows = []
for iterations in (1000, 10000):
    rng = np.random.default_rng(2)
    for w_ in WINDOWS:
        ps = [g.paired_bootstrap_p(pairs[a, w_][0], pairs[a, w_][1], n_draw, iterations, rng) for a in g.OPTO_AREAS]
        qs = g.bh_fdr(ps)
        for a, p_, q_ in zip(g.OPTO_AREAS, ps, qs):
            nl, op, subj = pairs[a, w_]
            d = nl - op
            opto_rows.append({"iterations": iterations, "window": w_, "area": a, "sessions": len(d), "mice": len(set(subj)),
                              "reduction_pts": d.mean(), "SEM": d.std(ddof=1) / np.sqrt(len(d)), "SD": d.std(ddof=1),
                              "relative_%": 100 * np.mean(d / nl), "p": p_, "p_FDR": q_})
opto_tab = pd.DataFrame(opto_rows)
print(opto_tab.round(4).to_string(index=False))
Smallest number of sessions over areas and windows: 9
 iterations  window area  sessions  mice  reduction_pts    SEM      SD  relative_%      p  p_FDR
       1000   audio   A1        17     9        38.8746 4.0987 16.8994     53.3400 0.0020 0.0040
       1000   audio  wS1        16     9        19.4513 6.1003 24.4012     25.6708 0.0080 0.0120
       1000   audio  wS2        18    10        25.9976 3.8420 16.3004     36.1389 0.0020 0.0040
       1000   audio  wM2        14     9        33.0500 5.7294 21.4375     40.3944 0.0020 0.0040
       1000   audio  ALM         9     7         7.8005 5.4037 16.2111      9.0774 0.1200 0.1440
       1000   audio fpS1         9     8         0.1203 3.9303 11.7909     -1.4000 0.9940 0.9940
       1000   delay   A1        17     9         7.7857 3.7755 15.5670     10.5743 0.0940 0.1128
       1000   delay  wS1        16     9        15.9766 2.9984 11.9935     21.0163 0.0020 0.0040
       1000   delay  wS2        18    10         8.1830 3.5278 14.9674     12.4011 0.0600 0.0900
       1000   delay  wM2        14     9        44.5286 7.1680 26.8203     53.0931 0.0020 0.0040
       1000   delay  ALM         9     7        32.0926 5.4776 16.4328     39.6748 0.0020 0.0040
       1000   delay fpS1         9     8         4.3371 4.2762 12.8286      7.9833 0.2760 0.2760
       1000 whisker   A1        17     9        12.7586 3.4509 14.2284     18.7056 0.0060 0.0072
       1000 whisker  wS1        20    10        37.6407 3.4682 15.5103     50.0466 0.0020 0.0030
       1000 whisker  wS2        18    10        35.4873 3.7168 15.7689     47.4322 0.0020 0.0030
       1000 whisker  wM2        14     9        48.2476 3.8139 14.2703     59.2603 0.0020 0.0030
       1000 whisker  ALM         9     7        52.3420 3.8229 11.4687     65.0630 0.0020 0.0030
       1000 whisker fpS1         9     8         8.7005 5.5304 16.5913     13.3388 0.1180 0.1180
      10000   audio   A1        17     9        38.8746 4.0987 16.8994     53.3400 0.0002 0.0004
      10000   audio  wS1        16     9        19.4513 6.1003 24.4012     25.6708 0.0014 0.0021
      10000   audio  wS2        18    10        25.9976 3.8420 16.3004     36.1389 0.0002 0.0004
      10000   audio  wM2        14     9        33.0500 5.7294 21.4375     40.3944 0.0002 0.0004
      10000   audio  ALM         9     7         7.8005 5.4037 16.2111      9.0774 0.1342 0.1610
      10000   audio fpS1         9     8         0.1203 3.9303 11.7909     -1.4000 0.9786 0.9786
      10000   delay   A1        17     9         7.7857 3.7755 15.5670     10.5743 0.0938 0.1126
      10000   delay  wS1        16     9        15.9766 2.9984 11.9935     21.0163 0.0002 0.0004
      10000   delay  wS2        18    10         8.1830 3.5278 14.9674     12.4011 0.0506 0.0759
      10000   delay  wM2        14     9        44.5286 7.1680 26.8203     53.0931 0.0002 0.0004
      10000   delay  ALM         9     7        32.0926 5.4776 16.4328     39.6748 0.0002 0.0004
      10000   delay fpS1         9     8         4.3371 4.2762 12.8286      7.9833 0.2920 0.2920
      10000 whisker   A1        17     9        12.7586 3.4509 14.2284     18.7056 0.0096 0.0115
      10000 whisker  wS1        20    10        37.6407 3.4682 15.5103     50.0466 0.0002 0.0003
      10000 whisker  wS2        18    10        35.4873 3.7168 15.7689     47.4322 0.0002 0.0003
      10000 whisker  wM2        14     9        48.2476 3.8139 14.2703     59.2603 0.0002 0.0003
      10000 whisker  ALM         9     7        52.3420 3.8229 11.4687     65.0630 0.0002 0.0003
      10000 whisker fpS1         9     8         8.7005 5.5304 16.5913     13.3388 0.1178 0.1178
In [14]:
expected_opto = {("audio", "A1"): (39, 4), ("audio", "wM2"): (33, 6), ("audio", "wS2"): (26, 4), ("audio", "wS1"): (19, 6),
                 ("delay", "wM2"): (45, 7), ("delay", "ALM"): (32, 5), ("delay", "wS1"): (16, 3),
                 ("whisker", "ALM"): (52, 4), ("whisker", "wM2"): (48, 4), ("whisker", "wS1"): (38, 3),
                 ("whisker", "wS2"): (35, 4), ("whisker", "A1"): (13, 3)}
significant_expected = {"audio": {"A1", "wM2", "wS2", "wS1"}, "delay": {"wM2", "ALM", "wS1"},
                        "whisker": {"A1", "wS1", "wS2", "wM2", "ALM"}}
for iterations in (1000, 10000):
    for w_ in WINDOWS:
        sub = opto_tab[(opto_tab.iterations == iterations) & (opto_tab.window == w_)].set_index("area")
        sig_ = set(sub.index[sub.p_FDR < 0.05])
        checks = []
        for (ww, a), (v, tol) in expected_opto.items():
            if ww == w_:
                checks.append(f"{a} {sub.loc[a, 'reduction_pts']:.1f} pts / {sub.loc[a, 'relative_%']:.1f}% (paper {v} +/- {tol}; "
                              f"points within: {abs(sub.loc[a, 'reduction_pts'] - v) <= tol}; relative within: {abs(sub.loc[a, 'relative_%'] - v) <= tol})")
        print(f"{iterations} iterations, {w_}: significant {sorted(sig_)}; paper's pattern {sorted(significant_expected[w_])}; "
              f"same: {sig_ == significant_expected[w_]}")
        for c_ in checks:
            print("   ", c_)
print("\nPer mouse, mean reduction in points (Auditory, Delay, Whisker):")
rows = []
for a in g.OPTO_AREAS:
    for w_ in WINDOWS:
        nl, op, subj = pairs[a, w_]
        for m_ in sorted(set(subj)):
            k = np.array(subj) == m_
            rows.append({"area": a, "window": w_, "mouse": m_, "sessions": int(k.sum()), "reduction": round((nl[k] - op[k]).mean(), 1)})
print(pd.DataFrame(rows).pivot_table(index=["area", "mouse"], columns="window", values="reduction").round(1).to_string())
1000 iterations, audio: significant ['A1', 'wM2', 'wS1', 'wS2']; paper's pattern ['A1', 'wM2', 'wS1', 'wS2']; same: True
    A1 38.9 pts / 53.3% (paper 39 +/- 4; points within: True; relative within: False)
    wM2 33.0 pts / 40.4% (paper 33 +/- 6; points within: True; relative within: False)
    wS2 26.0 pts / 36.1% (paper 26 +/- 4; points within: True; relative within: False)
    wS1 19.5 pts / 25.7% (paper 19 +/- 6; points within: True; relative within: False)
1000 iterations, delay: significant ['ALM', 'wM2', 'wS1']; paper's pattern ['ALM', 'wM2', 'wS1']; same: True
    wM2 44.5 pts / 53.1% (paper 45 +/- 7; points within: True; relative within: False)
    ALM 32.1 pts / 39.7% (paper 32 +/- 5; points within: True; relative within: False)
    wS1 16.0 pts / 21.0% (paper 16 +/- 3; points within: True; relative within: False)
1000 iterations, whisker: significant ['A1', 'ALM', 'wM2', 'wS1', 'wS2']; paper's pattern ['A1', 'ALM', 'wM2', 'wS1', 'wS2']; same: True
    ALM 52.3 pts / 65.1% (paper 52 +/- 4; points within: True; relative within: False)
    wM2 48.2 pts / 59.3% (paper 48 +/- 4; points within: True; relative within: False)
    wS1 37.6 pts / 50.0% (paper 38 +/- 3; points within: True; relative within: False)
    wS2 35.5 pts / 47.4% (paper 35 +/- 4; points within: True; relative within: False)
    A1 12.8 pts / 18.7% (paper 13 +/- 3; points within: True; relative within: False)
10000 iterations, audio: significant ['A1', 'wM2', 'wS1', 'wS2']; paper's pattern ['A1', 'wM2', 'wS1', 'wS2']; same: True
    A1 38.9 pts / 53.3% (paper 39 +/- 4; points within: True; relative within: False)
    wM2 33.0 pts / 40.4% (paper 33 +/- 6; points within: True; relative within: False)
    wS2 26.0 pts / 36.1% (paper 26 +/- 4; points within: True; relative within: False)
    wS1 19.5 pts / 25.7% (paper 19 +/- 6; points within: True; relative within: False)
10000 iterations, delay: significant ['ALM', 'wM2', 'wS1']; paper's pattern ['ALM', 'wM2', 'wS1']; same: True
    wM2 44.5 pts / 53.1% (paper 45 +/- 7; points within: True; relative within: False)
    ALM 32.1 pts / 39.7% (paper 32 +/- 5; points within: True; relative within: False)
    wS1 16.0 pts / 21.0% (paper 16 +/- 3; points within: True; relative within: False)
10000 iterations, whisker: significant ['A1', 'ALM', 'wM2', 'wS1', 'wS2']; paper's pattern ['A1', 'ALM', 'wM2', 'wS1', 'wS2']; same: True
    ALM 52.3 pts / 65.1% (paper 52 +/- 4; points within: True; relative within: False)
    wM2 48.2 pts / 59.3% (paper 48 +/- 4; points within: True; relative within: False)
    wS1 37.6 pts / 50.0% (paper 38 +/- 3; points within: True; relative within: False)
    wS2 35.5 pts / 47.4% (paper 35 +/- 4; points within: True; relative within: False)
    A1 12.8 pts / 18.7% (paper 13 +/- 3; points within: True; relative within: False)

Per mouse, mean reduction in points (Auditory, Delay, Whisker):
window      audio  delay  whisker
area mouse                       
A1   PG021   32.7    3.2     24.6
     PG057   55.3   30.3     20.1
     PG061   50.7   11.9     21.9
     PG062   36.8   -7.6      4.7
     PG063   40.3    3.9     16.7
     PG064   26.7   -0.9     23.2
     PG067   40.7   13.0      7.4
     PG069   36.5   -4.0      5.1
     PG070   28.1   13.6     -1.2
ALM  PG057  -18.5    3.7     59.3
     PG059    5.0   55.0     75.0
     PG061    2.3   54.3     54.3
     PG062   17.9   37.5     41.7
     PG064   22.5   24.3     43.1
     PG067   -5.0   33.7     57.3
     PG069   28.4   22.5     40.2
fpS1 PG057  -16.2  -16.2     22.7
     PG059  -14.9   13.7     17.2
     PG061    2.8  -13.9      2.8
     PG062    5.4   11.7     25.4
     PG064   15.5   -6.0      8.3
     PG067   -6.5    6.8     20.1
     PG069   17.4   11.8     17.4
     PG070   -1.2   15.5    -17.8
wM2  PG057   53.3   13.3     53.3
     PG059   30.8   80.8     80.8
     PG061   19.0   25.9     31.5
     PG062   40.6   80.1     61.4
     PG063   47.8   25.1     39.7
     PG064   29.0   21.2     45.1
     PG067   -0.2   53.5     43.1
     PG069   65.6   65.6     58.9
     PG070   40.8   51.9     40.8
wS1  PG021    NaN    NaN     21.7
     PG057   70.9   31.6     27.6
     PG059   23.8   13.8     34.9
     PG061   12.0   12.0     49.9
     PG062   40.0    0.0     30.0
     PG063   13.6   26.9     53.6
     PG064   13.5   13.5     55.7
     PG067    0.4   17.8     42.8
     PG069    7.3   11.1     33.2
     PG070    8.6   14.4     34.8
wS2  PG021   54.3    6.5     59.6
     PG057   39.6   27.4     18.6
     PG059   22.9   18.0     43.8
     PG061   31.4    4.1     26.7
     PG062   15.0   -5.0     25.0
     PG063   36.6    6.5     47.1
     PG064   15.2   10.8     38.8
     PG067   31.7   -3.3     31.7
     PG069   28.9   -3.9     40.4
     PG070    4.2   -3.0     25.6
In [15]:
fig, axs = plt.subplots(1, 6, figsize=(14, 3), sharey=True)
for ax, a in zip(axs, g.OPTO_AREAS):
    sess = [o for o in O if o["area"] == a]
    for o in sess:
        y = [plick(o, w_) for w_ in ["nolight"] + WINDOWS]
        ax.plot(range(4), y, "-o", color="0.7", ms=2, lw=0.5)
    ax.set_xticks(range(4), ["none", "aud", "delay", "whisk"], fontsize=7)
    ax.set_title(a)
axs[0].set_ylabel("P(lick), Go-tone Whisker (%)")
plt.show()
print("All plotted P(lick) values lie in 0 to 100%.")
No description has been provided for this image
All plotted P(lick) values lie in 0 to 100%.

Result: reproduced (fig2-auditory-window). In the Auditory window the reductions are A1 38.9 (SEM 4.1), wM2 33.0 (5.7), wS2 26.0 (3.8) and wS1 19.5 (6.1) points, all within tolerance in points; these four areas are significant after FDR (10,000 iterations: 0.0004, 0.0004, 0.0004 and 0.0021; 1,000: 0.004 to 0.012) and ALM (7.8 points, p 0.161) and fpS1 (0.1, p 0.979) are not. The paper's spread matches the SEM, not the SD. As a percent of no-light P(lick) (reading b) the values are larger and out of tolerance, so the paper's numbers are points.

Result: reproduced (fig2-delay-window). In the Delay window wM2 44.5 (SEM 7.2), ALM 32.1 (5.5) and wS1 16.0 (3.0) points, within tolerance and significant (p_FDR 0.0004 with 10,000 iterations); A1 (7.8, p 0.113), wS2 (8.2, p 0.076) and fpS1 (4.3, p 0.292) are not significant.

Result: reproduced (fig2-whisker-window). In the Whisker window ALM 52.3 (SEM 3.8), wM2 48.2 (3.8), wS1 37.6 (3.5), wS2 35.5 (3.7) and A1 12.8 (3.5) points, within tolerance and significant (p_FDR 0.0003 for the first four and 0.0115 for A1 with 10,000 iterations, the paper's 0.0003 and 0.01); fpS1 (8.7, p 0.118) is not. With 1,000 iterations the pattern is the same.

fig2-wm2-vs-alm-auditory¶

Inactivation during the auditory window reduces licking significantly more for wM2 than for ALM (33 +/- 6% against 8 +/- 5%).

Unpaired bootstrap of the difference of the two areas' mean per-session reductions, readings (a) 9 sessions per area and (b) all sessions of each area, two-tailed with the code's p rule; FDR over the 15 area pairs of the Auditory window as a variant.

In [16]:
def unpaired_bootstrap_p(x, y, n_x, n_y, iterations, rng):
    d = rng.choice(x, (iterations, n_x)).mean(axis=1) - rng.choice(y, (iterations, n_y)).mean(axis=1)
    obs = x.mean() - y.mean()
    p_ = ((d <= 0).sum() + 1) / iterations if obs > 0 else ((d >= 0).sum() + 1) / iterations
    return 2 * min(p_, 1 - p_)


red = {a: pairs[a, "audio"][0] - pairs[a, "audio"][1] for a in g.OPTO_AREAS}
print(f"wM2 {red['wM2'].mean():.1f} +/- {red['wM2'].std(ddof=1) / np.sqrt(len(red['wM2'])):.1f} (n {len(red['wM2'])}); "
      f"ALM {red['ALM'].mean():.1f} +/- {red['ALM'].std(ddof=1) / np.sqrt(len(red['ALM'])):.1f} (n {len(red['ALM'])})")
for iterations in (1000, 10000):
    rng = np.random.default_rng(3)
    pa = unpaired_bootstrap_p(red["wM2"], red["ALM"], 9, 9, iterations, rng)
    pb = unpaired_bootstrap_p(red["wM2"], red["ALM"], len(red["wM2"]), len(red["ALM"]), iterations, rng)
    pairs15 = [(a, b) for i, a in enumerate(g.OPTO_AREAS) for b in g.OPTO_AREAS[i + 1:]]
    pall = [unpaired_bootstrap_p(red[a], red[b], len(red[a]), len(red[b]), iterations, rng) for a, b in pairs15]
    q15 = g.bh_fdr(pall)[pairs15.index(("wM2", "ALM"))]
    print(f"{iterations} iterations: reading (a) p = {pa:.4f}; reading (b) p = {pb:.4f}; "
          f"(b) with FDR over the 15 pairs: {q15:.4f}")
wM2 33.0 +/- 5.7 (n 14); ALM 7.8 +/- 5.4 (n 9)
1000 iterations: reading (a) p = 0.0060; reading (b) p = 0.0020; (b) with FDR over the 15 pairs: 0.0050
10000 iterations: reading (a) p = 0.0024; reading (b) p = 0.0008; (b) with FDR over the 15 pairs: 0.0018

Result: reproduced. wM2 33.0 +/- 5.7 and ALM 7.8 +/- 5.4 points, both within tolerance, and the bootstrap gives p < 0.05 with wM2 larger under both readings (10,000 iterations: 0.0024 and 0.0008 uncorrected, 0.0018 after FDR over the 15 pairs; 1,000 iterations: 0.006, 0.002 and 0.005).

fig2-other-trial-types¶

Inactivation has little impact on licking in the trial types other than Go-tone Whisker.

The change in P(lick) for trial types 2 to 5, 6 areas and 3 windows (72 changes); reading (a) the bootstrap test of fig2 with FDR within each window and trial type finds no significant change in more than 7 of 72; reading (b) no change exceeds 13 points.

In [17]:
rows = []
rng = np.random.default_rng(4)
for ttype in (2, 3, 4, 5):
    pr = opto_pairs(ttype)
    for w_ in WINDOWS:
        ps = []
        for a in g.OPTO_AREAS:
            nl, op, _ = pr[a, w_]
            ps.append(g.paired_bootstrap_p(nl, op, n_draw, 1000, rng) if len(nl) > 1 else np.nan)
        qs = g.bh_fdr(np.nan_to_num(ps, nan=1.0))
        for a, p_, q_ in zip(g.OPTO_AREAS, ps, qs):
            nl, op, _ = pr[a, w_]
            rows.append({"trial type": g.TRIAL_NAMES[ttype], "window": w_, "area": a, "sessions": len(nl),
                         "change_pts": (op - nl).mean(), "p": p_, "p_FDR": q_})
other = pd.DataFrame(rows)
print(other.round(4).to_string(index=False))
n_sig = int((other.p_FDR < 0.05).sum())
print(f"\nReading (a): {n_sig} of {len(other)} changes significant after FDR (threshold: at most 7)")
print(f"Reading (b): largest absolute change {other.change_pts.abs().max():.1f} points (threshold 13); "
      f"changes above 13 points: {int((other.change_pts.abs() > 13).sum())}")
print(other.loc[other.change_pts.abs() > 13, ["trial type", "window", "area", "change_pts", "p_FDR"]].round(3).to_string(index=False))
          trial type  window area  sessions  change_pts     p  p_FDR
  Go-tone No-Whisker   audio   A1        17    -19.0108 0.002 0.0040
  Go-tone No-Whisker   audio  wS1        15     -2.1295 0.680 0.6800
  Go-tone No-Whisker   audio  wS2        18    -15.6853 0.002 0.0040
  Go-tone No-Whisker   audio  wM2        14    -10.0468 0.006 0.0090
  Go-tone No-Whisker   audio  ALM         9    -11.4714 0.002 0.0040
  Go-tone No-Whisker   audio fpS1         9     -8.1988 0.016 0.0192
  Go-tone No-Whisker   delay   A1        17      1.3075 0.716 0.8592
  Go-tone No-Whisker   delay  wS1        16      6.3140 0.138 0.5640
  Go-tone No-Whisker   delay  wS2        18      0.4541 0.936 0.9360
  Go-tone No-Whisker   delay  wM2        14     -8.1526 0.188 0.5640
  Go-tone No-Whisker   delay  ALM         9     -6.4267 0.360 0.6870
  Go-tone No-Whisker   delay fpS1         9     -2.0127 0.458 0.6870
  Go-tone No-Whisker whisker   A1        17      1.0652 0.844 0.9840
  Go-tone No-Whisker whisker  wS1        20      0.8251 0.876 0.9840
  Go-tone No-Whisker whisker  wS2        18     -7.6047 0.066 0.3960
  Go-tone No-Whisker whisker  wM2        14     -5.7442 0.254 0.5080
  Go-tone No-Whisker whisker  ALM         9     -0.3396 0.984 0.9840
  Go-tone No-Whisker whisker fpS1         9      3.6006 0.178 0.5080
   Nogo-tone Whisker   audio   A1        17      3.9467 0.266 0.3990
   Nogo-tone Whisker   audio  wS1        16      2.0459 0.640 0.6400
   Nogo-tone Whisker   audio  wS2        18      3.2962 0.348 0.4176
   Nogo-tone Whisker   audio  wM2        14      4.4508 0.216 0.3990
   Nogo-tone Whisker   audio  ALM         9      6.6415 0.010 0.0600
   Nogo-tone Whisker   audio fpS1         9      8.1986 0.056 0.1680
   Nogo-tone Whisker   delay   A1        17     -0.1276 0.970 0.9700
   Nogo-tone Whisker   delay  wS1        16      1.6575 0.566 0.8490
   Nogo-tone Whisker   delay  wS2        18      0.8132 0.758 0.9096
   Nogo-tone Whisker   delay  wM2        14     -3.1670 0.228 0.5880
   Nogo-tone Whisker   delay  ALM         9     -4.6910 0.294 0.5880
   Nogo-tone Whisker   delay fpS1         9      8.5610 0.002 0.0120
   Nogo-tone Whisker whisker   A1        17     -5.1160 0.004 0.0120
   Nogo-tone Whisker whisker  wS1        19     -4.4376 0.022 0.0330
   Nogo-tone Whisker whisker  wS2        18     -7.1548 0.002 0.0120
   Nogo-tone Whisker whisker  wM2        14     -3.6095 0.122 0.1220
   Nogo-tone Whisker whisker  ALM         9    -10.3157 0.018 0.0330
   Nogo-tone Whisker whisker fpS1         9     -5.1171 0.064 0.0768
Nogo-tone No-Whisker   audio   A1        17     -0.5290 0.346 0.8900
Nogo-tone No-Whisker   audio  wS1        16      0.3354 0.782 0.8900
Nogo-tone No-Whisker   audio  wS2        18     -0.3326 0.756 0.8900
Nogo-tone No-Whisker   audio  wM2        14      0.3685 0.890 0.8900
Nogo-tone No-Whisker   audio  ALM         9     -0.1084 0.872 0.8900
Nogo-tone No-Whisker   audio fpS1         9      2.1871 0.318 0.8900
Nogo-tone No-Whisker   delay   A1        17      0.1874 0.924 0.9240
Nogo-tone No-Whisker   delay  wS1        16     -1.5235 0.002 0.0120
Nogo-tone No-Whisker   delay  wS2        18     -1.2769 0.006 0.0180
Nogo-tone No-Whisker   delay  wM2        14      0.0927 0.804 0.9240
Nogo-tone No-Whisker   delay  ALM         9     -1.1870 0.306 0.6120
Nogo-tone No-Whisker   delay fpS1         9     -0.3592 0.690 0.9240
Nogo-tone No-Whisker whisker   A1        17      0.0232 0.906 0.9060
Nogo-tone No-Whisker whisker  wS1        20     -0.9338 0.318 0.4770
Nogo-tone No-Whisker whisker  wS2        18     -0.7244 0.412 0.4944
Nogo-tone No-Whisker whisker  wM2        14     -0.7010 0.214 0.4280
Nogo-tone No-Whisker whisker  ALM         9     -1.0730 0.214 0.4280
Nogo-tone No-Whisker whisker fpS1         9     -1.0536 0.016 0.0960
     No-tone Whisker   audio   A1        17     -1.1580 0.852 0.8520
     No-tone Whisker   audio  wS1        16      2.5277 0.506 0.7980
     No-tone Whisker   audio  wS2        18     -1.0588 0.702 0.8424
     No-tone Whisker   audio  wM2        14      2.4691 0.532 0.7980
     No-tone Whisker   audio  ALM         9      8.0375 0.096 0.5760
     No-tone Whisker   audio fpS1         9      5.4436 0.210 0.6300
     No-tone Whisker   delay   A1        17     -4.4979 0.274 0.8940
     No-tone Whisker   delay  wS1        16     -1.7566 0.576 0.9980
     No-tone Whisker   delay  wS2        18     -2.8907 0.298 0.8940
     No-tone Whisker   delay  wM2        14      0.7080 0.946 0.9980
     No-tone Whisker   delay  ALM         9      0.3795 0.998 0.9980
     No-tone Whisker   delay fpS1         9     -0.3152 0.906 0.9980
     No-tone Whisker whisker   A1        17     -8.6381 0.008 0.0120
     No-tone Whisker whisker  wS1        20     -5.7968 0.030 0.0300
     No-tone Whisker whisker  wS2        18    -10.9173 0.002 0.0040
     No-tone Whisker whisker  wM2        14     -9.2267 0.002 0.0040
     No-tone Whisker whisker  ALM         9    -12.6004 0.002 0.0040
     No-tone Whisker whisker fpS1         9     -5.7297 0.020 0.0240

Reading (a): 18 of 72 changes significant after FDR (threshold: at most 7)
Reading (b): largest absolute change 19.0 points (threshold 13); changes above 13 points: 2
        trial type window area  change_pts  p_FDR
Go-tone No-Whisker  audio   A1     -19.011  0.004
Go-tone No-Whisker  audio  wS2     -15.685  0.004

Result: not reproduced. Both readings fail. By the bootstrap test 18 of the 72 changes are significant after FDR (reading a allows at most 7), and two changes exceed 13 points (reading b), both Go-tone No-Whisker trials in the Auditory window: A1 -19.0 and wS2 -15.7 points. Most significant changes are reductions of licking in No-tone Whisker and Nogo-tone Whisker trials (table above), smaller than on Go-tone Whisker trials but not absent.

units-recorded¶

Across 35 sessions in 14 mice, 10,294 well-isolated units were recorded in the five areas (A1 780, wS1 1938, wS2 2064, wM2 2749, ALM 2763).

The files hold only the units kept after curation (no inclusion column); a unit is in an area when its probe location is the area and its ccf_location is one of the area's labels in Area_list.mat.

In [18]:
rows = []
for a in g.AREAS:
    ccf = sum(int((s["units"]["area"] == a).sum()) for s in S)
    probe = sum(int((s["units"]["location"] == a).sum()) for s in S)
    sess_probe = [s for s in S if (s["units"]["location"] == a).any()]
    sess_ccf = [s for s in S if (s["units"]["area"] == a).any()]
    rows.append({"area": a, "units (probe and CCF)": ccf, "units (probe only)": probe,
                 "sessions (probe)": len(sess_probe), "mice (probe)": len({s["subject"] for s in sess_probe}),
                 "sessions (with CCF units)": len(sess_ccf), "mice (with CCF units)": len({s["subject"] for s in sess_ccf})})
units = pd.DataFrame(rows)
units["paper units"] = [780, 1938, 2064, 2749, 2763]
units["paper sessions, mice"] = ["14, 6", "24, 12", "24, 11", "18, 8", "16, 6"]
print(units.to_string(index=False))
print("Total (probe and CCF):", units["units (probe and CCF)"].sum(), "; paper 10,294")
print("Units on other probes:", {L: sum(int((s["units"]["location"] == L).sum()) for s in S) for L in ("tjM1", "unassigned_area")})
print("Cell types of the 10,294 (RS, FS, neither):",
      [sum(int(s["units"][k][s["keep"]].sum()) for s in S) for k in ("rsUnits", "fsUnits")],
      sum(int((~s["units"]["rsUnits"][s["keep"]] & ~s["units"]["fsUnits"][s["keep"]]).sum()) for s in S))
sw = 1000 * np.concatenate([s["units"]["spike_width"][s["keep"]] for s in S])   # the values are in seconds
rs = np.concatenate([s["units"]["rsUnits"][s["keep"]] for s in S])
fs = np.concatenate([s["units"]["fsUnits"][s["keep"]] for s in S])
print(f"Spike width x 1000 (ms): RS {sw[rs].min():.3f} to {sw[rs].max():.3f}; FS {sw[fs].min():.3f} to {sw[fs].max():.3f}; "
      f"neither {sw[~rs & ~fs].min():.3f} to {sw[~rs & ~fs].max():.3f} (Methods: RS > 0.46, FS < 0.36)")
area  units (probe and CCF)  units (probe only)  sessions (probe)  mice (probe)  sessions (with CCF units)  mice (with CCF units)  paper units paper sessions, mice
  A1                    780                1256                14             6                         14                      6          780                14, 6
 wS1                   1938                2175                24            12                         24                     12         1938               24, 12
 wS2                   2064                2849                24            11                         19                      9         2064               24, 11
 wM2                   2749                2758                18             8                         18                      8         2749                18, 8
 ALM                   2763                3028                16             6                         16                      6         2763                16, 6
Total (probe and CCF): 10294 ; paper 10,294
Units on other probes: {'tjM1': 893, 'unassigned_area': 834}
Cell types of the 10,294 (RS, FS, neither): [8691, 1311] 292
Spike width x 1000 (ms): RS 0.467 to 1.200; FS 0.100 to 0.333; neither 0.367 to 0.433 (Methods: RS > 0.46, FS < 0.36)

Result: reproduced. The unit counts are exactly the paper's: A1 780, wS1 1938, wS2 2064, wM2 2749 and ALM 2763, 10,294 in all; they match only with the CCF filter (without it, 12,066 units sit on the five areas' probes). The probe session and mouse counts are the paper's (A1 14 and 6, wS1 24 and 12, wS2 24 and 11, wM2 18 and 8, ALM 16 and 6); for wS2 only 19 sessions in 9 mice keep units after the CCF filter.

fig3a-activity-maps¶

In quiet Hit trials, probe-averaged activity changes are largest in A1 in the first 30 ms after the tone, in wM2 and ALM in the last 200 ms of the delay, in wS1 and wS2 in the first 30 ms after the whisker deflection, and in frontal areas 300 to 500 ms after it.

Per area-session (one probe each), the mean over neurons of the trial-averaged change in rate over quiet Hit trials in the windows of the code (Ghaderi2025_Figure3_a_brainmap_activity.m, bins labelled 0.01-0.03, 0.8-1.0, 1.01-1.03 and 1.3-1.5 s); per area, the mean over probes. Pre-whisker baseline readings (a) 0.95 to 1.0 s and (b) 0.8 to 1.0 s; the code's -1 to 0 s baseline for every window is a variant.

In [19]:
WIN3A = {"Auditory": (0.01, 0.03), "Delay": (0.8, 1.0), "Whisker": (1.01, 1.03), "Lick": (1.3, 1.5)}
TOP = {"Auditory": {"A1"}, "Delay": {"wM2", "ALM"}, "Whisker": {"wS1", "wS2"}, "Lick": {"wM2", "ALM"}}


def activity_maps(reading):
    rows = []
    for a in g.AREAS:
        for s, cols in g.area_sessions(S, a):
            sel = g.trial_mask(s, 1, True) & g.quiet_mask(s)
            if sel.sum() == 0:
                continue
            m = s["c10"][sel][:, :, cols].mean(axis=0) / g.W10
            row = {"area": a, "session": s["session"], "neurons": len(cols), "trials": int(sel.sum())}
            for k, (t1, t2) in WIN3A.items():
                if k in ("Auditory", "Delay") or reading == "code":
                    b = g.bin_index(-1.0, 0.0)
                else:
                    b = g.bin_index(0.95, 1.0) if reading == "a" else g.bin_index(0.8, 1.0)
                row[k] = (m[g.bin_index(t1, t2)].mean(axis=0) - m[b].mean(axis=0)).mean()
            rows.append(row)
    return pd.DataFrame(rows)


for reading in ("a", "b", "code"):
    df = activity_maps(reading)
    means = df.groupby("area")[list(WIN3A)].mean().loc[g.AREAS]
    print(f"Reading {reading}: mean over probes (Hz)")
    print(means.round(2).to_string())
    held = []
    for k, top in TOP.items():
        order = means[k].sort_values(ascending=False).index.tolist()
        ok = set(order[:len(top)]) == top
        held.append(ok)
        print(f"  {k}: largest {order[:len(top)]}, expected {sorted(top)} -> {ok}")
    print(f"  {sum(held)} of 4 hold\n")
print("Per probe, reading (a):")
print(activity_maps("a").round(2).to_string(index=False))
Reading a: mean over probes (Hz)
      Auditory  Delay  Whisker  Lick
area                                
A1        5.55   0.20     1.26  0.28
wS1       1.34   0.02     6.80  1.03
wS2       1.54  -0.06     5.61  1.28
wM2       1.11   0.70     1.48  1.79
ALM       0.81   0.35     0.74  1.80
  Auditory: largest ['A1'], expected ['A1'] -> True
  Delay: largest ['wM2', 'ALM'], expected ['ALM', 'wM2'] -> True
  Whisker: largest ['wS1', 'wS2'], expected ['wS1', 'wS2'] -> True
  Lick: largest ['ALM', 'wM2'], expected ['ALM', 'wM2'] -> True
  4 of 4 hold

Reading b: mean over probes (Hz)
      Auditory  Delay  Whisker  Lick
area                                
A1        5.55   0.20     1.20  0.22
wS1       1.34   0.02     6.93  1.17
wS2       1.54  -0.06     5.64  1.30
wM2       1.11   0.70     1.57  1.88
ALM       0.81   0.35     0.83  1.89
  Auditory: largest ['A1'], expected ['A1'] -> True
  Delay: largest ['wM2', 'ALM'], expected ['ALM', 'wM2'] -> True
  Whisker: largest ['wS1', 'wS2'], expected ['wS1', 'wS2'] -> True
  Lick: largest ['ALM', 'wM2'], expected ['ALM', 'wM2'] -> True
  4 of 4 hold

Reading code: mean over probes (Hz)
      Auditory  Delay  Whisker  Lick
area                                
A1        5.55   0.20     1.40  0.42
wS1       1.34   0.02     6.96  1.19
wS2       1.54  -0.06     5.58  1.24
wM2       1.11   0.70     2.27  2.58
ALM       0.81   0.35     1.19  2.25
  Auditory: largest ['A1'], expected ['A1'] -> True
  Delay: largest ['wM2', 'ALM'], expected ['ALM', 'wM2'] -> True
  Whisker: largest ['wS1', 'wS2'], expected ['wS1', 'wS2'] -> True
  Lick: largest ['wM2', 'ALM'], expected ['ALM', 'wM2'] -> True
  4 of 4 hold

Per probe, reading (a):
area                       session  neurons  trials  Auditory  Delay  Whisker  Lick
  A1 sub-PG061_ses-20220212T233813       75      14      1.82   0.52     0.71  1.67
  A1 sub-PG062_ses-20220207T213136       74      13      5.86   0.02     0.52  0.01
  A1 sub-PG082_ses-20221113T145317       86      43      3.63   0.25     0.96 -0.51
  A1 sub-PG082_ses-20221114T163239       33      20      0.29   0.07    -0.03  0.34
  A1 sub-PG082_ses-20221120T182616       16      42      5.92   0.07     2.18  0.52
  A1 sub-PG083_ses-20221125T180851        8      44     21.92  -0.90     1.14  2.83
  A1 sub-PG083_ses-20221129T153120       59      26      6.55  -0.41     1.35 -0.49
  A1 sub-PG083_ses-20221130T230127       40      42      3.78  -0.26     1.71  1.29
  A1 sub-PG084_ses-20221206T162236       32      26      3.58   0.03     1.76 -0.33
  A1 sub-PG084_ses-20221207T192711       34      49      5.30   0.93     0.86 -0.56
  A1 sub-PG084_ses-20221208T224009       99      44      1.96   0.03     1.16  0.03
  A1 sub-PG085_ses-20221213T195032       65      41      5.94   1.56     2.20 -0.79
  A1 sub-PG085_ses-20221214T211712       50      55      6.76   0.32     0.97  0.17
  A1 sub-PG085_ses-20221215T222439      109      30      4.44   0.55     2.08 -0.28
 wS1 sub-PG019_ses-20200906T175456      154      22      1.10   0.26     3.11  0.18
 wS1 sub-PG027_ses-20210403T115220       42      11      4.14   0.24     9.60  0.62
 wS1 sub-PG027_ses-20210404T111739       79      19      3.71  -0.29     9.53  1.75
 wS1 sub-PG028_ses-20210318T163504       37      34      1.22  -0.02     6.96  0.95
 wS1 sub-PG028_ses-20210319T135422       45      48      1.95   0.18     8.80  2.05
 wS1 sub-PG030_ses-20210405T163808       88      33      0.46  -0.13     5.29  0.89
 wS1 sub-PG030_ses-20210406T164509       68       9      2.47   0.50     7.14  0.74
 wS1 sub-PG032_ses-20210711T175822      124      31     -0.33   0.09     6.72  0.12
 wS1 sub-PG032_ses-20210712T185829      128      32     -0.33  -0.02     0.31  1.14
 wS1 sub-PG038_ses-20210316T152753      119      15     -0.38  -0.15     7.51  1.66
 wS1 sub-PG061_ses-20220211T222307       30      40     -0.07  -0.24    13.99  1.76
 wS1 sub-PG062_ses-20220207T213136       48      13     -0.77  -0.37     9.72  0.39
 wS1 sub-PG082_ses-20221113T145317      170      43      0.66  -0.26     4.63  0.32
 wS1 sub-PG082_ses-20221114T163239       88      20      1.12  -0.05     7.29  1.49
 wS1 sub-PG082_ses-20221120T182616      165      42      0.11  -0.04     5.52  0.79
 wS1 sub-PG083_ses-20221125T180851       55      44      3.11  -0.65     4.22  1.75
 wS1 sub-PG083_ses-20221129T153120       63      26      2.33   0.67     5.47  1.27
 wS1 sub-PG083_ses-20221130T230127       48      42      0.09   0.89     3.66  1.05
 wS1 sub-PG084_ses-20221206T162236       17      26      1.04  -0.09     8.52  0.66
 wS1 sub-PG084_ses-20221207T192711       54      49      1.70  -0.35     8.52  1.56
 wS1 sub-PG084_ses-20221208T224009       71      44      1.24  -0.17     8.01  1.39
 wS1 sub-PG085_ses-20221213T195032       55      41      2.75   0.80     6.63  0.73
 wS1 sub-PG085_ses-20221214T211712      126      55      2.13   0.02     5.54  0.44
 wS1 sub-PG085_ses-20221215T222439       64      30      2.80  -0.26     6.42  1.07
 wS2 sub-PG019_ses-20200904T224847       73      32      2.67  -0.61     6.62  2.48
 wS2 sub-PG028_ses-20210318T163504       89      34      2.57  -0.15     3.08  2.10
 wS2 sub-PG028_ses-20210319T135422      102      48      4.15  -0.14     2.31  1.36
 wS2 sub-PG030_ses-20210405T163808      138      33      0.91   0.02     7.17  1.43
 wS2 sub-PG030_ses-20210406T164509      140       9      2.75   0.04     6.39  1.11
 wS2 sub-PG032_ses-20210711T175822      108      31     -0.20   0.18     8.30  1.64
 wS2 sub-PG032_ses-20210712T185829       52      32     -0.32  -0.26     0.35  2.79
 wS2 sub-PG061_ses-20220211T222307      128      40      0.13   0.37     4.12  2.26
 wS2 sub-PG061_ses-20220212T233813      131      14      0.17   0.09     4.21  2.02
 wS2 sub-PG062_ses-20220206T200225       61      34      0.55  -0.14     7.11  1.30
 wS2 sub-PG083_ses-20221125T180851       99      44      2.27  -0.64     9.91  1.85
 wS2 sub-PG083_ses-20221129T153120      131      26      1.83  -0.19     5.63  0.68
 wS2 sub-PG083_ses-20221130T230127       85      42      1.09   0.20     4.95 -0.78
 wS2 sub-PG084_ses-20221206T162236      120      26      1.36   0.05     6.40  1.21
 wS2 sub-PG084_ses-20221207T192711       74      49      2.16   0.30     7.60  1.42
 wS2 sub-PG084_ses-20221208T224009       87      44      1.35  -0.14     4.39  1.19
 wS2 sub-PG085_ses-20221213T195032      211      41      2.59  -0.01     6.56  0.28
 wS2 sub-PG085_ses-20221214T211712       55      55      1.56  -0.11     6.40 -0.25
 wS2 sub-PG085_ses-20221215T222439      180      30      1.67  -0.01     5.09  0.20
 wM2 sub-PG030_ses-20210408T223046      133       7      3.54   0.55     2.77  2.66
 wM2 sub-PG032_ses-20210715T223447      152      30      0.14   0.76     1.92  1.49
 wM2 sub-PG061_ses-20220211T222307      164      40     -0.02   0.12     1.76  1.76
 wM2 sub-PG061_ses-20220212T233813      125      14     -0.01   0.00     2.58  3.86
 wM2 sub-PG062_ses-20220206T200225      211      34      0.07   0.71     0.73  0.45
 wM2 sub-PG062_ses-20220207T213136       89      13     -0.03   0.19     2.13  3.77
 wM2 sub-PG082_ses-20221113T145317      216      43      0.09   0.80     0.91  1.14
 wM2 sub-PG082_ses-20221114T163239      141      20      0.81   1.16     0.86  1.59
 wM2 sub-PG082_ses-20221120T182616      167      42      0.08   0.28     0.44  1.30
 wM2 sub-PG083_ses-20221125T180851      139      44      1.16   0.65     1.25  3.08
 wM2 sub-PG083_ses-20221129T153120      270      26      0.58   1.01     0.90  0.87
 wM2 sub-PG083_ses-20221130T230127      199      42      0.57   1.29     0.45  1.41
 wM2 sub-PG084_ses-20221206T162236       91      26      1.90   1.69     1.50  1.53
 wM2 sub-PG084_ses-20221207T192711       83      49      3.02   1.10     1.66  1.59
 wM2 sub-PG084_ses-20221208T224009      119      44      0.94   0.73     1.26  1.70
 wM2 sub-PG085_ses-20221213T195032      194      41      1.67   0.15     1.89  1.22
 wM2 sub-PG085_ses-20221214T211712      115      55      3.62   0.84     1.78  1.48
 wM2 sub-PG085_ses-20221215T222439      141      30      1.81   0.55     1.82  1.24
 ALM sub-PG030_ses-20210407T211250      117      11      1.26   0.34     0.28  3.83
 ALM sub-PG030_ses-20210408T223046      101       7      2.47   1.00     0.54  2.85
 ALM sub-PG030_ses-20210410T012800      104      15      0.92  -0.03     1.34  4.98
 ALM sub-PG032_ses-20210715T223447      183      30      0.24   0.50     0.89  2.62
 ALM sub-PG082_ses-20221113T145317      116      43     -0.65   0.63    -0.15  0.98
 ALM sub-PG082_ses-20221114T163239      168      20     -0.05   1.33     0.63  0.01
 ALM sub-PG082_ses-20221120T182616      248      42      0.06   0.38     0.77  0.41
 ALM sub-PG083_ses-20221125T180851      119      44      1.59  -0.46     1.15  1.20
 ALM sub-PG083_ses-20221129T153120      138      26      2.70   0.10     1.38  0.68
 ALM sub-PG083_ses-20221130T230127      135      42      1.22   0.51     0.47  0.47
 ALM sub-PG084_ses-20221206T162236      210      26      0.57  -0.01     1.04  1.74
 ALM sub-PG084_ses-20221207T192711      162      49      0.71   0.50     0.78  1.27
 ALM sub-PG084_ses-20221208T224009      245      44      0.18   0.13     0.60  1.33
 ALM sub-PG085_ses-20221213T195032      262      41      0.40   0.06     0.56  2.12
 ALM sub-PG085_ses-20221214T211712      231      55      0.44   0.76     0.75  2.53
 ALM sub-PG085_ses-20221215T222439      224      30      0.84  -0.08     0.88  1.84

Result: reproduced. Under both pre-whisker readings, A1 has the largest change in the Auditory window (5.55 Hz against at most 1.54), wM2 and ALM the two largest in the Delay window (0.70 and 0.35 Hz; A1 0.20), wS1 and wS2 the two largest in the Whisker window (6.80 and 5.61 Hz under (a)) and wM2 and ALM the two largest in the Lick window (1.79 and 1.80 Hz under (a); wS2 1.28). The code's -1 to 0 s baseline gives the same ranking.

fig3b-delay-and-response-psth¶

In grand-average PSTHs of correct quiet trials, firing in wM2 and ALM is elevated during the delay of Go-tone trials compared with Nogo-tone trials, and after the whisker stimulus activity rises in Go-tone Whisker Hit trials compared with all other trial types in wS1, wS2, wM2 and ALM.

Per neuron, baseline-subtracted means over quiet correct trials; Wilcoxon signed-rank over neurons. Pooled Go-tone trials are the Hit and Go-tone No-Whisker correct trials together, and likewise for Nogo-tone. Neurons of sessions lacking either condition are left out (counts printed).

In [20]:
hit = lambda s: g.correct_mask(s, 1)
go12 = lambda s: g.correct_mask(s, 1) | g.correct_mask(s, 2)
ng34 = lambda s: g.correct_mask(s, 3) | g.correct_mask(s, 4)
rows = []
for variant, sigs in (("main (whisker and jaw)", ("whisker_speed", "jaw_movement")), ("code (whisker only)", ("whisker_speed",))):
    for a in ("wM2", "ALM"):
        for pairing, (m1, m2) in {"pooled 1+2 vs 3+4": (go12, ng34), "type 1 vs 3": (hit, lambda s: g.correct_mask(s, 3))}.items():
            (x, y), sess = g.neuron_window_means(S, a, [m1, m2], (0.8, 1.0), signals=sigs)
            rows.append({"variant": variant, "part": "i delay", "area": a, "comparison": pairing, "window": "0.8-1.0",
                         "neurons": len(x), "sessions": len(set(sess)), "Go": x.mean(), "other": y.mean(),
                         "diff": (x - y).mean(), "p": stats.wilcoxon(x, y).pvalue})
    for window in ((1.3, 1.5), (1.0, 1.5)):
        for a in ("wS1", "wS2", "wM2", "ALM"):
            for t_ in (2, 3, 4, 5):
                (x, y), sess = g.neuron_window_means(S, a, [hit, lambda s, t_=t_: g.correct_mask(s, t_)], window, signals=sigs)
                rows.append({"variant": variant, "part": "ii response", "area": a, "comparison": f"Hit vs type {t_}",
                             "window": f"{window[0]}-{window[1]}", "neurons": len(x), "sessions": len(set(sess)),
                             "Go": x.mean(), "other": y.mean(), "diff": (x - y).mean(), "p": stats.wilcoxon(x, y).pvalue})
psth = pd.DataFrame(rows)
psth["holds"] = (psth["diff"] > 0) & (psth.p < 0.05)
print(psth.round(4).to_string(index=False))
for (variant, part, window), sub in psth.groupby(["variant", "part", "window"]):
    print(f"{variant}, {part}, {window}: {int(sub.holds.sum())} of {len(sub)} comparisons hold; failing: "
          f"{sub.loc[~sub.holds, ['area', 'comparison']].values.tolist()}")
               variant        part area        comparison  window  neurons  sessions     Go   other   diff      p  holds
main (whisker and jaw)     i delay  wM2 pooled 1+2 vs 3+4 0.8-1.0     2749        18 0.5755 -0.3880 0.9635 0.0042   True
main (whisker and jaw)     i delay  wM2       type 1 vs 3 0.8-1.0     2749        18 0.6967 -0.4100 1.1066 0.0015   True
main (whisker and jaw)     i delay  ALM pooled 1+2 vs 3+4 0.8-1.0     2763        16 0.2633 -0.2892 0.5525 0.0093   True
main (whisker and jaw)     i delay  ALM       type 1 vs 3 0.8-1.0     2763        16 0.3375 -0.2851 0.6226 0.0079   True
main (whisker and jaw) ii response  wS1     Hit vs type 2 1.3-1.5     1938        24 1.0536  0.1279 0.9257 0.0000   True
main (whisker and jaw) ii response  wS1     Hit vs type 3 1.3-1.5     1938        24 1.0536  0.0754 0.9782 0.0000   True
main (whisker and jaw) ii response  wS1     Hit vs type 4 1.3-1.5     1938        24 1.0536 -0.1258 1.1794 0.0000   True
main (whisker and jaw) ii response  wS1     Hit vs type 5 1.3-1.5     1938        24 1.0536  0.1282 0.9254 0.0000   True
main (whisker and jaw) ii response  wS2     Hit vs type 2 1.3-1.5     2064        19 1.1795  0.0066 1.1729 0.0000   True
main (whisker and jaw) ii response  wS2     Hit vs type 3 1.3-1.5     2064        19 1.1795  0.1846 0.9949 0.0063   True
main (whisker and jaw) ii response  wS2     Hit vs type 4 1.3-1.5     2064        19 1.1795 -0.1457 1.3252 0.0000   True
main (whisker and jaw) ii response  wS2     Hit vs type 5 1.3-1.5     2064        19 1.1795  0.3771 0.8024 0.1144  False
main (whisker and jaw) ii response  wM2     Hit vs type 2 1.3-1.5     2749        18 2.3754  0.4410 1.9344 0.0000   True
main (whisker and jaw) ii response  wM2     Hit vs type 3 1.3-1.5     2749        18 2.3754 -0.0315 2.4069 0.0000   True
main (whisker and jaw) ii response  wM2     Hit vs type 4 1.3-1.5     2749        18 2.3754 -0.2366 2.6120 0.0000   True
main (whisker and jaw) ii response  wM2     Hit vs type 5 1.3-1.5     2749        18 2.3754  0.2362 2.1393 0.0000   True
main (whisker and jaw) ii response  ALM     Hit vs type 2 1.3-1.5     2763        16 2.1104  0.2784 1.8320 0.0000   True
main (whisker and jaw) ii response  ALM     Hit vs type 3 1.3-1.5     2763        16 2.1104 -0.0458 2.1563 0.0000   True
main (whisker and jaw) ii response  ALM     Hit vs type 4 1.3-1.5     2763        16 2.1104 -0.1242 2.2346 0.0000   True
main (whisker and jaw) ii response  ALM     Hit vs type 5 1.3-1.5     2763        16 2.1104  0.0447 2.0658 0.0000   True
main (whisker and jaw) ii response  wS1     Hit vs type 2 1.0-1.5     1938        24 1.5834  0.1142 1.4692 0.0000   True
main (whisker and jaw) ii response  wS1     Hit vs type 3 1.0-1.5     1938        24 1.5834  0.7062 0.8772 0.0000   True
main (whisker and jaw) ii response  wS1     Hit vs type 4 1.0-1.5     1938        24 1.5834 -0.1682 1.7516 0.0000   True
main (whisker and jaw) ii response  wS1     Hit vs type 5 1.0-1.5     1938        24 1.5834  0.8405 0.7429 0.0000   True
main (whisker and jaw) ii response  wS2     Hit vs type 2 1.0-1.5     2064        19 1.6239 -0.0065 1.6305 0.0000   True
main (whisker and jaw) ii response  wS2     Hit vs type 3 1.0-1.5     2064        19 1.6239  0.6420 0.9819 0.0000   True
main (whisker and jaw) ii response  wS2     Hit vs type 4 1.0-1.5     2064        19 1.6239 -0.1803 1.8042 0.0000   True
main (whisker and jaw) ii response  wS2     Hit vs type 5 1.0-1.5     2064        19 1.6239  0.8660 0.7579 0.0002   True
main (whisker and jaw) ii response  wM2     Hit vs type 2 1.0-1.5     2749        18 2.9745  0.5245 2.4500 0.0000   True
main (whisker and jaw) ii response  wM2     Hit vs type 3 1.0-1.5     2749        18 2.9745  0.4959 2.4786 0.0000   True
main (whisker and jaw) ii response  wM2     Hit vs type 4 1.0-1.5     2749        18 2.9745 -0.2709 3.2454 0.0000   True
main (whisker and jaw) ii response  wM2     Hit vs type 5 1.0-1.5     2749        18 2.9745  0.8649 2.1096 0.0000   True
main (whisker and jaw) ii response  ALM     Hit vs type 2 1.0-1.5     2763        16 2.4896  0.3376 2.1519 0.0000   True
main (whisker and jaw) ii response  ALM     Hit vs type 3 1.0-1.5     2763        16 2.4896  0.2575 2.2321 0.0000   True
main (whisker and jaw) ii response  ALM     Hit vs type 4 1.0-1.5     2763        16 2.4896 -0.1566 2.6461 0.0000   True
main (whisker and jaw) ii response  ALM     Hit vs type 5 1.0-1.5     2763        16 2.4896  0.4201 2.0694 0.0000   True
   code (whisker only)     i delay  wM2 pooled 1+2 vs 3+4 0.8-1.0     2749        18 0.5624 -0.3806 0.9430 0.0192   True
   code (whisker only)     i delay  wM2       type 1 vs 3 0.8-1.0     2749        18 0.7199 -0.4041 1.1240 0.0008   True
   code (whisker only)     i delay  ALM pooled 1+2 vs 3+4 0.8-1.0     2763        16 0.2431 -0.2977 0.5408 0.0187   True
   code (whisker only)     i delay  ALM       type 1 vs 3 0.8-1.0     2763        16 0.3268 -0.2961 0.6229 0.0547  False
   code (whisker only) ii response  wS1     Hit vs type 2 1.3-1.5     1938        24 1.0236  0.0974 0.9262 0.0000   True
   code (whisker only) ii response  wS1     Hit vs type 3 1.3-1.5     1938        24 1.0236  0.0521 0.9715 0.0000   True
   code (whisker only) ii response  wS1     Hit vs type 4 1.3-1.5     1938        24 1.0236 -0.1029 1.1265 0.0000   True
   code (whisker only) ii response  wS1     Hit vs type 5 1.3-1.5     1938        24 1.0236  0.1414 0.8822 0.0000   True
   code (whisker only) ii response  wS2     Hit vs type 2 1.3-1.5     2064        19 1.1763  0.0099 1.1665 0.0000   True
   code (whisker only) ii response  wS2     Hit vs type 3 1.3-1.5     2064        19 1.1763  0.1743 1.0020 0.0027   True
   code (whisker only) ii response  wS2     Hit vs type 4 1.3-1.5     2064        19 1.1763 -0.1360 1.3123 0.0000   True
   code (whisker only) ii response  wS2     Hit vs type 5 1.3-1.5     2064        19 1.1763  0.3844 0.7919 0.0755  False
   code (whisker only) ii response  wM2     Hit vs type 2 1.3-1.5     2749        18 2.3648  0.4199 1.9449 0.0000   True
   code (whisker only) ii response  wM2     Hit vs type 3 1.3-1.5     2749        18 2.3648 -0.0390 2.4039 0.0000   True
   code (whisker only) ii response  wM2     Hit vs type 4 1.3-1.5     2749        18 2.3648 -0.1936 2.5585 0.0000   True
   code (whisker only) ii response  wM2     Hit vs type 5 1.3-1.5     2749        18 2.3648  0.2384 2.1265 0.0000   True
   code (whisker only) ii response  ALM     Hit vs type 2 1.3-1.5     2763        16 2.1303  0.2820 1.8483 0.0000   True
   code (whisker only) ii response  ALM     Hit vs type 3 1.3-1.5     2763        16 2.1303 -0.0583 2.1886 0.0000   True
   code (whisker only) ii response  ALM     Hit vs type 4 1.3-1.5     2763        16 2.1303 -0.1197 2.2500 0.0000   True
   code (whisker only) ii response  ALM     Hit vs type 5 1.3-1.5     2763        16 2.1303  0.0250 2.1053 0.0000   True
   code (whisker only) ii response  wS1     Hit vs type 2 1.0-1.5     1938        24 1.5586  0.0844 1.4742 0.0000   True
   code (whisker only) ii response  wS1     Hit vs type 3 1.0-1.5     1938        24 1.5586  0.6931 0.8655 0.0000   True
   code (whisker only) ii response  wS1     Hit vs type 4 1.0-1.5     1938        24 1.5586 -0.1498 1.7084 0.0000   True
   code (whisker only) ii response  wS1     Hit vs type 5 1.0-1.5     1938        24 1.5586  0.8551 0.7035 0.0000   True
   code (whisker only) ii response  wS2     Hit vs type 2 1.0-1.5     2064        19 1.6283 -0.0104 1.6387 0.0000   True
   code (whisker only) ii response  wS2     Hit vs type 3 1.0-1.5     2064        19 1.6283  0.6384 0.9900 0.0000   True
   code (whisker only) ii response  wS2     Hit vs type 4 1.0-1.5     2064        19 1.6283 -0.1799 1.8083 0.0000   True
   code (whisker only) ii response  wS2     Hit vs type 5 1.0-1.5     2064        19 1.6283  0.8868 0.7416 0.0002   True
   code (whisker only) ii response  wM2     Hit vs type 2 1.0-1.5     2749        18 2.9731  0.4885 2.4847 0.0000   True
   code (whisker only) ii response  wM2     Hit vs type 3 1.0-1.5     2749        18 2.9731  0.5015 2.4717 0.0000   True
   code (whisker only) ii response  wM2     Hit vs type 4 1.0-1.5     2749        18 2.9731 -0.2466 3.2197 0.0000   True
   code (whisker only) ii response  wM2     Hit vs type 5 1.0-1.5     2749        18 2.9731  0.8741 2.0990 0.0000   True
   code (whisker only) ii response  ALM     Hit vs type 2 1.0-1.5     2763        16 2.5120  0.3265 2.1855 0.0000   True
   code (whisker only) ii response  ALM     Hit vs type 3 1.0-1.5     2763        16 2.5120  0.2459 2.2661 0.0000   True
   code (whisker only) ii response  ALM     Hit vs type 4 1.0-1.5     2763        16 2.5120 -0.1665 2.6786 0.0000   True
   code (whisker only) ii response  ALM     Hit vs type 5 1.0-1.5     2763        16 2.5120  0.4227 2.0893 0.0000   True
code (whisker only), i delay, 0.8-1.0: 3 of 4 comparisons hold; failing: [['ALM', 'type 1 vs 3']]
code (whisker only), ii response, 1.0-1.5: 16 of 16 comparisons hold; failing: []
code (whisker only), ii response, 1.3-1.5: 15 of 16 comparisons hold; failing: [['wS2', 'Hit vs type 5']]
main (whisker and jaw), i delay, 0.8-1.0: 4 of 4 comparisons hold; failing: []
main (whisker and jaw), ii response, 1.0-1.5: 16 of 16 comparisons hold; failing: []
main (whisker and jaw), ii response, 1.3-1.5: 15 of 16 comparisons hold; failing: [['wS2', 'Hit vs type 5']]
In [21]:
fig, axs = plt.subplots(1, 5, figsize=(15, 3), sharey=True)
t = labels10
ranges = []
for ax, a in zip(axs, g.AREAS):
    for t_, col in zip(range(1, 6), ("b", "c", "r", "orange", "grey")):
        traces = []
        for s, cols in g.area_sessions(S, a):
            m = g.correct_mask(s, t_) & g.quiet_mask(s)
            if m.sum() == 0:
                continue
            x = s["c10"][m][:, :, cols].mean(axis=0) / g.W10
            traces.append(x - x[g.bin_index(-1, 0)].mean(axis=0))
        mtrace = np.concatenate(traces, axis=1).mean(axis=1)
        ranges.append((mtrace.min(), mtrace.max()))
        ax.plot(t, mtrace, color=col, lw=0.8, label=g.TRIAL_NAMES[t_])
    ax.set_title(a)
    ax.set_xlim(-0.2, 1.6)
axs[0].set_ylabel("rate change (Hz)")
axs[0].legend(fontsize=6)
plt.show()
print(f"Plotted traces span {min(r[0] for r in ranges):.2f} to {max(r[1] for r in ranges):.2f} Hz over -1 to 2 s; x axis shows -0.2 to 1.6 s.")
No description has been provided for this image
Plotted traces span -0.53 to 10.80 Hz over -1 to 2 s; x axis shows -0.2 to 1.6 s.

Result: partially reproduced. (i) holds: in wM2 and ALM delay firing is higher in Go-tone than Nogo-tone trials under both pairings (wM2 p 0.004 pooled and 0.0015 by type; ALM 0.009 and 0.008). (ii) holds in wS1, wM2 and ALM, but in wS2 the Hit response over 1.3 to 1.5 s is not significantly above No-tone Whisker trials (difference 0.80 Hz, p 0.11), so (ii) fails for one area. Over 1.0 to 1.5 s every comparison holds. With the code's whisker-only quiet rule (ii) fails for the same wS2 comparison and (i) also fails for ALM by type (Go-tone Whisker against Nogo-tone Whisker, p 0.0547), so that variant is also partial.

fig3c-delay-modulation-wm2-alm¶

In the last 200 ms of the delay of quiet Hit trials, more wM2 than ALM neurons are up-modulated relative to baseline (16.0% against 14.2%, p = 0.0499) and fewer are down-modulated (14.3% against 17.0%, p = 0.0062), by chi-squared tests.

As code, Modulation.m: counts in 0.8 to 1.0 s against -0.2 to 0 s of the same trials (bins 181:200 and 81:100), SI = 2(AUC - 0.5), 200 label permutations. Three permutation seeds; the code's mean absolute deviation as a variant.

In [22]:
W_DELAY, W_PRE = np.arange(180, 200), np.arange(80, 100)


def modulation(area, rule, rng):
    si, p = [], []
    for s, cols in g.area_sessions(S, area):
        sel = g.trial_mask(s, 1, True) & g.quiet_mask(s, rule)
        if sel.sum() == 0:
            continue
        X = s["c10"][sel][:, :, cols].astype(float)
        w_, b_ = X[:, W_DELAY].sum(axis=1), X[:, W_PRE].sum(axis=1)
        for j in range(len(cols)):
            r = g.roc_test(w_[:, j], b_[:, j], 200, rng)
            si.append(r[0])
            p.append(r[1])
    return np.array(si), np.array(p)


rows = []
for rule in ("median", "mean"):
    for seed in (5, 6, 7):
        rng = np.random.default_rng(seed)
        R = {a: modulation(a, rule, rng) for a in ("wM2", "ALM")}
        for kind, sign in (("up", 1), ("down", -1)):
            k = {a: (np.sign(R[a][0]) == sign) & (R[a][1] < 0.05) for a in R}
            tab = [[k["wM2"].sum(), (~k["wM2"]).sum()], [k["ALM"].sum(), (~k["ALM"]).sum()]]
            rows.append({"MAD": rule, "seed": seed, "kind": kind, "wM2 %": 100 * k["wM2"].mean(), "ALM %": 100 * k["ALM"].mean(),
                         "wM2 n": len(k["wM2"]), "ALM n": len(k["ALM"]),
                         "chi2 p": stats.chi2_contingency(tab, correction=False).pvalue})
mod = pd.DataFrame(rows)
print(mod.round(4).to_string(index=False))
print("\nPaper: up 16.0 (wM2) and 14.2 (ALM), p 0.0499; down 14.3 and 17.0, p 0.0062. Tolerances 10%.")
   MAD  seed kind   wM2 %   ALM %  wM2 n  ALM n  chi2 p
median     5   up 13.7868 11.6902   2749   2763  0.0196
median     5 down 11.1313 13.8617   2749   2763  0.0022
median     6   up 13.7141 11.8350   2749   2763  0.0366
median     6 down 11.0949 13.6084   2749   2763  0.0046
median     7   up 13.5686 11.5816   2749   2763  0.0261
median     7 down 10.9494 14.0065   2749   2763  0.0006
  mean     5   up 16.2605 14.3322   2749   2763  0.0467
  mean     5 down 14.0051 16.9743   2749   2763  0.0023
  mean     6   up 16.0422 14.3322   2749   2763  0.0769
  mean     6 down 13.9687 16.9743   2749   2763  0.0020
  mean     7   up 16.0422 14.2961   2749   2763  0.0708
  mean     7 down 14.2597 17.0105   2749   2763  0.0049

Paper: up 16.0 (wM2) and 14.2 (ALM), p 0.0499; down 14.3 and 17.0, p 0.0062. Tolerances 10%.

Result: partially reproduced. Under the Methods' quiet rule both directions hold and both tests are significant for every seed (up: wM2 13.6 to 13.8% against ALM 11.6 to 11.8%, p 0.020 to 0.037; down: 10.9 to 11.1% against 13.6 to 14.0%, p 0.0006 to 0.0046), but all four fractions are below tolerance. With the code's mean absolute deviation, which keeps more trials, the fractions are the paper's (up 16.0 to 16.3% against 14.3%, down 14.0 to 14.3% against 17.0%), and the up-modulation test gives p 0.047 to 0.077 depending on the seed, against the paper's 0.0499.

fig3d-wm2-infragranular-delay¶

During the late delay of Go-tone Whisker trials, wM2 infragranular neurons change their firing more than supragranular neurons (1.2 +/- 0.1 Hz against 0.03 +/- 0.10 Hz, p = 1.7 x 10^-7, two-sample t-test), while no layer difference is detected in A1, wS2 or ALM.

In [23]:
LAYER_GROUP = {"1": "supra", "2/3": "supra", "4": "gran", "5": "infra", "6a": "infra", "6b": "infra"}
rows = []
for variant, rule, sigs in (("main", "median", ("whisker_speed", "jaw_movement")),
                            ("code quiet (whisker only)", "median", ("whisker_speed",)),
                            ("code MAD (mean)", "mean", ("whisker_speed", "jaw_movement"))):
    for a in g.AREAS:
        v, L = [], []
        for s, cols in g.area_sessions(S, a):
            sel = g.trial_mask(s, 1, True) & g.quiet_mask(s, rule, sigs)
            if sel.sum() == 0:
                continue
            x = s["c10"][sel][:, :, cols].mean(axis=0) / g.W10
            v.append(x[g.bin_index(0.8, 1.0)].mean(axis=0) - x[g.bin_index(-1, 0)].mean(axis=0))
            L.append(s["units"]["allenccf_area_layer"][s["keep"][cols]])
        v = np.concatenate(v)
        L = np.array([LAYER_GROUP.get(l, "none") for l in np.concatenate(L)])
        d = {k: v[L == k] for k in ("supra", "gran", "infra")}
        row = {"variant": variant, "area": a, "unassigned": int((L == "none").sum())}
        for k, x in d.items():
            row[f"{k} n"] = len(x)
            row[f"{k} mean"] = x.mean() if len(x) else np.nan
            row[f"{k} SEM"] = x.std(ddof=1) / np.sqrt(len(x)) if len(x) > 1 else np.nan
        for p1, p2 in (("infra", "supra"), ("infra", "gran"), ("gran", "supra")):
            row[f"p {p1}-{p2}"] = stats.ttest_ind(d[p1], d[p2]).pvalue if len(d[p1]) > 1 and len(d[p2]) > 1 else np.nan
        rows.append(row)
layers = pd.DataFrame(rows)
print(layers.round(4).to_string(index=False))
for _, r in layers[layers.area == "wM2"].iterrows():
    print(f"{r['variant']}: wM2 infragranular against supragranular, t-test p = {r['p infra-supra']:.2e}")
                  variant area  unassigned  supra n  supra mean  supra SEM  gran n  gran mean  gran SEM  infra n  infra mean  infra SEM  p infra-supra  p infra-gran  p gran-supra
                     main   A1           0       65      0.4475     0.1688      79     0.5743    0.3956      636      0.2550     0.0909         0.5062        0.2761        0.7844
                     main  wS1           0      299     -0.1266     0.0867     529     0.0088    0.0679     1110      0.0441     0.0633         0.1893        0.7319        0.2242
                     main  wS2           0      460     -0.0725     0.0691     421     0.0524    0.0732     1183     -0.0507     0.0559         0.8272        0.3186        0.2147
                     main  wM2           0      703     -0.0545     0.0929       0        NaN       NaN     2046      0.9548     0.1187         0.0000           NaN           NaN
                     main  ALM           0      722      0.3340     0.1511       0        NaN       NaN     2041      0.3387     0.1079         0.9812           NaN           NaN
code quiet (whisker only)   A1           0       65      0.3465     0.1506      79     0.5599    0.3713      636      0.2524     0.0877         0.7358        0.2741        0.6218
code quiet (whisker only)  wS1           0      299     -0.2143     0.0777     529     0.0206    0.0586     1110      0.0323     0.0604         0.0455        0.9039        0.0161
code quiet (whisker only)  wS2           0      460     -0.0697     0.0715     421     0.0612    0.0738     1183     -0.0730     0.0544         0.9729        0.1851        0.2031
code quiet (whisker only)  wM2           0      703     -0.0212     0.0920       0        NaN       NaN     2046      0.9745     0.1182         0.0000           NaN           NaN
code quiet (whisker only)  ALM           0      722      0.3236     0.1485       0        NaN       NaN     2041      0.3279     0.1054         0.9823           NaN           NaN
          code MAD (mean)   A1           0       65      0.3705     0.1526      79     0.5199    0.3872      636      0.2700     0.0838         0.7063        0.3618        0.7398
          code MAD (mean)  wS1           0      299     -0.0808     0.0829     529     0.0759    0.0665     1110      0.1407     0.0620         0.0812        0.5209        0.1481
          code MAD (mean)  wS2           0      460     -0.0559     0.0670     421     0.0571    0.0716     1183      0.0150     0.0545         0.4642        0.6763        0.2491
          code MAD (mean)  wM2           0      703     -0.0030     0.0949       0        NaN       NaN     2046      1.1279     0.1230         0.0000           NaN           NaN
          code MAD (mean)  ALM           0      722      0.3834     0.1499       0        NaN       NaN     2041      0.4819     0.1072         0.6244           NaN           NaN
main: wM2 infragranular against supragranular, t-test p = 1.56e-06
code quiet (whisker only): wM2 infragranular against supragranular, t-test p = 1.94e-06
code MAD (mean): wM2 infragranular against supragranular, t-test p = 2.04e-07

Result: partially reproduced. In wM2 infragranular neurons change by 0.955 +/- 0.119 Hz and supragranular by -0.055 +/- 0.093 Hz (t-test p 1.6e-06; wM2 has no layer 4 units); the supragranular value is within tolerance, the infragranular one below it (1.1 to 1.3). No layer pair differs in A1, wS2 or ALM (smallest p 0.21). With the code's mean absolute deviation the wM2 values are 1.128 and -0.003 Hz (p 2.0e-07), within tolerance. The criterion's partial case does not cover this result (the wM2 test holds and no other pair is significant, but one value is out of tolerance); it is recorded as partial since the effect is there and one number misses.

cluster-label-link¶

The paper's cluster labels (Zenodo, processed_data/Data_Clustering.mat) can be matched to the dataset's units by the code's global unit index.

The global index is rebuilt as psth_10ms.m builds it (helper global_ids). The link holds when every labelled neuron maps to a unit of the dataset whose probe area, CCF label and layer are the ones the label file gives, and the unit is one of the 10,294 analysed here.

In [24]:
t0 = time.time()
CL = g.cluster_labels()
print(f"read {len(CL['cluster'])} cluster labels in {time.time() - t0:.0f} s; clusters {CL['cluster'].min()} to {CL['cluster'].max()}")
GID = g.global_ids(S)
print("global indices built:", len(GID), "; units in the dataset:", sum(len(s["units"]["location"]) for s in S))
match = {"mapped": 0, "area": 0, "ccf": 0, "layer": 0, "analysed": 0}
unit_cluster = {}
for gi, cl, ar, cc, la in zip(CL["global_id"], CL["cluster"], CL["area"], CL["ccf"], CL["layer"]):
    if gi not in GID:
        continue
    i, u = GID[gi]
    U = S[i]["units"]
    match["mapped"] += 1
    match["area"] += U["location"][u] == ar
    match["ccf"] += U["ccf_location"][u] == cc
    match["layer"] += U["allenccf_area_layer"][u] == la
    match["analysed"] += U["area"][u] == ar
    unit_cluster[(i, u)] = cl
n = len(CL["cluster"])
print({k: f"{v} of {n}" for k, v in match.items()})
print("Distinct dataset units matched:", len(unit_cluster))
read 10294 cluster labels in 101 s; clusters 1 to 29
global indices built: 13793 ; units in the dataset: 13793
{'mapped': '10294 of 10294', 'area': '10294 of 10294', 'ccf': '10294 of 10294', 'layer': '10294 of 10294', 'analysed': '10294 of 10294'}
Distinct dataset units matched: 10294

Result: reproduced. All 10,294 labelled neurons map to distinct dataset units with the same probe area, CCF label and layer, and each is one of the 10,294 units analysed here.

fig4b-named-clusters¶

Some clusters represent sensory responses (cluster 1, fast auditory response, mostly A1 neurons; cluster 29, fast whisker response, mostly wS1 and wS2), clusters 11 and 25 fire during the delay only on Go-tone trials and consist mainly of wM2 and ALM neurons, and cluster 4 decreases its firing during the Go-tone delay and is spread over the five areas.

PSTHs as fig3b-delay-and-response-psth (quiet correct trials, baseline -1 to 0 s). The response of clusters 1 and 29 is shown for each correct trial type that has the stimulus.

In [25]:
def cluster_of(s_index, area):
    s = S[s_index]
    rows_ = s["keep"][g.area_columns(s, area)]
    return np.array([unit_cluster.get((s_index, int(u)), 0) for u in rows_])


comp = []
for a in g.AREAS:
    for i in range(len(S)):
        for c_ in cluster_of(i, a):
            comp.append((c_, a))
comp = pd.DataFrame(comp, columns=["cluster", "area"])
share = pd.crosstab(comp.cluster, comp.area, normalize="index")[g.AREAS] * 100
counts = pd.crosstab(comp.cluster, comp.area)[g.AREAS]
print("Neurons per cluster and area (%), clusters 1, 4, 11, 25, 29:")
print(pd.concat([counts.loc[[1, 4, 11, 25, 29]].sum(axis=1).rename("n"), share.loc[[1, 4, 11, 25, 29]].round(1)], axis=1).to_string())


def cluster_window(cl, masks, window):
    out = [[] for _ in masks]
    for a in g.AREAS:
        for i, s in enumerate(S):
            cols = g.area_columns(s, a)
            if len(cols) == 0:
                continue
            sel_cols = cols[cluster_of(i, a) == cl]
            if len(sel_cols) == 0:
                continue
            q = g.quiet_mask(s)
            for k, m in enumerate(masks):
                mm = m(s) & q
                if mm.sum() == 0:
                    continue
                x = s["c10"][mm][:, :, sel_cols].mean(axis=0) / g.W10
                out[k].append(x[g.bin_index(*window)].mean(axis=0) - x[g.bin_index(-1, 0)].mean(axis=0))
    return [np.concatenate(o) for o in out]


tone_types = [lambda s, t_=t_: g.correct_mask(s, t_) for t_ in (1, 2, 3, 4)]
whisk_types = [lambda s, t_=t_: g.correct_mask(s, t_) for t_ in (1, 3, 5)]
r1 = cluster_window(1, tone_types, (0.01, 0.03))
r29 = cluster_window(29, whisk_types, (1.01, 1.03))
print("\nCluster 1, mean change 0 to 30 ms (Hz), trial types 1-4:", [round(x.mean(), 2) for x in r1])
print("Cluster 29, mean change 1.00 to 1.03 s (Hz), trial types 1, 3, 5:", [round(x.mean(), 2) for x in r29])
for cl in (11, 25, 4):
    h_, n_ = cluster_window(cl, [lambda s: g.correct_mask(s, 1), lambda s: g.correct_mask(s, 3)], (0.8, 1.0))
    print(f"Cluster {cl}, 0.8 to 1.0 s: Hit {h_.mean():.2f} Hz, Nogo-tone Whisker CR {n_.mean():.2f} Hz "
          f"(neurons {len(h_)}, {len(n_)})")


def mostly(cl, group):
    sh = share.loc[cl]
    a_ = sh[list(group)].sum() > 50
    b_ = set(sh.sort_values(ascending=False).index[:len(group)]) == set(group)
    return a_, b_


for cl, group in ((1, ("A1",)), (29, ("wS1", "wS2")), (11, ("wM2", "ALM")), (25, ("wM2", "ALM"))):
    a_, b_ = mostly(cl, group)
    print(f"Cluster {cl} mostly {group}: reading (a) more than half: {a_}; reading (b) largest share: {b_}")
print("Cluster 4, share in each area (%):", share.loc[4].round(1).to_dict(), "; at least 5% in each:", bool((share.loc[4] >= 5).all()))
Neurons per cluster and area (%), clusters 1, 4, 11, 25, 29:
           n    A1   wS1   wS2   wM2   ALM
cluster                                   
1        187  30.5  20.3  21.4  12.8  15.0
4        367   7.1  12.0  21.3  27.8  31.9
11       209   2.4   3.8   3.3  49.3  41.1
25       302   2.3   6.3   8.3  35.1  48.0
29       325   2.5  45.2  41.5   7.4   3.4
Cluster 1, mean change 0 to 30 ms (Hz), trial types 1-4: [np.float64(13.55), np.float64(12.98), np.float64(17.18), np.float64(17.27)]
Cluster 29, mean change 1.00 to 1.03 s (Hz), trial types 1, 3, 5: [np.float64(21.92), np.float64(21.81), np.float64(21.73)]
Cluster 11, 0.8 to 1.0 s: Hit 11.54 Hz, Nogo-tone Whisker CR -0.79 Hz (neurons 209, 209)
Cluster 25, 0.8 to 1.0 s: Hit 3.56 Hz, Nogo-tone Whisker CR -0.29 Hz (neurons 302, 302)
Cluster 4, 0.8 to 1.0 s: Hit -1.60 Hz, Nogo-tone Whisker CR 0.05 Hz (neurons 367, 367)
Cluster 1 mostly ('A1',): reading (a) more than half: False; reading (b) largest share: True
Cluster 29 mostly ('wS1', 'wS2'): reading (a) more than half: True; reading (b) largest share: True
Cluster 11 mostly ('wM2', 'ALM'): reading (a) more than half: True; reading (b) largest share: True
Cluster 25 mostly ('wM2', 'ALM'): reading (a) more than half: True; reading (b) largest share: True
Cluster 4, share in each area (%): {'A1': 7.1, 'wS1': 12.0, 'wS2': 21.3, 'wM2': 27.8, 'ALM': 31.9} ; at least 5% in each: True

Result: blocked (methods underspecified). Parts (2) to (4) hold under both readings of "mostly": cluster 29 is 45.2% wS1 and 41.5% wS2 with a whisker response of 21.7 to 21.9 Hz; clusters 11 and 25 are 90.4% and 83.1% wM2 and ALM and fire more in Hit than in Nogo CR trials over the late delay (11.54 against -0.79 Hz, 3.56 against -0.29 Hz); cluster 4 fires less in Hit (-1.60 against 0.05 Hz) and has 7.1 to 31.9% of its neurons in each area. Cluster 1 has a fast auditory response (13.0 to 17.3 Hz) and its largest share in A1 (30.5%), but not more than half: reading (b) gives reproduced and reading (a) partially reproduced. The criterion blocks the claim when the readings differ.

fig5a-single-neuron-context¶

Comparing Hit with Nogo-tone Whisker correct rejection trials in the last 200 ms of the delay, wM2 and ALM have the highest proportions of context-modulated neurons (wM2, 20% increase firing by 8 Hz on average, 14% decrease by 3 Hz; ALM, 17% increase by 8 Hz, 16% decrease by 3 Hz), and wM2 has the largest proportion of Go-tone excited neurons.

As code, Roc_hit_cr3.m: counts in bins 181:200 (0.8 to 1.0 s) of quiet Hit against quiet Nogo-tone Whisker CR trials, SI and 200-permutation p; the change is the Hit minus CR mean rate.

In [26]:
rows = []
for rule in ("median", "mean"):
    rng = np.random.default_rng(8)
    for a in g.AREAS:
        si, p, d = [], [], []
        for s, cols in g.area_sessions(S, a):
            q = g.quiet_mask(s, rule)
            m1, m2 = g.trial_mask(s, 1, True) & q, g.trial_mask(s, 3, False) & q
            if m1.sum() == 0 or m2.sum() == 0:
                continue
            x = s["c10"][m1][:, W_DELAY][:, :, cols].sum(axis=1).astype(float)
            y = s["c10"][m2][:, W_DELAY][:, :, cols].sum(axis=1).astype(float)
            for j in range(len(cols)):
                r = g.roc_test(x[:, j], y[:, j], 200, rng)
                si.append(r[0])
                p.append(r[1])
            d.append(x.mean(axis=0) / 0.2 - y.mean(axis=0) / 0.2)
        si, p, d = np.array(si), np.array(p), np.concatenate(d)
        up, dn = (si > 0) & (p < 0.05), (si < 0) & (p < 0.05)
        rows.append({"MAD": rule, "area": a, "neurons": len(si), "up %": 100 * up.mean(), "up mean Hz": d[up].mean(),
                     "down %": 100 * dn.mean(), "down mean Hz": d[dn].mean(), "modulated %": 100 * (up | dn).mean()})
ctx = pd.DataFrame(rows)
print(ctx.round(2).to_string(index=False))
exp5a = {("wM2", "up %"): (20, 2), ("wM2", "up mean Hz"): (8, 0.8), ("wM2", "down %"): (14, 1.4), ("wM2", "down mean Hz"): (-3, 0.5),
         ("ALM", "up %"): (17, 1.7), ("ALM", "up mean Hz"): (8, 0.8), ("ALM", "down %"): (16, 1.6), ("ALM", "down mean Hz"): (-3, 0.5)}
for rule in ("median", "mean"):
    sub = ctx[ctx.MAD == rule].set_index("area")
    within = {f"{a} {k}": bool(abs(sub.loc[a, k] - v) <= tol) for (a, k), (v, tol) in exp5a.items()}
    print(f"\n{rule}: within tolerance {sum(within.values())} of 8: {within}")
    print(f"  wM2 up fraction largest: {sub['up %'].idxmax() == 'wM2'}; wM2 and ALM modulated above A1, wS1, wS2: "
          f"{min(sub.loc['wM2', 'modulated %'], sub.loc['ALM', 'modulated %']) > sub.loc[['A1', 'wS1', 'wS2'], 'modulated %'].max()}")
   MAD area  neurons  up %  up mean Hz  down %  down mean Hz  modulated %
median   A1      780  9.49        4.04    6.03         -3.06        15.51
median  wS1     1938  8.57        4.34    3.56         -3.25        12.13
median  wS2     2064  8.72        4.12    3.88         -2.38        12.60
median  wM2     2749 17.86        8.65   11.50         -3.16        29.36
median  ALM     2763 14.48        8.05   12.92         -3.40        27.40
  mean   A1      780 11.15        3.91    6.92         -2.51        18.08
  mean  wS1     1938 10.42        4.21    5.68         -2.47        16.10
  mean  wS2     2064 10.03        3.90    4.26         -2.02        14.29
  mean  wM2     2749 20.04        8.14   14.11         -2.77        34.16
  mean  ALM     2763 16.72        7.53   16.14         -2.97        32.86

median: within tolerance 4 of 8: {'wM2 up %': False, 'wM2 up mean Hz': True, 'wM2 down %': False, 'wM2 down mean Hz': True, 'ALM up %': False, 'ALM up mean Hz': True, 'ALM down %': False, 'ALM down mean Hz': True}
  wM2 up fraction largest: True; wM2 and ALM modulated above A1, wS1, wS2: True

mean: within tolerance 8 of 8: {'wM2 up %': True, 'wM2 up mean Hz': True, 'wM2 down %': True, 'wM2 down mean Hz': True, 'ALM up %': True, 'ALM up mean Hz': True, 'ALM down %': True, 'ALM down mean Hz': True}
  wM2 up fraction largest: True; wM2 and ALM modulated above A1, wS1, wS2: True

Result: partially reproduced. Under the Methods' quiet rule the wM2 up-modulated fraction is the largest (17.9%) and wM2 (29.4%) and ALM (27.4%) have more modulated neurons than A1, wS1 and wS2 (at most 15.5%), and the four firing changes are within tolerance (8.65, -3.16, 8.05, -3.40 Hz), but the four fractions are below it (wM2 17.9% and 11.5%, ALM 14.5% and 12.9%). With the code's mean absolute deviation all eight values are within tolerance (wM2 20.0%, 8.14 Hz, 14.1%, -2.77 Hz; ALM 16.7%, 7.53 Hz, 16.1%, -2.97 Hz).

fig6a-pca-delay-states¶

In the first two PCs, A1, wS1 and wS2 activity returns near its start by the end of the delay, while in correct Go-tone trials wM2 and ALM settle within about 200 ms into a state far from the origin, reached with and without the whisker stimulus; Nogo correct rejections return to baseline and Miss trials fail to reach the Go-tone state. PC1 explains 11% (A1, wS1, wS2), 17% (wM2) and 14% (ALM) of variance, PC2 6% (A1, wS1, wS2) and 8% (wM2, ALM).

As code, Ghaderi2025_Figure6_a_pca.m: per area all neurons, mean over quiet completed trials of Hit, Nogo-tone Whisker CR, Go-tone No-Whisker CR and Miss in 50 ms bins, baseline (-1 to 0 s) subtracted, the four conditions concatenated (240 time points), neurons with no range (or no trials of a condition) dropped, each divided by its range; PCA over time points.

In [27]:
CONDS6 = [("Hit", 1, True), ("Nogo CR", 3, False), ("Go NoW CR", 2, False), ("Miss", 1, False)]


def pca_area(area, rule, fit_on=None):
    blocks = []
    for s, cols in g.area_sessions(S, area):
        q = g.quiet_mask(s, rule)
        M = []
        for _, t_, l_ in CONDS6:
            m = g.trial_mask(s, t_, l_) & q
            if m.sum():
                x = s["c10"][m][:, :, cols].astype(float).reshape(m.sum(), 60, 5, len(cols)).sum(axis=2).mean(axis=0)
            else:
                x = np.full((60, len(cols)), np.nan)
            M.append(x - x[:20].mean(axis=0))
        blocks.append(np.concatenate(M, axis=0))
    X = np.concatenate(blocks, axis=1).T
    rng_ = X.max(axis=1) - X.min(axis=1)
    ok = np.isfinite(rng_) & (rng_ > 0)
    X = (X[ok] / rng_[ok, None]).T
    fit = X if fit_on is None else X[np.concatenate([np.arange(i * 60, (i + 1) * 60) for i in fit_on])]
    mu = fit.mean(axis=0)
    _, sv, Vt = np.linalg.svd(fit - mu, full_matrices=False)
    ev = 100 * sv ** 2 / (sv ** 2).sum()
    P = (X - X.mean(axis=0)) @ Vt[:2].T if fit_on is None else (X - mu) @ Vt[:2].T
    dist = []
    for i in range(4):
        seg = P[i * 60:(i + 1) * 60]
        dist.append(np.linalg.norm(seg[36:40].mean(axis=0) - seg[:20].mean(axis=0)))
    hitseg = P[:60]
    dh = np.linalg.norm(hitseg - hitseg[:20].mean(axis=0), axis=1)
    return {"area": area, "neurons kept": int(ok.sum()), "neurons": len(ok), "PC1 %": ev[0], "PC2 %": ev[1],
            **{f"dist {c[0]}": d_ for c, d_ in zip(CONDS6, dist)}, "Hit dist at 1.0 / max 0-1 s": dh[39] / dh[20:40].max()}, P


exp6 = {"A1": (11, 6), "wS1": (11, 6), "wS2": (11, 6), "wM2": (17, 8), "ALM": (14, 8)}
pca_rows, projections = [], {}
for variant, rule, fit_on in (("main", "median", None), ("code MAD (mean)", "mean", None), ("legend: fit on Hit and Nogo CR", "median", (0, 1))):
    for a in g.AREAS:
        r, P_ = pca_area(a, rule, fit_on)
        r["variant"] = variant
        r["PC1 within"] = abs(r["PC1 %"] - exp6[a][0]) <= 0.1 * exp6[a][0]
        r["PC2 within"] = abs(r["PC2 %"] - exp6[a][1]) <= 0.1 * exp6[a][1]
        if a in ("wM2", "ALM"):
            r["geometry"] = min(r["dist Hit"], r["dist Go NoW CR"]) > max(r["dist Nogo CR"], r["dist Miss"])
        else:
            r["geometry"] = r["Hit dist at 1.0 / max 0-1 s"] < 0.5
        pca_rows.append(r)
        if variant == "main":
            projections[a] = P_
pca_tab = pd.DataFrame(pca_rows)
print(pca_tab.round(3).to_string(index=False))
area  neurons kept  neurons  PC1 %  PC2 %  dist Hit  dist Nogo CR  dist Go NoW CR  dist Miss  Hit dist at 1.0 / max 0-1 s                        variant  PC1 within  PC2 within  geometry
  A1           780      780 10.081  5.523     0.482         0.275           0.395      0.482                        0.048                           main        True        True      True
 wS1          1938     1938  9.770  5.472     0.911         0.731           0.641      1.061                        0.159                           main       False        True      True
 wS2          2061     2064 10.768  5.739     1.122         0.778           0.914      1.473                        0.152                           main        True        True      True
 wM2          2616     2749 14.966  7.360     7.139         0.957           5.869      1.904                        0.905                           main       False        True      True
 ALM          2662     2763 12.614  6.788     6.640         0.455           5.647      1.949                        0.986                           main        True       False      True
  A1           780      780 11.075  6.011     0.894         0.187           0.748      0.835                        0.122                code MAD (mean)        True        True      True
 wS1          1938     1938 10.604  6.128     1.200         0.544           0.814      1.180                        0.227                code MAD (mean)        True        True      True
 wS2          2061     2064 11.471  6.239     1.350         0.660           1.129      1.304                        0.185                code MAD (mean)        True        True      True
 wM2          2749     2749 16.633  8.208     7.951         0.861           6.633      2.044                        0.931                code MAD (mean)        True        True      True
 ALM          2763     2763 14.266  7.787     7.581         0.383           6.438      1.951                        1.000                code MAD (mean)        True        True      True
  A1           780      780 17.336  7.828     0.836         0.549           0.393      0.144                        0.141 legend: fit on Hit and Nogo CR       False       False      True
 wS1          1938     1938 16.687  9.844     0.810         0.789           0.422      0.796                        0.168 legend: fit on Hit and Nogo CR       False       False      True
 wS2          2061     2064 18.561  9.478     0.955         0.776           0.577      1.012                        0.145 legend: fit on Hit and Nogo CR       False       False      True
 wM2          2616     2749 27.247 10.319     6.737         1.106           4.629      1.064                        0.863 legend: fit on Hit and Nogo CR       False       False      True
 ALM          2662     2763 25.046 10.150     5.757         0.548           4.031      0.833                        0.855 legend: fit on Hit and Nogo CR       False       False      True
In [28]:
fig, axs = plt.subplots(1, 5, figsize=(15, 3))
lo, hi = [], []
for ax, a in zip(axs, g.AREAS):
    P_ = projections[a]
    for i, (name, *_), col in zip(range(4), CONDS6, ("b", "r", "c", "purple")):
        seg = P_[i * 60:(i + 1) * 60][20:40]
        ax.plot(seg[:, 0], seg[:, 1], color=col, label=name)
        ax.plot(seg[0, 0], seg[0, 1], "o", color=col, ms=3)
    lo.append(P_.min())
    hi.append(P_.max())
    ax.set_title(a)
axs[0].legend(fontsize=6)
plt.show()
print(f"Delay trajectories (0 to 1 s) in PC1-PC2; projections span {min(lo):.2f} to {max(hi):.2f}.")
No description has been provided for this image
Delay trajectories (0 to 1 s) in PC1-PC2; projections span -13.36 to 11.43.

Result: partially reproduced. The geometry holds: in wM2 and ALM the end-of-delay state of Hit and Go-tone No-Whisker trials is far from baseline (distances 7.14 and 5.87 in wM2, 6.64 and 5.65 in ALM) while Nogo CR (0.96, 0.45) and Miss (1.90, 1.95) stay near it, and in A1, wS1 and wS2 the Hit trajectory is back to 0.05 to 0.16 of its maximum distance at 1.0 s. Seven of the ten explained variances are within tolerance under the Methods' quiet rule (PC1 wS1 9.8 and wM2 15.0% and PC2 ALM 6.8% are below it; PC1 ALM 12.61% is just inside). With the code's mean absolute deviation all ten are within tolerance (PC1 11.1, 10.6, 11.5, 16.6, 14.3%; PC2 6.0, 6.1, 6.2, 8.2, 7.8%). The legend's reading (PCs fitted on Hit and Nogo CR only) gives larger explained variances (PC1 16.7 to 27.2%).

fig6b-context-coding-direction¶

Projected on a context coding direction, late-delay activity in wM2 and ALM is high in Hit trials and significantly lower in Nogo-tone, Go-tone No-Whisker and Miss trials.

As the criterion: per area-session with at least 5 neurons, CD context from a random 20% of quiet Hit and of quiet Nogo CR trials (Methods; 30% in the code, a variant), the mean over bins labelled 0.8 to 1.0 s of the difference of mean count vectors, unit length (Gram-Schmidt with the later directions leaves it unchanged); held-out Hit and Nogo CR trials and all Go-tone No-Whisker CR and Miss trials projected; per session the mean projection over 0.8 to 1.0 s; Wilcoxon, p times 3.

In [29]:
WCTX = g.bin_index(0.8, 1.0)


def cd_context(frac, rule, rng):
    rows = []
    for a in g.AREAS:
        for s, cols in g.area_sessions(S, a, 5):
            q = g.quiet_mask(s, rule)
            X = s["c10"][:, :, cols].astype(float)
            ids = {name: np.flatnonzero(g.trial_mask(s, t_, l_) & q) for name, t_, l_ in CONDS6}
            h_tr, h_te = g.split_train(ids["Hit"], frac, rng)
            c_tr, c_te = g.split_train(ids["Nogo CR"], frac, rng)
            if len(h_tr) == 0 or len(c_tr) == 0:
                rows.append({"area": a, "session": s["session"], "dropped": True})
                continue
            cd = X[h_tr][:, WCTX].mean(axis=(0, 1)) - X[c_tr][:, WCTX].mean(axis=(0, 1))
            cd /= np.linalg.norm(cd)
            pr = lambda t: (X[t][:, WCTX] @ cd).mean() if len(t) else np.nan
            rows.append({"area": a, "session": s["session"], "dropped": False, "Hit": pr(h_te), "Nogo CR": pr(c_te),
                         "Go NoW CR": pr(ids["Go NoW CR"]), "Miss": pr(ids["Miss"])})
    return pd.DataFrame(rows)


def hit_vs(df, others, factor=3):
    out = []
    for a in g.AREAS:
        sub = df[(df.area == a) & ~df.dropped]
        for o in others:
            ok = sub["Hit"].notna() & sub[o].notna()
            p_ = stats.wilcoxon(sub.loc[ok, "Hit"], sub.loc[ok, o]).pvalue
            out.append({"area": a, "vs": o, "sessions": int(ok.sum()), "Hit": sub.loc[ok, "Hit"].mean(),
                        "other": sub.loc[ok, o].mean(), "diff": (sub.loc[ok, "Hit"] - sub.loc[ok, o]).mean(),
                        "p x3": min(1.0, factor * p_)})
    return pd.DataFrame(out)


for frac, rule, seed in ((0.2, "median", 9), (0.3, "median", 9), (0.2, "mean", 9), (0.2, "median", 10)):
    df = cd_context(frac, rule, np.random.default_rng(seed))
    res = hit_vs(df, ["Nogo CR", "Go NoW CR", "Miss"])
    res["holds"] = (res["diff"] > 0) & (res["p x3"] < 0.05)
    print(f"Training fraction {frac}, MAD {rule}, seed {seed}; area-sessions dropped (no training trials): {int(df.dropped.sum())}")
    print(res.round(4).to_string(index=False))
    print("  wM2 and ALM, comparisons holding:", int(res[res.area.isin(["wM2", "ALM"])].holds.sum()), "of 6\n")
Training fraction 0.2, MAD median, seed 9; area-sessions dropped (no training trials): 0
area        vs  sessions    Hit  other   diff   p x3  holds
  A1   Nogo CR        14 0.1026 0.0316 0.0710 0.0018   True
  A1 Go NoW CR        14 0.1026 0.0867 0.0159 0.1058  False
  A1      Miss        14 0.1026 0.0489 0.0537 0.0201   True
 wS1   Nogo CR        24 0.1012 0.0303 0.0710 0.0037   True
 wS1 Go NoW CR        24 0.1012 0.0974 0.0039 0.9915  False
 wS1      Miss        24 0.1012 0.0693 0.0320 0.1370  False
 wS2   Nogo CR        19 0.1518 0.0715 0.0803 0.0000   True
 wS2 Go NoW CR        19 0.1518 0.1339 0.0179 0.2185  False
 wS2      Miss        19 0.1518 0.0999 0.0518 0.0019   True
 wM2   Nogo CR        18 0.6416 0.1084 0.5332 0.0000   True
 wM2 Go NoW CR        18 0.6416 0.5497 0.0919 0.0010   True
 wM2      Miss        17 0.6384 0.2286 0.4098 0.0000   True
 ALM   Nogo CR        16 0.5780 0.0839 0.4941 0.0001   True
 ALM Go NoW CR        16 0.5780 0.4868 0.0912 0.0039   True
 ALM      Miss        15 0.5814 0.1785 0.4029 0.0002   True
  wM2 and ALM, comparisons holding: 6 of 6

Training fraction 0.3, MAD median, seed 9; area-sessions dropped (no training trials): 0
area        vs  sessions    Hit  other   diff   p x3  holds
  A1   Nogo CR        14 0.1142 0.0337 0.0805 0.0018   True
  A1 Go NoW CR        14 0.1142 0.0991 0.0150 0.1740  False
  A1      Miss        14 0.1142 0.0683 0.0459 0.1058  False
 wS1   Nogo CR        24 0.1304 0.0410 0.0895 0.0000   True
 wS1 Go NoW CR        24 0.1304 0.1078 0.0227 0.1370  False
 wS1      Miss        24 0.1304 0.0657 0.0647 0.0094   True
 wS2   Nogo CR        19 0.1674 0.0836 0.0839 0.0000   True
 wS2 Go NoW CR        19 0.1674 0.1552 0.0123 0.6304  False
 wS2      Miss        19 0.1674 0.1157 0.0518 0.0024   True
 wM2   Nogo CR        18 0.6671 0.1146 0.5525 0.0000   True
 wM2 Go NoW CR        18 0.6671 0.5725 0.0946 0.0047   True
 wM2      Miss        17 0.6630 0.2429 0.4202 0.0000   True
 ALM   Nogo CR        16 0.6077 0.0840 0.5238 0.0001   True
 ALM Go NoW CR        16 0.6077 0.5080 0.0997 0.0009   True
 ALM      Miss        15 0.6095 0.1884 0.4211 0.0002   True
  wM2 and ALM, comparisons holding: 6 of 6

Training fraction 0.2, MAD mean, seed 9; area-sessions dropped (no training trials): 0
area        vs  sessions    Hit   other    diff   p x3  holds
  A1   Nogo CR        14 0.0339 -0.0100  0.0440 0.2355  False
  A1 Go NoW CR        14 0.0339  0.0419 -0.0080 1.0000  False
  A1      Miss        14 0.0339  0.0376 -0.0037 1.0000  False
 wS1   Nogo CR        24 0.1420  0.0405  0.1015 0.0000   True
 wS1 Go NoW CR        24 0.1420  0.1145  0.0275 0.0808  False
 wS1      Miss        24 0.1420  0.0531  0.0889 0.0003   True
 wS2   Nogo CR        19 0.1751  0.0850  0.0901 0.0001   True
 wS2 Go NoW CR        19 0.1751  0.1465  0.0286 0.0016   True
 wS2      Miss        19 0.1751  0.0944  0.0807 0.0000   True
 wM2   Nogo CR        18 0.6858  0.1158  0.5700 0.0000   True
 wM2 Go NoW CR        18 0.6858  0.5820  0.1038 0.0025   True
 wM2      Miss        18 0.6858  0.2332  0.4526 0.0000   True
 ALM   Nogo CR        16 0.6348  0.0859  0.5490 0.0001   True
 ALM Go NoW CR        16 0.6348  0.5200  0.1148 0.0006   True
 ALM      Miss        16 0.6348  0.1830  0.4519 0.0001   True
  wM2 and ALM, comparisons holding: 6 of 6

Training fraction 0.2, MAD median, seed 10; area-sessions dropped (no training trials): 0
area        vs  sessions    Hit  other   diff   p x3  holds
  A1   Nogo CR        14 0.0859 0.0271 0.0588 0.0011   True
  A1 Go NoW CR        14 0.0859 0.0720 0.0139 0.0201   True
  A1      Miss        14 0.0859 0.0639 0.0220 0.4592  False
 wS1   Nogo CR        24 0.1371 0.0520 0.0851 0.0002   True
 wS1 Go NoW CR        24 0.1371 0.1177 0.0194 0.4545  False
 wS1      Miss        24 0.1371 0.0591 0.0780 0.0094   True
 wS2   Nogo CR        19 0.1960 0.1128 0.0832 0.0001   True
 wS2 Go NoW CR        19 0.1960 0.1723 0.0237 0.0542  False
 wS2      Miss        19 0.1960 0.1248 0.0712 0.0001   True
 wM2   Nogo CR        18 0.6214 0.0829 0.5386 0.0000   True
 wM2 Go NoW CR        18 0.6214 0.5353 0.0861 0.0020   True
 wM2      Miss        17 0.6173 0.2187 0.3986 0.0000   True
 ALM   Nogo CR        16 0.5637 0.0833 0.4803 0.0001   True
 ALM Go NoW CR        16 0.5637 0.4725 0.0912 0.0189   True
 ALM      Miss        15 0.5663 0.1984 0.3679 0.0002   True
  wM2 and ALM, comparisons holding: 6 of 6

Result: reproduced. With 20% training trials and the Methods' quiet rule, Hit projections in wM2 exceed Nogo CR, Go-tone No-Whisker CR and Miss (corrected p below 0.0001, 0.0010 and below 0.0001) and in ALM likewise (0.0001, 0.0039, 0.0002); all six comparisons hold under the variants (30% training, the code's MAD, another seed).

fig6c-temporal-correlation¶

In wM2 and ALM the Go-tone induces a long-lasting increase in correlated population activity during the delay in Hit and Go-tone No-Whisker trials, absent in Nogo-tone and Miss trials, while in A1, wS1 and wS2 the cue evokes only a brief increase.

As the criterion (code, Temporal_corrrelation_10ms.m and Ghaderi2025_Figure6_c_temporalCorrelation.m).

In [30]:
off = np.ones((100, 100)) - np.eye(100)
off[off == 0] = np.nan
rows, maps = [], {}
for a in g.AREAS:
    for s, cols in g.area_sessions(S, a, 5):
        q = g.quiet_mask(s)
        row = {"area": a, "session": s["session"]}
        for name, t_, l_ in CONDS6:
            m = g.trial_mask(s, t_, l_) & q
            if m.sum() == 0:
                row[name] = np.nan
                continue
            R = g.temporal_correlation(s["c10"][m][:, :, cols])
            R = R - np.nanmean(R[:100, :100] * off)
            row[name] = np.nanmean(R[99:200, 99:200])
            maps.setdefault((a, name), []).append(R)
        rows.append(row)
tc = pd.DataFrame(rows).assign(dropped=False)
res = hit_vs(tc, ["Nogo CR", "Go NoW CR", "Miss"])
res["holds"] = (res["diff"] > 0) & (res["p x3"] < 0.05)
print(res.round(5).to_string(index=False))
a1 = tc[tc.area == "A1"].reset_index(drop=True)
print("\nA1 without its fourth Hit session (as the code does):")
print(hit_vs(a1.drop(index=3).assign(area="A1"), ["Nogo CR", "Go NoW CR", "Miss"]).query("area == 'A1'").round(4).to_string(index=False))
area        vs  sessions     Hit   other    diff    p x3  holds
  A1   Nogo CR        14 0.01163 0.00910 0.00253 1.00000  False
  A1 Go NoW CR        14 0.01163 0.00818 0.00345 1.00000  False
  A1      Miss        14 0.01163 0.00467 0.00696 1.00000  False
 wS1   Nogo CR        24 0.01489 0.00926 0.00563 0.23619  False
 wS1 Go NoW CR        24 0.01489 0.01390 0.00099 1.00000  False
 wS1      Miss        24 0.01489 0.00262 0.01227 0.08739  False
 wS2   Nogo CR        19 0.01525 0.00981 0.00544 0.09702  False
 wS2 Go NoW CR        19 0.01525 0.01311 0.00214 1.00000  False
 wS2      Miss        19 0.01525 0.00968 0.00557 0.23963  False
 wM2   Nogo CR        18 0.05630 0.00768 0.04863 0.00002   True
 wM2 Go NoW CR        18 0.05630 0.04582 0.01049 0.00387   True
 wM2      Miss        17 0.05260 0.01424 0.03836 0.00005   True
 ALM   Nogo CR        16 0.04550 0.00853 0.03696 0.00018   True
 ALM Go NoW CR        16 0.04550 0.03381 0.01169 0.00027   True
 ALM      Miss        15 0.04488 0.01092 0.03396 0.00037   True

A1 without its fourth Hit session (as the code does):
area        vs  sessions    Hit  other   diff  p x3
  A1   Nogo CR        13 0.0112 0.0078 0.0034   1.0
  A1 Go NoW CR        13 0.0112 0.0082 0.0030   1.0
  A1      Miss        13 0.0112 0.0110 0.0002   1.0
In [31]:
fig, axs = plt.subplots(2, 5, figsize=(15, 6))
vals = []
for j, a in enumerate(g.AREAS):
    for i, name in enumerate(("Hit", "Nogo CR")):
        M = np.nanmean(maps[(a, name)], axis=0)
        vals.append(M)
        axs[i, j].imshow(M, origin="lower", extent=[-1, 2, -1, 2], vmin=-0.02, vmax=0.08, cmap="viridis")
        axs[i, j].set_title(f"{a} {name}", fontsize=8)
allv = np.concatenate([v.ravel() for v in vals])
print(f"Mean maps span {np.nanmin(allv):.3f} to {np.nanmax(allv):.3f}; colour scale -0.02 to 0.08, "
      f"{int(np.sum(allv > 0.08) + np.sum(allv < -0.02))} of {np.isfinite(allv).sum()} values outside it (mostly the diagonal).")
plt.show()
Mean maps span -0.111 to 0.924; colour scale -0.02 to 0.08, 221306 of 900000 values outside it (mostly the diagonal).
No description has been provided for this image

Result: reproduced. In wM2 the baseline-subtracted delay correlation of Hit trials exceeds Nogo CR, Go-tone No-Whisker CR and Miss (corrected p 2.3e-05, 0.0039, 4.6e-05; 18, 18 and 17 sessions) and in ALM likewise (0.00018, 0.00027, 0.00037). The brief cue-evoked increase in A1, wS1 and wS2 is visible in the maps and is not judged.

fig7b-early-whisker-response¶

Whisker-evoked activity in the Go-tone context is transiently reduced in wS1 and wS2 around 15 ms after the deflection and higher from about 30 ms on in most areas, compared with the Nogo-tone context.

As the criterion (code, psth_5ms.m and Ghaderi2025_Figure7_b_DeltaFR.m). Bins are labelled by their right edge, as in the code.

In [32]:
lab5 = g.T5_START + g.W5 * np.arange(1, g.N5 + 1)
rows, dfr = [], {}
for a in g.AREAS:
    D = []
    for s, cols in g.area_sessions(S, a):
        q = g.quiet_mask(s)
        m1, m2 = g.trial_mask(s, 1, True) & q, g.trial_mask(s, 3, False) & q
        if m1.sum() == 0 or m2.sum() == 0:
            continue
        x = s["c5"][m1][:, :, cols].mean(axis=0) / g.W5
        y = s["c5"][m2][:, :, cols].mean(axis=0) / g.W5
        D.append((x - x[:10].mean(axis=0)) - (y - y[:10].mean(axis=0)))
    D = np.concatenate(D, axis=1)
    dfr[a] = D
    for i in range(g.N5):
        rows.append({"area": a, "bin": round(lab5[i], 3), "neurons": D.shape[1], "mean dFR": D[i].mean(),
                     "p": stats.wilcoxon(D[i]).pvalue if np.any(D[i] != 0) else 1.0})
b7 = pd.DataFrame(rows)
b7["p_FDR_area"] = b7.groupby("area").p.transform(lambda p: g.bh_fdr(p.values))
b7["p_FDR_all"] = g.bh_fdr(b7.p.values)
for col in ("p_FDR_area", "p_FDR_all"):
    print(f"FDR {col}:")
    for a in g.AREAS:
        sub = b7[b7.area == a]
        neg = sub[(sub[col] < 0.05) & (sub["mean dFR"] < 0)].bin.tolist()
        pos = sub[(sub[col] < 0.05) & (sub["mean dFR"] > 0)].bin.tolist()
        print(f"  {a}: significant negative bins {neg}; positive {pos}")
early_neg = {a: bool(((b7.area == a) & (b7.p_FDR_area < 0.05) & (b7["mean dFR"] < 0) & b7.bin.between(1.0099, 1.0201)).any()) for a in ("wS1", "wS2")}
late_pos = [a for a in g.AREAS if ((b7.area == a) & (b7.p_FDR_area < 0.05) & (b7["mean dFR"] > 0) & (b7.bin >= 1.0299)).any()]
print("\nwS1 and wS2 negative bin within 1.010-1.020 s:", early_neg)
print("Areas with significant positive bins from 1.030 s:", late_pos, f"({len(late_pos)} of 5)")
print(b7[b7.bin.between(1.0, 1.04)].pivot(index="bin", columns="area", values="mean dFR").round(2).to_string())
FDR p_FDR_area:
  A1: significant negative bins []; positive [1.07, 1.08, 1.085, 1.1]
  wS1: significant negative bins [0.965, 0.97, 1.015, 1.02]; positive [1.04, 1.045, 1.05, 1.055, 1.06, 1.07, 1.08, 1.085, 1.09]
  wS2: significant negative bins [0.96, 0.965, 1.01, 1.015, 1.02, 1.025]; positive [1.04, 1.045, 1.05, 1.055, 1.06, 1.065, 1.07, 1.075, 1.08, 1.085, 1.09, 1.095, 1.1]
  wM2: significant negative bins [0.965, 0.99]; positive [0.985, 1.035, 1.04, 1.045, 1.05, 1.055, 1.06, 1.065, 1.07, 1.075, 1.08, 1.085, 1.09, 1.095, 1.1]
  ALM: significant negative bins []; positive [1.03, 1.035, 1.04, 1.045, 1.05, 1.055, 1.06, 1.065, 1.07, 1.075, 1.08, 1.085, 1.09, 1.095, 1.1]
FDR p_FDR_all:
  A1: significant negative bins []; positive [1.065, 1.07, 1.075, 1.08, 1.085, 1.09, 1.095, 1.1]
  wS1: significant negative bins [0.965, 0.97, 1.015, 1.02]; positive [1.04, 1.045, 1.05, 1.055, 1.06, 1.07, 1.08, 1.085, 1.09]
  wS2: significant negative bins [0.965, 1.01, 1.015, 1.02, 1.025]; positive [1.04, 1.045, 1.05, 1.055, 1.06, 1.065, 1.07, 1.075, 1.08, 1.085, 1.09, 1.095, 1.1]
  wM2: significant negative bins [0.965, 0.99]; positive [0.985, 1.035, 1.04, 1.045, 1.05, 1.055, 1.06, 1.065, 1.07, 1.075, 1.08, 1.085, 1.09, 1.095, 1.1]
  ALM: significant negative bins []; positive [1.03, 1.035, 1.04, 1.045, 1.05, 1.055, 1.06, 1.065, 1.07, 1.075, 1.08, 1.085, 1.09, 1.095, 1.1]

wS1 and wS2 negative bin within 1.010-1.020 s: {'wS1': True, 'wS2': True}
Areas with significant positive bins from 1.030 s: ['A1', 'wS1', 'wS2', 'wM2', 'ALM'] (5 of 5)
area     A1   ALM   wM2   wS1   wS2
bin                                
1.000  0.01 -0.07 -0.00 -0.20 -0.09
1.005  0.23  0.12  0.05 -0.05  0.06
1.010  0.27 -0.06 -0.12 -0.25 -0.29
1.015  1.13  0.07  0.35 -1.04 -1.02
1.020  0.40  0.33  0.04 -0.78 -0.75
1.025  0.33  0.40  0.20 -0.01 -0.31
1.030 -0.21  0.97  0.36 -0.02  0.35
1.035  0.54  1.31  1.01  0.44  0.48
1.040  0.17  1.61  1.29  0.80  0.87

Result: reproduced. With FDR within each area, wS1 has significant negative Hit minus CR bins at 1.015 and 1.020 s and wS2 at 1.010 to 1.025 s, and all five areas have significant positive bins from 1.030 s on (ALM from 1.030, wM2 from 1.035, wS1 and wS2 from 1.040, A1 from 1.065 s). The code's FDR over all areas and bins gives the same bins for wS1, wM2 and ALM, and for wS2 the same bins after the stimulus; wS2 also has negative bins before the stimulus (0.96 and 0.965 s) with FDR within the area, and the one at 0.96 s is not significant with the code's FDR.

fig7c-no-whisker-cd-change¶

Activity projected on a whisker coding direction, defined from the first 30 ms of No-tone Whisker responses, shows no significant difference between Go-tone and Nogo-tone contexts.

As the criterion (code, Coding_direction_5ms.m and Ghaderi2025_Figure7_c_StimCD.m), with 30% training trials (code). The 5 ms counts kept by the helper start at 0.95 s, so the -1 to 0 s baseline of the whisker direction and the 0.8 to 1.0 s window of the context direction are taken from the 10 ms counts divided by 2 (the mean count per 5 ms); the context window is then [0.79, 1.0) in place of [0.795, 1.0). The projection is the 5 ms bin labelled 1.030 s.

In [33]:
B10 = g.bin_index(-1.0, 0.0)
I_WHISK = np.arange(9, 16)      # 5 ms bins labelled 1.000 to 1.030 s
I_30 = 15                       # bin labelled 1.030 s
GROUPS8 = [("Go lick", 1, True), ("Go no lick", 1, False), ("Nogo lick", 3, True), ("Nogo no lick", 3, False),
           ("No-tone lick", 5, True), ("No-tone no lick", 5, False)]


def coding_directions_5ms(frac, rule, rng):
    rows7, rows8 = [], []
    for a in g.AREAS:
        for s, cols in g.area_sessions(S, a, 5):
            q = g.quiet_mask(s, rule)
            X10 = s["c10"][:, :, cols].astype(float)
            X5 = s["c5"][:, :, cols].astype(float)
            hit = np.flatnonzero(g.trial_mask(s, 1, True) & q)
            cr = np.flatnonzero(g.trial_mask(s, 3, False) & q)
            wt = np.flatnonzero(g.trial_mask(s, 5, False) & q)
            h_tr, h_te = g.split_train(hit, frac, rng)
            c_tr, c_te = g.split_train(cr, frac, rng)
            w_tr, w_te = g.split_train(wt, frac, rng)
            if min(len(h_tr), len(c_tr), len(w_tr)) == 0:
                continue
            cdc = (X10[h_tr][:, WCTX].mean(axis=(0, 1)) - X10[c_tr][:, WCTX].mean(axis=(0, 1))) / 2
            cdc /= np.linalg.norm(cdc)
            cdw = X5[w_tr][:, I_WHISK].mean(axis=(0, 1)) - X10[w_tr][:, B10].mean(axis=(0, 1)) / 2
            cdw /= np.linalg.norm(cdw)
            cdw = cdw - (cdw @ cdc) * cdc
            cdw /= np.linalg.norm(cdw)
            pr = lambda t, cd: (X5[t][:, I_30] @ cd).mean() if len(t) else np.nan
            rows7.append({"area": a, "session": s["session"], "Hit": pr(h_te, cdw), "Nogo CR": pr(c_te, cdw)})
            train = set(h_tr) | set(c_tr)
            row = {"area": a, "session": s["session"]}
            for name, t_, l_ in GROUPS8:
                ids = np.array([i for i in np.flatnonzero(g.trial_mask(s, t_, l_) & q) if i not in train], int)
                row[name] = pr(ids, cdc)
            rows8.append(row)
    return pd.DataFrame(rows7), pd.DataFrame(rows8)


cd7, cd8 = {}, {}
for key, (frac, rule, seed) in {"main": (0.3, "median", 11), "20% training": (0.2, "median", 11),
                                "code MAD (mean)": (0.3, "mean", 11), "seed 12": (0.3, "median", 12)}.items():
    cd7[key], cd8[key] = coding_directions_5ms(frac, rule, np.random.default_rng(seed))
for key, df in cd7.items():
    rows = []
    for a in g.AREAS:
        sub = df[df.area == a]
        H, p_, _ = g.kruskal_lsd([sub["Hit"], sub["Nogo CR"]])
        ok = sub["Hit"].notna() & sub["Nogo CR"].notna()
        rows.append({"area": a, "sessions": len(sub), "Hit": sub["Hit"].mean(), "Nogo CR": sub["Nogo CR"].mean(),
                     "diff": (sub["Hit"] - sub["Nogo CR"]).mean(), "KW p": p_,
                     "paired Wilcoxon p": stats.wilcoxon(sub.loc[ok, "Hit"], sub.loc[ok, "Nogo CR"]).pvalue})
    print(f"Whisker CD at 30 ms, {key}:")
    print(pd.DataFrame(rows).round(4).to_string(index=False))
Whisker CD at 30 ms, main:
area  sessions    Hit  Nogo CR    diff   KW p  paired Wilcoxon p
  A1        14 0.2841   0.3066 -0.0225 0.8183             0.5416
 wS1        24 0.7128   0.7102  0.0026 0.9015             0.8334
 wS2        19 0.7760   0.7317  0.0443 0.6721             0.0955
 wM2        18 0.5303   0.5291  0.0011 0.9748             0.5798
 ALM        16 0.2887   0.2276  0.0612 0.3089             0.1591
Whisker CD at 30 ms, 20% training:
area  sessions    Hit  Nogo CR    diff   KW p  paired Wilcoxon p
  A1        14 0.2617   0.2766 -0.0150 0.7477             0.6257
 wS1        24 0.6981   0.6846  0.0135 0.7259             0.4223
 wS2        19 0.7663   0.7149  0.0514 0.6300             0.0289
 wM2        18 0.4988   0.4931  0.0057 0.8247             0.9661
 ALM        16 0.2454   0.1826  0.0628 0.1871             0.0739
Whisker CD at 30 ms, code MAD (mean):
area  sessions    Hit  Nogo CR    diff   KW p  paired Wilcoxon p
  A1        14 0.2905   0.3269 -0.0364 0.4907             0.0419
 wS1        24 0.7337   0.7031  0.0306 0.8366             0.2522
 wS2        19 0.7481   0.7180  0.0301 0.7592             0.0446
 wM2        18 0.5080   0.5294 -0.0214 1.0000             0.4171
 ALM        16 0.2765   0.2307  0.0459 0.4975             0.2312
Whisker CD at 30 ms, seed 12:
area  sessions    Hit  Nogo CR    diff   KW p  paired Wilcoxon p
  A1        14 0.2574   0.2883 -0.0309 0.6459             0.2166
 wS1        24 0.7043   0.7041  0.0002 0.9835             0.9664
 wS2        19 0.7658   0.7271  0.0387 0.6935             0.1134
 wM2        18 0.4992   0.5091 -0.0099 0.9495             0.8317
 ALM        16 0.2452   0.2096  0.0356 0.5465             0.1928

Result: reproduced. The Kruskal-Wallis test finds no difference between Hit and Nogo CR projections on the whisker direction in any area (p 0.31 to 0.97), as the claim of absence requires, and the variants agree (smallest p 0.19). The paired Wilcoxon test, not the paper's, gives p 0.096 in wS2 (Hit higher by 0.044) and p above 0.15 elsewhere; in the variants it falls below 0.05 in wS2 (20% training, code's MAD) and A1 (code's MAD).

fig8a-wm2-lick-divergence¶

In the first 30 ms after the whisker stimulus, only wM2 activity diverges into separate states for lick and no-lick trials, mainly along the context coding direction, and at 30 ms distinguishes lick from no-lick trials both in correct Go-tone and error Nogo-tone conditions; ALM shows a weaker effect and A1, wS1 and wS2 none.

Held-out quiet trials projected on CD context (computed above, 30% training as the 5 ms code), the value in the bin labelled 1.030 s, six groups; Kruskal-Wallis then Fisher LSD on the ranks.

In [34]:
for key, df in cd8.items():
    rows = []
    for a in g.AREAS:
        sub = df[df.area == a]
        H, p_, comps = g.kruskal_lsd([sub[name] for name, *_ in GROUPS8])
        rows.append({"area": a, "sessions": len(sub), **{name: sub[name].mean() for name, *_ in GROUPS8},
                     "KW p": p_, "Go lick-nolick p": comps[(0, 1)][1], "Nogo lick-nolick p": comps[(2, 3)][1],
                     "No-tone lick-nolick p": comps[(4, 5)][1],
                     "Nogo lick vs No-tone no lick p (Supp. Fig. 17)": comps[(2, 5)][1],
                     "Nogo lick vs No-tone no lick sign": "+" if comps[(2, 5)][0] > 0 else "-"})
    res8 = pd.DataFrame(rows)
    print(f"Context CD at 30 ms, {key}:")
    print(res8.round(4).to_string(index=False))
    print("  area-sessions (all areas) with trials in each group:", {name: int(df[name].notna().sum()) for name, *_ in GROUPS8}, "\n")
Context CD at 30 ms, main:
area  sessions  Go lick  Go no lick  Nogo lick  Nogo no lick  No-tone lick  No-tone no lick   KW p  Go lick-nolick p  Nogo lick-nolick p  No-tone lick-nolick p  Nogo lick vs No-tone no lick p (Supp. Fig. 17) Nogo lick vs No-tone no lick sign
  A1        14   0.1120      0.1379     0.0948        0.0965        0.0473           0.0990 0.6223            0.5359              0.5632                 0.4003                                          0.5683                                 -
 wS1        24   0.1642      0.1568     0.1386        0.1667        0.1436           0.1777 0.9736            0.4645              0.7769                 0.6460                                          0.7354                                 -
 wS2        19   0.2567      0.2212     0.3015        0.2167        0.2330           0.2254 0.9518            0.5758              0.4070                 0.9145                                          0.4741                                 +
 wM2        18   0.5528      0.2859     0.3530        0.2607        0.2932           0.2553 0.0048            0.0041              0.2760                 0.0906                                          0.2232                                 +
 ALM        16   0.4557      0.1596     0.2046        0.0827        0.1606           0.1085 0.0000            0.0008              0.0284                 0.2158                                          0.0711                                 +
  area-sessions (all areas) with trials in each group: {'Go lick': 91, 'Go no lick': 89, 'Nogo lick': 81, 'Nogo no lick': 91, 'No-tone lick': 89, 'No-tone no lick': 91} 

Context CD at 30 ms, 20% training:
area  sessions  Go lick  Go no lick  Nogo lick  Nogo no lick  No-tone lick  No-tone no lick   KW p  Go lick-nolick p  Nogo lick-nolick p  No-tone lick-nolick p  Nogo lick vs No-tone no lick p (Supp. Fig. 17) Nogo lick vs No-tone no lick sign
  A1        14   0.0912      0.1278     0.0933        0.0897        0.0763           0.0893 0.8631            0.3135              0.6238                 0.7934                                          0.6565                                 -
 wS1        24   0.1490      0.1401     0.1294        0.1618        0.1005           0.1668 0.8255            0.3944              0.6540                 0.2733                                          0.4963                                 -
 wS2        19   0.2640      0.2372     0.3233        0.2118        0.2539           0.2234 0.8222            0.5999              0.2064                 0.6331                                          0.2752                                 +
 wM2        18   0.5508      0.2661     0.3241        0.2494        0.2836           0.2415 0.0020            0.0019              0.3618                 0.0861                                          0.3185                                 +
 ALM        16   0.4526      0.1602     0.2218        0.1002        0.1518           0.1219 0.0000            0.0006              0.0336                 0.6094                                          0.0963                                 +
  area-sessions (all areas) with trials in each group: {'Go lick': 91, 'Go no lick': 89, 'Nogo lick': 81, 'Nogo no lick': 91, 'No-tone lick': 89, 'No-tone no lick': 91} 

Context CD at 30 ms, code MAD (mean):
area  sessions  Go lick  Go no lick  Nogo lick  Nogo no lick  No-tone lick  No-tone no lick   KW p  Go lick-nolick p  Nogo lick-nolick p  No-tone lick-nolick p  Nogo lick vs No-tone no lick p (Supp. Fig. 17) Nogo lick vs No-tone no lick sign
  A1        14   0.0964      0.0776     0.0819        0.0681        0.0507           0.0996 0.7361            0.7777              0.5955                 0.3081                                          0.1438                                 -
 wS1        24   0.2168      0.1947     0.1361        0.1951        0.1798           0.1845 0.8832            0.5438              0.4711                 0.8360                                          0.4462                                 -
 wS2        19   0.2724      0.2526     0.2975        0.2550        0.2153           0.2589 0.9981            0.7030              0.8585                 0.8330                                          0.9133                                 +
 wM2        18   0.6363      0.3550     0.4736        0.3327        0.4376           0.3287 0.0015            0.0011              0.0835                 0.0864                                          0.0864                                 +
 ALM        16   0.4876      0.1728     0.2349        0.1018        0.1688           0.1311 0.0000            0.0003              0.0854                 0.6170                                          0.1989                                 +
  area-sessions (all areas) with trials in each group: {'Go lick': 91, 'Go no lick': 91, 'Nogo lick': 86, 'Nogo no lick': 91, 'No-tone lick': 89, 'No-tone no lick': 91} 

Context CD at 30 ms, seed 12:
area  sessions  Go lick  Go no lick  Nogo lick  Nogo no lick  No-tone lick  No-tone no lick   KW p  Go lick-nolick p  Nogo lick-nolick p  No-tone lick-nolick p  Nogo lick vs No-tone no lick p (Supp. Fig. 17) Nogo lick vs No-tone no lick sign
  A1        14   0.0794      0.0966     0.1066        0.0680        0.0660           0.0932 0.9863            0.8057              0.7614                 0.5204                                          0.8658                                 -
 wS1        24   0.2060      0.1965     0.1153        0.1984        0.1691           0.1920 0.9371            0.7371              0.4309                 0.8074                                          0.5084                                 -
 wS2        19   0.1923      0.1628     0.2012        0.1742        0.1871           0.1717 0.9954            0.5793              0.7841                 0.9945                                          0.9035                                 +
 wM2        18   0.6320      0.3206     0.3848        0.3007        0.3989           0.2962 0.0023            0.0016              0.3336                 0.1042                                          0.3668                                 +
 ALM        16   0.4797      0.1917     0.1870        0.0974        0.1908           0.1111 0.0000            0.0025              0.1137                 0.1815                                          0.2149                                 +
  area-sessions (all areas) with trials in each group: {'Go lick': 91, 'Go no lick': 89, 'Nogo lick': 81, 'Nogo no lick': 91, 'No-tone lick': 89, 'No-tone no lick': 91} 

Result: partially reproduced. In wM2 the six groups differ (Kruskal-Wallis p 0.0048) and Go-tone lick trials project above Go-tone no-lick trials (LSD p 0.0041), but Nogo-tone lick (false alarm) trials are not significantly above Nogo-tone no-lick trials (p 0.28): wM2 holds for one of the two contexts. A1, wS1 and wS2 show no significant lick against no-lick comparison (all p 0.40 or more). ALM gives Kruskal-Wallis p below 0.0001, Go-tone p 0.0008 and Nogo-tone p 0.028. The variants agree that the Nogo-tone comparison in wM2 is not significant (p 0.08 to 0.36). The legend of Supplementary Fig. 17 gives wM2's Nogo-tone result as "Nogo-tone Lick vs No tone no lick trials" (p 0.04); that pair, not the criterion's, gives p 0.22 in wM2 (variants 0.09 to 0.37), also not significant. Whether the criterion's pair is the paper's is asked of a reader.

fig8b-lick-coding-direction¶

At 30 ms after the whisker stimulus, activity along a lick coding direction defined from spontaneous licking separates lick from no-lick trials in wM2 for Go-tone, Nogo-tone (false alarm) and No-tone trials, in ALM only for correct trials, and not in A1, wS1 or wS2.

As the criterion (code, Coding_direction_SpontLick.m and Ghaderi2025_Figure8_b_SpontLick_CD_LickvsNolick.m). The detected lick times and the lick mask come from data_helpers/Lick_times.mat on the Zenodo record, which the dandiset does not hold; the jaw trace and video timestamps the rule also needs are taken from the dandiset, and the file's copies are checked against them. Spontaneous licks: outside 0 to 6 s of every trial start, in a lick-mask bout longer than 0.5 s, and with the mean jaw trace over 0 to 0.1 s after the lick above 3 times its mean over -1 to 0 s; area-sessions (at least 5 neurons) with fewer than 2 such licks are dropped. CD lick per area-session: the mean over licks of each neuron's mean 5 ms count over 0.2 to 0.5 s after the lick minus that over -1 to -0.5 s, unit length. Quiet completed trials are projected (5 ms bin labelled 1.030 s) and averaged per group; a group with fewer than 2 trials in a session is left out (code, min_num_trials = 2). Kruskal-Wallis over the six groups, then Fisher LSD. No trial is used to train CD lick, so all trials are projected.

In [35]:
# What the dataset holds of licking: the contents of each session's behaviour module (verifier's
# question; the lick times come from Lick_times.mat because no detected lick times are here).
def behaviour_module(asset):
    path, _, aid = asset
    f = g.open_nwb(aid)
    pb = f["processing/behavior"]
    out = {"session": path.split("/")[-1][:33],
           "BehavioralEvents": ", ".join(sorted(pb["BehavioralEvents"].keys())) if "BehavioralEvents" in pb else "",
           "BehavioralTimeSeries": ", ".join(sorted(pb["BehavioralTimeSeries"].keys())) if "BehavioralTimeSeries" in pb else ""}
    f.close()
    return out


with ThreadPoolExecutor(8) as ex:
    bmod = pd.DataFrame(list(ex.map(behaviour_module, g.ephys_assets())))
print("Contents of processing/behavior over the", len(bmod), "sessions (distinct combinations, with session counts):")
print(bmod.groupby(["BehavioralEvents", "BehavioralTimeSeries"]).size().reset_index(name="sessions").to_string(index=False))

t0 = time.time()
LT, n_lick_entries, lick_mismatch = g.lick_times()
print(f"Lick_times.mat: {n_lick_entries} probe entries for {len(LT)} sessions, read in {time.time() - t0:.0f} s; "
      f"entries of one session that differ: {lick_mismatch}")
print("sessions of the dataset without an entry:", [s["session"] for s in S if s["session"] not in LT])


def spont_session(s):
    r = LT[s["session"]]
    ts, jaw = g.jaw_trace(s["path"])
    same = len(ts) == len(r["video_ts"]) and np.array_equal(ts, r["video_ts"])
    jaw_diff = float(np.nanmax(np.abs(jaw - r["jaw"]))) if same else np.nan
    same = same and bool(np.array_equal(np.isnan(jaw), np.isnan(r["jaw"])))
    sp, cnt = g.spontaneous_licks(r["lick_time"], r["lick_mask"], ts, jaw, s["trials"]["start_time"])
    return {"session": s["session"], "licks in file": len(r["lick_time"]), **cnt, "spontaneous": len(sp),
            "file timestamps and NaNs = dataset's": same, "largest jaw difference": jaw_diff, "mask frames = video frames": len(r["lick_mask"]) == len(ts)}, sp


with ThreadPoolExecutor(8) as ex:
    out = list(ex.map(spont_session, S))
SPONT = {r["session"]: sp for r, sp in out}
spont_tab = pd.DataFrame([r for r, _ in out])
print(spont_tab.to_string(index=False))
print("\nSessions with at least 2 spontaneous licks:", int((spont_tab.spontaneous >= 2).sum()), "of", len(spont_tab),
      "; all jaw traces and timestamps equal to the dataset's:", bool(spont_tab["file timestamps and NaNs = dataset's"].all()),
      "; largest jaw difference over sessions:", spont_tab["largest jaw difference"].max())
Contents of processing/behavior over the 35 sessions (distinct combinations, with session counts):
 BehavioralEvents                                                              BehavioralTimeSeries  sessions
Valve_OpeningTime C2Whisker_Angle, Jaw_Coordinate, Piezo_lick_trace, Snout_Angle, Tongue_Coordinate        35
Lick_times.mat: 110 probe entries for 35 sessions, read in 90 s; entries of one session that differ: []
sessions of the dataset without an entry: []
                      session  licks in file  outside trials  removed by bout length  removed by jaw rule  spontaneous  file timestamps and NaNs = dataset's  largest jaw difference  mask frames = video frames
sub-PG019_ses-20200904T224847            131              27                       5                    9           13                                  True            0.000000e+00                        True
sub-PG019_ses-20200906T175456            264              85                      14                   32           39                                  True            0.000000e+00                        True
sub-PG027_ses-20210403T115220            176              49                       0                   42            7                                  True            0.000000e+00                        True
sub-PG027_ses-20210404T111739            110              23                       0                   22            1                                  True            0.000000e+00                        True
sub-PG028_ses-20210318T163504            254              60                       0                   52            8                                  True            0.000000e+00                        True
sub-PG028_ses-20210319T135422            370              86                       8                   73            5                                  True            0.000000e+00                        True
sub-PG030_ses-20210405T163808            161              10                       2                    5            3                                  True            0.000000e+00                        True
sub-PG030_ses-20210406T164509            131              14                       1                   12            1                                  True            0.000000e+00                        True
sub-PG030_ses-20210407T211250            177              25                       5                   15            5                                  True            0.000000e+00                        True
sub-PG030_ses-20210408T223046             79              20                       0                   20            0                                  True            0.000000e+00                        True
sub-PG030_ses-20210410T012800             77              15                       0                   14            1                                  True            0.000000e+00                        True
sub-PG032_ses-20210711T175822            163               4                       2                    2            0                                  True            0.000000e+00                        True
sub-PG032_ses-20210712T185829            196              30                      15                    8            7                                  True            0.000000e+00                        True
sub-PG032_ses-20210715T223447            227              34                      16                   13            5                                  True            0.000000e+00                        True
sub-PG038_ses-20210316T152753            161              27                       0                   20            7                                  True            0.000000e+00                        True
sub-PG038_ses-20210317T180556            111              28                       0                   26            2                                  True            0.000000e+00                        True
sub-PG061_ses-20220211T222307            285              49                       6                   33           10                                  True            0.000000e+00                        True
sub-PG061_ses-20220212T233813            180              36                       0                   25           11                                  True            0.000000e+00                        True
sub-PG062_ses-20220206T200225             87              19                       3                   13            3                                  True            0.000000e+00                        True
sub-PG062_ses-20220207T213136             76               6                       0                    6            0                                  True            2.842171e-14                        True
sub-PG064_ses-20220209T222403            187              27                      12                   14            1                                  True            1.421085e-14                        True
sub-PG064_ses-20220210T183214             75               7                       3                    3            1                                  True            0.000000e+00                        True
sub-PG076_ses-20220502T140636            291              62                       7                   46            9                                  True            0.000000e+00                        True
sub-PG082_ses-20221113T145317            162               7                       4                    3            0                                  True            0.000000e+00                        True
sub-PG082_ses-20221114T163239             70               8                       3                    4            1                                  True            0.000000e+00                        True
sub-PG082_ses-20221120T182616            144               8                       1                    7            0                                  True            0.000000e+00                        True
sub-PG083_ses-20221125T180851            185              20                       2                   15            3                                  True            0.000000e+00                        True
sub-PG083_ses-20221129T153120            127              10                       1                    9            0                                  True            0.000000e+00                        True
sub-PG083_ses-20221130T230127            227              27                       5                   20            2                                  True            0.000000e+00                        True
sub-PG084_ses-20221206T162236            150              14                       5                    3            6                                  True            0.000000e+00                        True
sub-PG084_ses-20221207T192711            210               7                       2                    3            2                                  True            0.000000e+00                        True
sub-PG084_ses-20221208T224009            162              19                       0                   14            5                                  True            0.000000e+00                        True
sub-PG085_ses-20221213T195032            186              47                      11                   20           16                                  True            0.000000e+00                        True
sub-PG085_ses-20221214T211712            195              44                       9                   20           15                                  True            0.000000e+00                        True
sub-PG085_ses-20221215T222439            174              34                       9                   12           13                                  True            0.000000e+00                        True

Sessions with at least 2 spontaneous licks: 23 of 35 ; all jaw traces and timestamps equal to the dataset's: True ; largest jaw difference over sessions: 2.842170943040401e-14
In [36]:
GROUPS8B = [("Go lick", 1, True), ("Nogo lick", 3, True), ("No-tone lick", 5, True),
            ("Go no lick", 1, False), ("Nogo no lick", 3, False), ("No-tone no lick", 5, False)]
W_AFTER, W_BEFORE = (0.2, 0.5), (-1.0, -0.5)     # code, params.Win_lick and params.Win_nolick
W_S18 = g.bin_index(1.2, 1.4)                     # Supplementary Fig. 18 window, from the 10 ms counts


def lick_cd_session(s):
    """CD lick of each area of a session (unit length is applied later)."""
    sp = SPONT[s["session"]]
    cols = {a: g.area_columns(s, a) for a in g.AREAS}
    cols = {a: c for a, c in cols.items() if len(c) >= 5}
    if not cols or len(sp) < 2:
        return s["session"], {}
    allc = np.concatenate(list(cols.values()))
    C = g.event_counts(s["path"], s["keep"][allc], sp, (W_AFTER, W_BEFORE))
    pos = {c: i for i, c in enumerate(allc)}
    # mean 5 ms count per bin: 60 bins in 0.2 to 0.5 s, 100 in -1 to -0.5 s
    return s["session"], {a: C[0][:, [pos[c] for c in cl]].mean(axis=0) / 60 - C[1][:, [pos[c] for c in cl]].mean(axis=0) / 100
                          for a, cl in cols.items()}


t0 = time.time()
with ThreadPoolExecutor(8) as ex:
    CDL = dict(ex.map(lick_cd_session, S))
print(f"spike counts around spontaneous licks: {time.time() - t0:.0f} s")


def lick_projections(rule, min_trials=2):
    rows, dropped = [], []
    for a in g.AREAS:
        for s, cols in g.area_sessions(S, a, 5):
            cd = CDL[s["session"]].get(a)
            if cd is None or np.linalg.norm(cd) == 0:
                dropped.append((a, s["session"]))
                continue
            cd = cd / np.linalg.norm(cd)
            q = g.quiet_mask(s, rule)
            p30 = s["c5"][:, I_30, cols].astype(float) @ cd
            plate = (s["c10"][:, W_S18][:, :, cols].astype(float) @ cd).mean(axis=1) / 2   # 10 ms counts halved
            row = {"area": a, "session": s["session"], "subject": s["subject"], "spontaneous licks": len(SPONT[s["session"]])}
            for name, t_, l_ in GROUPS8B:
                m = g.trial_mask(s, t_, l_) & q
                row[name] = p30[m].mean() if m.sum() >= min_trials else np.nan
                row[name + " (1.2-1.4 s)"] = plate[m].mean() if m.sum() >= min_trials else np.nan
                row["n " + name] = int(m.sum())
            rows.append(row)
    return pd.DataFrame(rows), dropped


def lick_tests(df, suffix=""):
    rows = []
    for a in g.AREAS:
        sub = df[df.area == a]
        H, p_, comps = g.kruskal_lsd([sub[name + suffix] for name, *_ in GROUPS8B])
        row = {"area": a, "sessions": len(sub), "KW H": H, "KW p": p_}
        for i, ctx in enumerate(("Go", "Nogo", "No-tone")):
            for j, ctx2 in zip(range(3, 6), ("Go", "Nogo", "No-tone")):
                d, pp = comps[(i, j)]
                row[f"{ctx} lick vs {ctx2} no lick p"] = pp
                row[f"{ctx} lick vs {ctx2} no lick sign"] = "+" if d > 0 else "-"
        rows.append(row)
    return pd.DataFrame(rows)


LP, lick_tab = {}, {}
for rule in ("median", "mean"):
    LP[rule], dropped8b = lick_projections(rule)
    lick_tab[rule] = lick_tests(LP[rule])
    print(f"\nQuiet rule MAD = {rule}; area-sessions dropped for fewer than 2 spontaneous licks: {len(dropped8b)}")
    print("Mean projection at 1.030 s by group:")
    print(LP[rule].groupby("area")[[n for n, *_ in GROUPS8B]].mean().loc[g.AREAS].round(3).to_string())
    print("Range of the per-session group means:", round(float(np.nanmin(LP[rule][[n for n, *_ in GROUPS8B]].values)), 3),
          "to", round(float(np.nanmax(LP[rule][[n for n, *_ in GROUPS8B]].values)), 3))
    print(lick_tab[rule].round(4).T.to_string())


def within(tab, area, ctx):
    r = tab.set_index("area").loc[area]
    return r[f"{ctx} lick vs {ctx} no lick p"] < 0.05 and r[f"{ctx} lick vs {ctx} no lick sign"] == "+"


for rule in ("median", "mean"):
    t_ = lick_tab[rule]
    wm2 = [within(t_, "wM2", c) for c in ("Go", "Nogo", "No-tone")]
    alm = (within(t_, "ALM", "Go"), within(t_, "ALM", "Nogo"))
    sens = {a: [c for c in ("Go", "Nogo", "No-tone")
                if t_.set_index("area").loc[a, f"{c} lick vs {c} no lick p"] < 0.05] for a in ("A1", "wS1", "wS2")}
    sens_all = {a: int(sum(t_.set_index("area").loc[a, f"{c} lick vs {c2} no lick p"] < 0.05
                           for c in ("Go", "Nogo", "No-tone") for c2 in ("Go", "Nogo", "No-tone"))) for a in ("A1", "wS1", "wS2")}
    print(f"\nMAD = {rule}: wM2 KW p < 0.05: {bool(t_.set_index('area').loc['wM2', 'KW p'] < 0.05)}; "
          f"wM2 lick above no lick (Go, Nogo, No-tone): {wm2}; ALM Go significant {alm[0]}, Nogo significant {alm[1]}; "
          f"A1, wS1, wS2 contexts with a significant lick vs no lick comparison: {sens}; "
          f"of all 9 lick vs no-lick pairs: {sens_all}")
print("\nwM2 sessions per group (median MAD):", LP["median"][LP["median"].area == "wM2"][[n for n, *_ in GROUPS8B]].notna().sum().to_dict())
print("wM2 and ALM area-sessions per mouse:", LP["median"][LP["median"].area.isin(["wM2", "ALM"])].groupby(["area", "subject"]).size().to_dict())
spike counts around spontaneous licks: 61 s
Quiet rule MAD = median; area-sessions dropped for fewer than 2 spontaneous licks: 28
Mean projection at 1.030 s by group:
      Go lick  Nogo lick  No-tone lick  Go no lick  Nogo no lick  No-tone no lick
area                                                                             
A1      0.051      0.037         0.139       0.061         0.033            0.034
wS1     0.429      0.340         0.363       0.367         0.417            0.425
wS2     0.330      0.367         0.339       0.318         0.301            0.302
wM2     0.486      0.494         0.507       0.347         0.317            0.333
ALM     0.505      0.306         0.334       0.290         0.246            0.273
Range of the per-session group means: -0.422 to 1.285
                                           0       1       2        3       4
area                                      A1     wS1     wS2      wM2     ALM
sessions                                   9      16      16       12      10
KW H                                  1.4241  0.6446    0.16  17.5164  8.0202
KW p                                  0.9217  0.9859  0.9995   0.0036  0.1551
Go lick vs Go no lick p               0.7221  0.5964  0.8657   0.0445  0.0419
Go lick vs Go no lick sign                 -       +       +        +       +
Go lick vs Nogo no lick p             0.8971  0.9262  0.7711   0.0128  0.0105
Go lick vs Nogo no lick sign               +       +       +        +       +
Go lick vs No-tone no lick p          0.9871  0.8065  0.7814   0.0199  0.0301
Go lick vs No-tone no lick sign            +       +       +        +       +
Nogo lick vs Go no lick p             0.7904  0.8895  0.8727   0.0224   0.801
Nogo lick vs Go no lick sign               -       -       +        +       +
Nogo lick vs Nogo no lick p           0.8509  0.5748  0.7829   0.0064  0.4452
Nogo lick vs Nogo no lick sign             +       -       +        +       +
Nogo lick vs No-tone no lick p        0.9346  0.6789  0.7928   0.0099  0.7016
Nogo lick vs No-tone no lick sign          +       -       +        +       +
No-tone lick vs Go no lick p          0.5553  0.9185  0.9642   0.0324  0.5828
No-tone lick vs Go no lick sign            +       +       -        +       +
No-tone lick vs Nogo no lick p        0.2967  0.7491  0.9438   0.0098  0.2962
No-tone lick vs Nogo no lick sign          +       -       +        +       +
No-tone lick vs No-tone no lick p     0.3484  0.8629   0.954   0.0149  0.4988
No-tone lick vs No-tone no lick sign       +       -       +        +       +
Quiet rule MAD = mean; area-sessions dropped for fewer than 2 spontaneous licks: 28
Mean projection at 1.030 s by group:
      Go lick  Nogo lick  No-tone lick  Go no lick  Nogo no lick  No-tone no lick
area                                                                             
A1      0.056      0.016         0.102       0.076         0.029            0.036
wS1     0.442      0.328         0.378       0.380         0.406            0.424
wS2     0.328      0.332         0.291       0.331         0.303            0.302
wM2     0.489      0.507         0.505       0.333         0.314            0.335
ALM     0.513      0.328         0.309       0.281         0.239            0.268
Range of the per-session group means: -0.431 to 1.363
                                           0       1       2        3       4
area                                      A1     wS1     wS2      wM2     ALM
sessions                                   9      16      16       12      10
KW H                                  0.9062  0.4393  0.2657  20.3388  8.7963
KW p                                  0.9698  0.9942  0.9982   0.0011  0.1175
Go lick vs Go no lick p               0.7256  0.5997  0.9948   0.0127  0.0328
Go lick vs Go no lick sign                 -       +       -        +       +
Go lick vs Nogo no lick p             0.8547  0.8662  0.7682   0.0056   0.007
Go lick vs Nogo no lick sign               +       +       +        +       +
Go lick vs No-tone no lick p          0.8667  0.8307  0.7984   0.0155  0.0227
Go lick vs No-tone no lick sign            +       +       +        +       +
Nogo lick vs Go no lick p             0.5304  0.9793  0.9452   0.0039  0.6212
Nogo lick vs Go no lick sign               -       -       +        +       +
Nogo lick vs Nogo no lick p            0.913  0.7112   0.719   0.0017  0.2988
Nogo lick vs Nogo no lick sign             -       -       +        +       +
Nogo lick vs No-tone no lick p        0.9013  0.7441  0.7476   0.0049  0.5264
Nogo lick vs No-tone no lick sign          -       -       +        +       +
No-tone lick vs Go no lick p           0.927  0.8105    0.79   0.0349   0.735
No-tone lick vs Go no lick sign            +       +       -        +       +
No-tone lick vs Nogo no lick p        0.5315  0.9071   0.976   0.0174   0.369
No-tone lick vs Nogo no lick sign          +       -       +        +       +
No-tone lick vs No-tone no lick p     0.5415  0.9432  0.9931   0.0414    0.63
No-tone lick vs No-tone no lick sign       +       -       -        +       +

MAD = median: wM2 KW p < 0.05: True; wM2 lick above no lick (Go, Nogo, No-tone): [True, True, True]; ALM Go significant True, Nogo significant False; A1, wS1, wS2 contexts with a significant lick vs no lick comparison: {'A1': [], 'wS1': [], 'wS2': []}; of all 9 lick vs no-lick pairs: {'A1': 0, 'wS1': 0, 'wS2': 0}

MAD = mean: wM2 KW p < 0.05: True; wM2 lick above no lick (Go, Nogo, No-tone): [True, True, True]; ALM Go significant True, Nogo significant False; A1, wS1, wS2 contexts with a significant lick vs no lick comparison: {'A1': [], 'wS1': [], 'wS2': []}; of all 9 lick vs no-lick pairs: {'A1': 0, 'wS1': 0, 'wS2': 0}

wM2 sessions per group (median MAD): {'Go lick': 12, 'Nogo lick': 9, 'No-tone lick': 9, 'Go no lick': 12, 'Nogo no lick': 12, 'No-tone no lick': 12}
wM2 and ALM area-sessions per mouse: {('ALM', 'PG030'): 1, ('ALM', 'PG032'): 1, ('ALM', 'PG083'): 2, ('ALM', 'PG084'): 3, ('ALM', 'PG085'): 3, ('wM2', 'PG032'): 1, ('wM2', 'PG061'): 2, ('wM2', 'PG062'): 1, ('wM2', 'PG083'): 2, ('wM2', 'PG084'): 3, ('wM2', 'PG085'): 3}

Result: reproduced. Of the 35 sessions 23 have at least 2 spontaneous licks (the lick file's jaw trace and timestamps equal the dataset's), which leaves 12 wM2, 10 ALM, 9 A1, 16 wS1 and 16 wS2 area-sessions (the paper: 10 to 12 for wM2). In wM2 the six groups differ (Kruskal-Wallis p 0.0036) and each context's lick group is above its own no-lick group (LSD p 0.044 Go-tone, 0.0064 Nogo-tone, 0.015 No-tone; against the three no-lick groups p 0.0064 to 0.044, the paper 0.002 to 0.04). In ALM Go-tone lick trials are above Go-tone no-lick trials (p 0.042) and Nogo-tone lick trials are not (p 0.45), although ALM's Kruskal-Wallis test is not significant (p 0.155). A1, wS1 and wS2 have no significant lick against no-lick comparison (p 0.30 or more). The code's quiet rule gives the same pattern (wM2 Kruskal-Wallis p 0.0011; ALM Go-tone p 0.033, Nogo-tone p 0.30).

figs18-later-lick-coding¶

Later, at 0.2 to 0.4 s after the whisker stimulus, the lick coding direction separates lick from no-lick trials in ALM, wM2, wS2 and wS1, with the effect largest in ALM and ranked in that order.

The projections of fig8b-lick-coding-direction averaged over 1.2 to 1.4 s (code, Ghaderi2025_Sup_Figure18_SpontLick_CD_LickvsNolick_200mswindow.m), with the same Kruskal-Wallis and LSD tests. The 5 ms counts are kept only up to 1.10 s, so this window is taken from the 10 ms counts halved (bins labelled 1.20 to 1.40 s, [1.19, 1.40) in place of [1.195, 1.40)); a projection is linear, so this changes only the window edge. Effect size readings (criterion): (a) Cohen's d of the session-group means of the three lick groups against the three no-lick groups, (b) the Kruskal-Wallis statistic.

In [37]:
for rule in ("median", "mean"):
    df = LP[rule]
    t18 = lick_tests(df, " (1.2-1.4 s)")
    rows = []
    for a in g.AREAS:
        sub = df[df.area == a]
        lk = np.concatenate([sub[n + " (1.2-1.4 s)"].dropna().values for n, _, l in GROUPS8B if l])
        nl = np.concatenate([sub[n + " (1.2-1.4 s)"].dropna().values for n, _, l in GROUPS8B if not l])
        sp = np.sqrt(((len(lk) - 1) * lk.var(ddof=1) + (len(nl) - 1) * nl.var(ddof=1)) / (len(lk) + len(nl) - 2))
        r = t18.set_index("area").loc[a]
        n_sig_up = int(sum((r[f"{c} lick vs {c2} no lick p"] < 0.05) and r[f"{c} lick vs {c2} no lick sign"] == "+"
                           for c in ("Go", "Nogo", "No-tone") for c2 in ("Go", "Nogo", "No-tone")))
        rows.append({"area": a, "sessions": len(sub), "mean lick": lk.mean(), "mean no lick": nl.mean(),
                     "(a) Cohen's d": (lk.mean() - nl.mean()) / sp, "(b) KW H": r["KW H"], "KW p": r["KW p"],
                     "lick > no lick pairs significant (of 9)": n_sig_up,
                     "within-context significant (Go, Nogo, No-tone)": [within(t18, a, c) for c in ("Go", "Nogo", "No-tone")]})
    eff = pd.DataFrame(rows)
    print(f"Quiet rule MAD = {rule}, 1.2 to 1.4 s:")
    print(eff.round(4).to_string(index=False))
    eff["difference (not a criterion reading)"] = eff["mean lick"] - eff["mean no lick"]
    for col in ("(a) Cohen's d", "(b) KW H", "difference (not a criterion reading)"):
        print(f"  ranking by {col}: {eff.sort_values(col, ascending=False).area.tolist()}")
    four = eff.set_index("area").loc[["ALM", "wM2", "wS2", "wS1"]]
    print("  ALM, wM2, wS2 and wS1 each KW p < 0.05 with a lick group significantly above a no-lick group:",
          bool(((four["KW p"] < 0.05) & (four["lick > no lick pairs significant (of 9)"] > 0)).all()), "\n")
Quiet rule MAD = median, 1.2 to 1.4 s:
area  sessions  mean lick  mean no lick  (a) Cohen's d  (b) KW H   KW p  lick > no lick pairs significant (of 9) within-context significant (Go, Nogo, No-tone)
  A1         9     0.0964        0.0176         0.7508    5.1271 0.4006                                        0                          [False, False, False]
 wS1        16     0.1911        0.0834         0.9429   15.7554 0.0076                                        7                            [True, True, False]
 wS2        16     0.2835        0.1063         1.1551   27.3323 0.0000                                        9                             [True, True, True]
 wM2        12     0.5052        0.1569         3.7987   49.1984 0.0000                                        9                             [True, True, True]
 ALM        10     0.6559        0.1977         1.9531   24.4627 0.0002                                        9                             [True, True, True]
  ranking by (a) Cohen's d: ['wM2', 'ALM', 'wS2', 'wS1', 'A1']
  ranking by (b) KW H: ['wM2', 'wS2', 'ALM', 'wS1', 'A1']
  ranking by difference (not a criterion reading): ['ALM', 'wM2', 'wS2', 'wS1', 'A1']
  ALM, wM2, wS2 and wS1 each KW p < 0.05 with a lick group significantly above a no-lick group: True 

Quiet rule MAD = mean, 1.2 to 1.4 s:
area  sessions  mean lick  mean no lick  (a) Cohen's d  (b) KW H   KW p  lick > no lick pairs significant (of 9) within-context significant (Go, Nogo, No-tone)
  A1         9     0.0886        0.0153         0.6938    4.4315 0.4891                                        0                          [False, False, False]
 wS1        16     0.1938        0.0808         0.9721   17.1426 0.0042                                        9                             [True, True, True]
 wS2        16     0.2908        0.1051         1.2159   31.7602 0.0000                                        9                             [True, True, True]
 wM2        12     0.5109        0.1539         4.0183   52.2236 0.0000                                        9                             [True, True, True]
 ALM        10     0.6739        0.1913         2.0809   28.0637 0.0000                                        9                             [True, True, True]
  ranking by (a) Cohen's d: ['wM2', 'ALM', 'wS2', 'wS1', 'A1']
  ranking by (b) KW H: ['wM2', 'wS2', 'ALM', 'wS1', 'A1']
  ranking by difference (not a criterion reading): ['ALM', 'wM2', 'wS2', 'wS1', 'A1']
  ALM, wM2, wS2 and wS1 each KW p < 0.05 with a lick group significantly above a no-lick group: True 

Result: not reproduced. At 1.2 to 1.4 s ALM, wM2, wS2 and wS1 each give Kruskal-Wallis p < 0.05 (0.0002, below 0.0001, below 0.0001, 0.0076) with lick groups significantly above no-lick groups, as the statement says, and A1 does not (p 0.40). But under both effect-size readings the largest effect is in wM2, not ALM: Cohen's d wM2 3.80, ALM 1.95, wS2 1.16, wS1 0.94; Kruskal-Wallis statistic wM2 49.2, wS2 27.3, ALM 24.5, wS1 15.8. The readings agree on the largest area, so the claim is not blocked; it fails on its ranking. The plain difference of the mean projections, which is not one of the criterion's readings, ranks ALM (0.46), wM2 (0.35), wS2 (0.18) and wS1 (0.11) in the paper's order; the Supplementary Fig. 18 legend, which the claims file did not read, ranks the areas by "the projection amplitude in the lick coding direction ... largest for ALM, followed by wM2, wS2 and wS1 (in rank order), with A1 having the smallest and not significant difference", which reads as this difference. Whether the claims file's effect size misreads the paper is asked of a reader (questions/ghaderi-2026.yaml). The code's quiet rule gives the same rankings.

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
fig1c-lick-probabilities reproduced
fig1f-movement-latencies partially reproduced
quiet-trials-half partially reproduced
fig2-auditory-window reproduced
fig2-delay-window reproduced
fig2-whisker-window reproduced
fig2-wm2-vs-alm-auditory reproduced
fig2-other-trial-types not reproduced
units-recorded reproduced
fig3a-activity-maps reproduced
fig3b-delay-and-response-psth partially reproduced
fig3c-delay-modulation-wm2-alm partially reproduced
fig3d-wm2-infragranular-delay partially reproduced
cluster-label-link reproduced
fig4b-named-clusters blocked (methods underspecified)
fig5a-single-neuron-context partially reproduced
fig6a-pca-delay-states partially reproduced
fig6b-context-coding-direction reproduced
fig6c-temporal-correlation reproduced
fig7b-early-whisker-response reproduced
fig7c-no-whisker-cd-change reproduced
fig8a-wm2-lick-divergence partially reproduced
fig8b-lick-coding-direction reproduced
figs18-later-lick-coding not reproduced

How the analysis differs from the paper's. Quiet trials follow the Methods (median absolute deviation); the paper's code uses MATLAB's default mean absolute deviation, and with it the single-neuron fractions (Fig. 3c, 5a), the layer values (Fig. 3d) and the explained variances (Fig. 6a) come out at the paper's values, while with the Methods' rule they are lower. The 5 ms coding-direction analyses take their baseline and context window from the 10 ms counts. The lick coding direction uses the lick times and lick mask of the paper's Lick_times.mat with the dandiset's jaw trace, and its 1.2 to 1.4 s window comes from the 10 ms counts. Permutation and bootstrap seeds are fixed per section.

What was found about the dataset. The units, trials and unit counts per area are those of the paper; the optogenetic sessions per area are the paper's, but ALM inactivation comes from 7 mice where the Methods give 8; and the paper's cluster labels link one to one to the units. The genotype field of 12 optogenetic sessions (PG021, PG061) says C57BL/6JRj; one session has 11 trials of type 0; every session has at least one trial without video in its window, and two have many (243 and 29); several trial-table descriptions do not fit their columns; the area of a unit needs the CCF label list from the Zenodo record, which the dandiset does not hold.