Reproducing Rodgers and DeWeese (2014) from CRCNS pfc-1¶

Paper: Rodgers CC, DeWeese MR (2014). Neural correlates of task switching in prefrontal cortex and primary auditory cortex in a novel stimulus selection task for rodents. Neuron 82, 1157-1170, doi:10.1016/j.neuron.2014.04.031. The claims file (claims/crcns-pfc-1/) was written from the paper's full text with its Supplemental Information and checked against the paper's code (cxrodgers/Rodgers2014 at commit 390b608).

Data: CRCNS pfc-1 (doi:10.6080/K0W66HPJ), unversioned; the zip crcns_pfc-1_data.zip is streamed from the CRCNS bucket and its MD5 is checked against the pin in pfc1.py. The unit, session and figure tables come from the paper's code repository at commit 390b608.

Claim Tested or blocked
fig2a-above-chance tested
figs1a-go-better-than-nogo tested
fig2d-block-switch tested
iti-median tested
fig3c-pfc-rule-encoding tested
fig4c-a1-rule-encoding tested
a1-rule-encoding-not-audresp-dependent tested
rule-encoding-effect-size tested
fig3ab-pfc-example-units tested
fig4ab-a1-example-units tested
fig3d-pfc-interference tested
fig4d-a1-interference tested
figs2c-s3c-hold-by-trial-type tested
figs2f-s3f-bidirectional-vs-spont tested
fig5ab-single-unit-onset tested
fig5c-population-onset tested
fig5d-go-nogo tested
audresp-prevalence tested
figs5cd-evoked-strength tested
figs5e-latency tested
fig6cd-baseline-evoked-correlation tested
evoked-beyond-baseline-rare tested
fig6e-decoding tested
figs5fg-tuning-vs-rule tested
figs5hi-stimulus-pairs tested
figs2gh-s3gh-rt-mt tested
figs2i-head-angle tested
figs2kl-s3kl-fev tested
posture-equalized-sign tested
posture-equalized-magnitude tested
fig7-disruption-by-block tested
fig7c-disruption-nogo tested
figs1bc-catch tested
fig8-model tested
unit-table-link tested
In [1]:
import time
import warnings

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

import pfc1

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

check = pfc1.check_checksums()
print("checksums.md5 on the bucket:", check["sums"])
print(f"{pfc1.ZIP_NAME} MD5 still {pfc1.ZIP_MD5}:", check["zip_matches_pin"])

unit_db = pfc1.load_unit_db()
sessions_df = pfc1.load_sessions_df()
fig_index = pfc1.load_figure_index()
S = pfc1.load_all(unit_db)
print(f"loaded {len(S)} sessions of CRCNS {pfc1.DATASET_ID} ({pfc1.DATASET_VERSION}, doi:{pfc1.DATASET_DOI}) "
      f"in {time.time() - started:.0f} s")
checksums.md5 on the bucket: {'crcns_pfc-1_data.zip': 'a8bc7ed90568c298ec4d134d53354a67', 'docs/crcns_pfc-1_data_description.docx': '209855915114402f46edb0ade5181aea', 'docs/crcns_pfc-1_data_description.pdf': '8fc690426aea5abf553ee89878ca6a8b', 'filelist.txt': 'd488f167d61edcf823b08f8b71ee6ca0'}
crcns_pfc-1_data.zip MD5 still a8bc7ed90568c298ec4d134d53354a67: True
loaded 55 sessions of CRCNS pfc-1 (unversioned, doi:10.6080/K0W66HPJ) in 20 s

Data check¶

Every file of the zip, the sessions, the units of the code's unit table and the trial tables. Each check of the description against the values is stated under its output.

In [2]:
files = pfc1.list_files()
print(f"{len(files)} file members in the zip (resource forks under __MACOSX/ left out), "
      f"{files['size'].sum() / 1e9:.2f} GB uncompressed")
misc = files[files.name.str.contains("miscellaneous")]
print(misc.to_string(index=False))
paths = pfc1.session_paths()
print("\nSessions per rat:", paths.groupby("rat").size().to_dict(), "total", len(paths))
print("Sessions without a spike file in klusters0/:", paths.index[paths.kkp.isna()].tolist())
print("Sessions with a second spike file outside klusters0/:", paths.index[paths.kkp_extra.notna()].tolist())
print("Sessions in the data set and in the code's sessions_df.csv:",
      len(set(paths.index) & set(sessions_df.index)), "of", len(paths), "and", len(sessions_df))
176 file members in the zip (resource forks under __MACOSX/ left out), 2.49 GB uncompressed
                                                                                             name       size  compressed
                                crcns_pfc-1_data/miscellaneous/catch_trial_task/CR20B_trials_info      24970        3137
                                crcns_pfc-1_data/miscellaneous/catch_trial_task/CR21A_trials_info      42444        4905
                                    crcns_pfc-1_data/miscellaneous/model/simulation_params.pickle       6962        1783
                                            crcns_pfc-1_data/miscellaneous/model/simulation_resdf 1152000530    82772611
crcns_pfc-1_data/miscellaneous/vidtrack/CR17B_110803_001_behaving/CR17B_110803_001_behaving.pdict      94157       19656
crcns_pfc-1_data/miscellaneous/vidtrack/CR20B_120602_001_behaving/CR20B_120602_001_behaving.pdict     155751       30752
crcns_pfc-1_data/miscellaneous/vidtrack/CR24A_121022_001_behaving/CR24A_121022_001_behaving.pdict     216582       43970
                                                          crcns_pfc-1_data/miscellaneous/zap/TI_d    3346263      144718

Sessions per rat: {'CR12B': 14, 'CR17B': 9, 'CR20B': 9, 'CR21A': 9, 'CR24A': 12, 'YT6A': 2} total 55
Sessions without a spike file in klusters0/: ['CR20B_120613_001_behaving', 'CR21A_120502_003_behaving', 'CR21A_120506_003_behaving']
Sessions with a second spike file outside klusters0/: ['CR21A_120503_004_behaving', 'CR21A_120504_004_behaving']
Sessions in the data set and in the code's sessions_df.csv: 55 of 55 and 55
In [3]:
# The two duplicated spike files: are they the same spikes?
for sess, row in paths[paths.kkp_extra.notna()].iterrows():
    a = pfc1.load_old_pickle(pfc1.read_member(row.kkp))
    b = pfc1.load_old_pickle(pfc1.read_member(row.kkp_extra))
    print(f"{sess}: klusters0 file {a.shape} columns {list(a.columns)}, extra file {b.shape} columns {list(b.columns)}")
    print("   units:", sorted(a.unit.unique().astype(int)) == sorted(b.unit.unique().astype(int)),
          "; groups in klusters0 file", sorted(a.group.unique().astype(int)), "extra file", sorted(b.group.unique().astype(int)))
    b = b.rename(columns={"spike_time": "time"})
    for col in ["group", "time", "unit"]:
        x, y = a[col].to_numpy(float), b[col].to_numpy(float)
        print(f"   {col}: equal {np.array_equal(x, y)}; equal after sorting {np.array_equal(np.sort(x), np.sort(y))}; "
              f"max abs difference after sorting {np.abs(np.sort(x) - np.sort(y)).max():.3g}")
CR21A_120503_004_behaving: klusters0 file (1251128, 3) columns ['group', 'time', 'unit'], extra file (1251128, 3) columns ['group', 'spike_time', 'unit']
   units: False ; groups in klusters0 file [np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5), np.int64(6), np.int64(7), np.int64(8)] extra file [np.int64(0), np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5), np.int64(6), np.int64(7)]
   group: equal False; equal after sorting False; max abs difference after sorting 1
   time: equal False; equal after sorting True; max abs difference after sorting 0
   unit: equal False; equal after sorting False; max abs difference after sorting 122
CR21A_120504_004_behaving: klusters0 file (884504, 3) columns ['group', 'time', 'unit'], extra file (884504, 3) columns ['group', 'spike_time', 'unit']
   units: False ; groups in klusters0 file [np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5), np.int64(6), np.int64(7), np.int64(8)] extra file [np.int64(0), np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5), np.int64(6), np.int64(7)]
   group: equal False; equal after sorting False; max abs difference after sorting 1
   time: equal False; equal after sorting True; max abs difference after sorting 0
   unit: equal False; equal after sorting False; max abs difference after sorting 117

The descriptor says each session folder holds one spike file in klusters0/, and that the folder is empty when no units were recorded. Three sessions (CR20B_120613, CR21A_120502, CR21A_120506) have only a README.txt there. Two CR21A sessions also hold a second copy of their spike file at the session level; the output above says whether the copies hold the same spikes. Only the klusters0/ file is read. The descriptor lists miscellaneous/catch_trial_task with one file per rat, which is there.

In [4]:
inc = unit_db[unit_db.include]
print("unit_db.csv rows:", len(unit_db), "; include True:", len(inc))
print(pd.crosstab(inc.ratname, inc.region, margins=True).to_string())
# region rule of the descriptor: CR12B and CR17B all A1; otherwise unit < 500 mPFC, > 500 A1
rule = np.where(inc.ratname.isin(["CR12B", "CR17B"]), "A1", np.where(inc.unum < 500, "PFC", "A1"))
print("Units whose unit_db region agrees with the descriptor's unit-number rule:",
      int((rule == inc.region).sum()), "of", len(inc))
print("Group column equals the first digit of the unit number:",
      bool((inc.group == inc.unum // 100).all()))
missing = [u for u, r in inc.iterrows() if int(r.unum) not in S[r.session_name]["spikes"]]
print("Included units without spikes in their session's file:", missing)
not_in_db = sum(len(set(S[s]["kkp_units"]) - set(unit_db[unit_db.session_name == s].unum.astype(int))) for s in S)
print("Clusters in spike files that unit_db does not list:", not_in_db,
      "; clusters in the files in total:", sum(len(S[s]["kkp_units"]) for s in S))
unit_db.csv rows: 401 ; include True: 220
region   A1  PFC  All
ratname              
CR12B    60    0   60
CR17B    18    0   18
CR20B    12   40   52
CR21A     5    7   12
CR24A     4   65   69
YT6A      0    9    9
All      99  121  220
Units whose unit_db region agrees with the descriptor's unit-number rule: 220 of 220
Group column equals the first digit of the unit number: True
Included units without spikes in their session's file: []
Clusters in spike files that unit_db does not list: 2616 ; clusters in the files in total: 2977

The unit table of the paper's code lists 220 units with include True, 121 mPFC and 99 A1, as the paper reports. Every one is in its session's spike file. The region column agrees with the descriptor's rule on unit numbers wherever the output says so.

In [5]:
rows = []
for s, d in S.items():
    t = d["trials"]
    rows.append({"session": s, "rat": d["rat"], "trials": len(t), "munged": int(t.is_munged.sum()),
                 "nonrandom": int((t.nonrandom == 1).sum()),
                 "neg_times": int((t[["cpoke_start", "stim_onset", "cpoke_stop", "choice_made"]] < 0).any(axis=1).sum()),
                 "nan_onset": int(t.stim_onset.isna().sum()),
                 "hold_min_ms": 1000 * (t.stim_onset - t.cpoke_start).min(),
                 "hold_max_ms": 1000 * (t.stim_onset - t.cpoke_start).max(),
                 "units": len(d["spikes"]),
                 "spk_t_min": min((v.min() for v in d["spikes"].values()), default=np.nan),
                 "spk_t_max": max((v.max() for v in d["spikes"].values()), default=np.nan),
                 "last_onset": t.stim_onset.max()})
T = pd.DataFrame(rows).set_index("session")
print(T.round(2).to_string())
print("\nColumns of trial_timings joined to trials_info:", list(next(iter(S.values()))["trials"].columns))
ti0 = next(iter(S.values()))["trials"]
print("stim_name values:", sorted(ti0.stim_name.unique()))
print("outcome values over all sessions:", sorted(set().union(*[set(d['trials'].outcome) for d in S.values()])))
print("block values:", sorted(set().union(*[set(d['trials'].block) for d in S.values()])))
sn = pd.concat([d["trials"][["stim_name", "stim_number", "block", "go_or_nogo", "correct_side"]] for d in S.values()]).drop_duplicates()
print("\nstim_number, block, go_or_nogo and correct_side of each stim_name:")
print(sn.sort_values("stim_number").to_string(index=False))
                             rat  trials  munged  nonrandom  neg_times  nan_onset  hold_min_ms  hold_max_ms  units  spk_t_min  spk_t_max  last_onset
session                                                                                                                                             
CR12B_110421_001_behaving  CR12B     480       1        137          0          0         1.16        99.83      2       0.45    3784.71     3726.69
CR12B_110422_001_behaving  CR12B     481       0         83          0          0         1.16        99.83      8       0.00    4461.53     4420.48
CR12B_110423_001_behaving  CR12B     386       0         76          0          0         1.16        99.83      6       0.08    3213.33     2870.10
CR12B_110426_001_behaving  CR12B     944       1         66          0          0         1.00        99.83      7       0.00    5508.87     5469.07
CR12B_110428_001_behaving  CR12B     380       1         52          0          0         1.00        99.66      9       0.01    3459.00     3227.87
CR12B_110429_001_behaving  CR12B     621       1         60          0          0         1.00        99.83      9       0.00    3860.49     3708.70
CR12B_110503_001_behaving  CR12B     368       1         16          0          0         1.99        99.83      3       0.01    3069.19     2966.87
CR12B_110504_001_behaving  CR12B     449       1         59          0          0         1.00        99.83      2       0.00    3008.74     2926.69
CR12B_110505_001_behaving  CR12B     807       0         62          0          0         1.00        99.83      5       0.06    4407.47     4377.19
CR12B_110507_001_behaving  CR12B     498       0         33          0          0         1.00        99.83      0        NaN        NaN     3496.28
CR12B_110508_001_behaving  CR12B     940     320         76          0          1         1.00        99.83      3       0.01    4512.20     4434.19
CR12B_110511_001_behaving  CR12B     536       1         34          0          0         1.00        99.83      5       0.02    3178.82     2978.04
CR12B_110514_001_behaving  CR12B     636       1         47          0          0         1.00        99.83      0        NaN        NaN     3983.77
CR12B_110517_001_behaving  CR12B     379       1          0          0          0         1.00        99.83      1       0.01    2749.63     2429.82
CR17B_110727_001_behaving  CR17B     611       0         94          0          0         1.00        99.83      1       0.63    4514.67     4494.03
CR17B_110728_001_behaving  CR17B     557       0         86          0          0         1.00        99.83      3       0.00    3007.74     2944.24
CR17B_110731_001_behaving  CR17B     834       1         38          0          0         1.00        99.83      4       0.02    3699.34     3653.04
CR17B_110801_001_behaving  CR17B     835       0         89          0          0         1.00        99.83      2       0.07    3367.20     3212.31
CR17B_110803_001_behaving  CR17B    1158     179        254          0          0         1.00        99.83      4       0.00    5117.74     5090.96
CR17B_110804_001_behaving  CR17B    1100     177        216          0          1         1.00        99.83      2       0.01    4719.13     4673.02
CR17B_110805_001_behaving  CR17B     596       2         92          0          1         1.00        99.83      0        NaN        NaN     2439.53
CR17B_110806_001_behaving  CR17B     799       0         88          0          0         1.00        99.83      1       0.02    3193.63     3161.84
CR17B_110808_001_behaving  CR17B     959       0        214          0          0         1.00        99.83      1       0.36    4057.65     3988.99
CR20B_120531_001_behaving  CR20B     352       0         38          0          0       250.16       348.99     14       0.01    4721.27     4642.34
CR20B_120602_001_behaving  CR20B     936       0          6          0          0       250.16       348.99     11       0.04    7858.48     7775.85
CR20B_120603_001_behaving  CR20B     479       0          3          0          0       250.16       348.99      3       0.27    4390.05     4347.91
CR20B_120604_001_behaving  CR20B     746       0          0          0          0       250.31       348.99      6       0.03    5644.29     5465.11
CR20B_120605_001_behaving  CR20B     695     179          0          0          0       250.16       348.99      6       0.01    4662.76     4631.11
CR20B_120606_004_behaving  CR20B     570       1          0          0          0       250.32       348.99      4       0.01    5258.08     5009.01
CR20B_120609_001_behaving  CR20B     609       1          0          0          0       250.32       348.99      0        NaN        NaN     4169.88
CR20B_120612_001_behaving  CR20B     482       1          0          0          0       250.16       348.99      8       0.06    3956.92     3909.88
CR20B_120613_001_behaving  CR20B     390       1          0          0          0       250.16       348.99      0        NaN        NaN     5458.18
CR21A_120502_003_behaving  CR21A     923       1          0          0          0       250.16       348.99      0        NaN        NaN     7278.11
CR21A_120503_004_behaving  CR21A     747       1          9          0          0       250.16       348.99      5       0.00    5426.76     5378.06
CR21A_120504_004_behaving  CR21A     698       0         36          0          0       250.16       348.99      2       0.01    4547.20     4440.97
CR21A_120505_003_behaving  CR21A     918       1          0          0          0       250.16       348.99      1       0.04    5295.72     5198.56
CR21A_120506_003_behaving  CR21A     725       1          0          0          0       250.16       348.99      0        NaN        NaN     4699.48
CR21A_120507_003_behaving  CR21A     867       1          3          0          0       250.16       348.99      1       0.33    5229.45     5158.74
CR21A_120508_001_behaving  CR21A     689       1          0          0          0       250.16       348.99      1       1.72    3527.13     3494.95
CR21A_120509_001_behaving  CR21A     657       0          0          0          0       250.16       348.99      1       1.05    3682.86     3611.14
CR21A_120510_004_behaving  CR21A     722       0          0          0          0       250.32       348.99      1       0.21    4348.59     4086.75
CR24A_121008_001_behaving  CR24A     367       1         49          0          0       250.32       348.82      0        NaN        NaN     3559.10
CR24A_121019_001_behaving  CR24A     885      10         85          0          0       250.32       348.99      1       1.44    6431.72     6295.18
CR24A_121021_001_behaving  CR24A    1433       1        125          0          0       250.16       348.99     11       0.02    8213.90     8043.39
CR24A_121022_001_behaving  CR24A    1220       1          0          0          0       250.16       348.99     15       0.00    5184.70     5118.58
CR24A_121023_001_behaving  CR24A    1077       1          0          0          0       250.16       348.99     11       0.01    5407.35     5357.35
CR24A_121024_001_behaving  CR24A    1451       1          0          0          0       250.16       348.99     10       0.06    5898.31     5885.50
CR24A_121026_001_behaving  CR24A    1034       0          0          0          0       250.16       348.99      2       0.03    5508.03     5420.63
CR24A_121027_001_behaving  CR24A     924       1          8          0          0       250.16       348.99      3       0.45    4163.87     4127.47
CR24A_121029_001_behaving  CR24A    1113       1          0          0          0       250.16       348.99      8       0.03    4440.35     4307.73
CR24A_121030_001_behaving  CR24A     541       1          7          0          0       250.16       348.99      5       0.00    2875.57     2838.10
CR24A_121031_001_behaving  CR24A     751       1          0          0          0       250.32       348.99      1       0.05    4066.00     3999.46
CR24A_121101_001_behaving  CR24A     910       2          0          0          1       250.16       348.99      2       0.03    3709.68     3544.22
YT6A_120201_behaving        YT6A     804       0         34          0          0         1.00        99.83      5     805.43    6198.81     6157.61
YT6A_120202_behaving        YT6A     466       1          0          0          0         1.00        99.82      4       0.05    3036.40     2836.45

Columns of trial_timings joined to trials_info: ['choice_made', 'cpoke_start', 'cpoke_stop', 'stim_onset', 'is_munged', 'correct_side', 'stim_number', 'nonrandom', 'outcome', 'go_or_nogo', 'block', 'stim_name']
stim_name values: ['hi_pc_no', 'le_hi_lc', 'le_hi_pc', 'le_lc_go', 'le_lo_lc', 'le_lo_pc', 'lo_pc_go', 'ri_hi_lc', 'ri_hi_pc', 'ri_lc_no', 'ri_lo_lc', 'ri_lo_pc']
outcome values over all sessions: ['error', 'hit', 'wrong_port']
block values: [1, 2, 3, 4]

stim_number, block, go_or_nogo and correct_side of each stim_name:
stim_name  stim_number  block go_or_nogo correct_side
 lo_pc_go            1      3         go        right
 hi_pc_no            2      3       nogo        right
 le_lc_go            3      1         go         left
 ri_lc_no            4      1       nogo         left
 le_hi_pc            5      4       nogo        right
 ri_hi_pc            6      4       nogo        right
 le_lo_pc            7      4         go        right
 ri_lo_pc            8      4         go        right
 le_hi_lc            9      2         go         left
 ri_hi_lc           10      2       nogo         left
 le_lo_lc           11      2         go         left
 ri_lo_lc           12      2       nogo         left
 ca_lo_pc           13      4         go        right
 ca_hi_pc           14      4       nogo        right
 le_ca_lc           15      2         go         left
 ri_ca_lc           16      2       nogo         left

Hold durations by rat: the code asserts 0 to 100 ms for CR12B, CR17B and YT6A and 250 to 350 ms for the other three; the ranges above agree. Times are in seconds; in every session the spikes start near 0 s and end after the last stimulus onset, so the spike files cover the trials. That is consistent with one clock; the stimulus responses below are the check that a task contrast lines up. No trial has a negative time. A few trials have no stimulus onset (column nan_onset) and are dropped wherever onsets are used. Two points disagree with the descriptor: the stimulus column is named stim_name, not stimulus_name, and the stimulus numbers do not follow the descriptor's order (le_lc_go is 3, not 1; the mapping is printed above). Neither is used: stimuli are taken by name.

In [6]:
# Stimulus timing against spikes: the auditory-responsive units (audresp good, weak or sustained in
# unit_db.csv) should fire more in their response window after the trial table's stimulus onsets
# than in the 50 ms before; the same windows shifted to onset + 1.7 s (inside the intertrial
# interval) are the null. An offset between the clocks would remove the contrast.
psth_rows = []
aud = unit_db[unit_db.include & unit_db.audresp.isin(["good", "weak", "sustained"])]
for ul, u in aud.iterrows():
    d = S[u.session_name]; sp = d["spikes"][int(u.unum)]
    on = pfc1.analysis_trials(d["trials"]).stim_onset.dropna().to_numpy()
    w = u.audresp_t2 - u.audresp_t1
    row = {"ulabel": ul, "session": u.session_name, "region": u.region}
    for name, shift in [("onset", 0.0), ("onset+1.7s", 1.7), ("onset-0.5s", -0.5)]:
        o = on + shift
        ev = pfc1.count_in_windows(sp, o + u.audresp_t1, o + u.audresp_t2).mean() / w
        pre = pfc1.count_in_windows(sp, o - 0.05, o).mean() / 0.05
        row[name] = ev - pre
    psth_rows.append(row)
P = pd.DataFrame(psth_rows)
for reg, g in P.groupby("region"):
    for col in ["onset", "onset+1.7s", "onset-0.5s"]:
        print(f"{reg} (n = {len(g)}), window aligned to {col}: evoked minus pre-window rate, median "
              f"{g[col].median():.2f} Hz, units above 0: {(g[col] > 0).sum()}, Wilcoxon p = {pfc1.signedrank_r(g[col]):.2g}")
per_sess = P.groupby("session")["onset"].median()
print("Sessions with auditory-responsive units:", len(per_sess), "; with a positive median response:", int((per_sess > 0).sum()))
print("Sessions with included units but no auditory-responsive unit (clock not checked this way):",
      sorted(set(unit_db[unit_db.include].session_name) - set(per_sess.index)))
A1 (n = 49), window aligned to onset: evoked minus pre-window rate, median 8.48 Hz, units above 0: 49, Wilcoxon p = 1.1e-09
A1 (n = 49), window aligned to onset+1.7s: evoked minus pre-window rate, median -0.00 Hz, units above 0: 24, Wilcoxon p = 0.69
A1 (n = 49), window aligned to onset-0.5s: evoked minus pre-window rate, median -0.08 Hz, units above 0: 22, Wilcoxon p = 0.37
PFC (n = 31), window aligned to onset: evoked minus pre-window rate, median 3.66 Hz, units above 0: 31, Wilcoxon p = 1.2e-06
PFC (n = 31), window aligned to onset+1.7s: evoked minus pre-window rate, median -0.13 Hz, units above 0: 13, Wilcoxon p = 0.55
PFC (n = 31), window aligned to onset-0.5s: evoked minus pre-window rate, median -0.27 Hz, units above 0: 10, Wilcoxon p = 0.39
Sessions with auditory-responsive units: 33 ; with a positive median response: 33
Sessions with included units but no auditory-responsive unit (clock not checked this way): ['CR12B_110421_001_behaving', 'CR12B_110503_001_behaving', 'CR12B_110504_001_behaving', 'CR17B_110803_001_behaving', 'CR21A_120505_003_behaving', 'CR21A_120507_003_behaving', 'CR21A_120508_001_behaving', 'CR21A_120509_001_behaving', 'CR24A_121019_001_behaving', 'CR24A_121024_001_behaving', 'CR24A_121026_001_behaving', 'CR24A_121029_001_behaving', 'CR24A_121031_001_behaving', 'CR24A_121101_001_behaving']

The responses at the trial table's onset times, against those at shifted times, are the check that the spike files and trial tables share a clock; sessions without an auditory-responsive unit are listed, and for them the rule encoding below (counts in the 50 or 250 ms before onset, which differ between blocks) is the only task-locked check.

unit-table-link¶

The unit and session tables of the paper's code match the data set's spike files and session folders, and the matched units have the paper's counts per region.

Units are matched by session name and unit number, sessions by name (claims file, unit-table-link).

In [7]:
inc = unit_db[unit_db.include]
found = sum(int(r.unum) in S[r.session_name]["spikes"] for _, r in inc.iterrows())
rule = np.where(inc.ratname.isin(["CR12B", "CR17B"]), "A1", np.where(inc.unum < 500, "PFC", "A1"))
sess_found = sum(s in S for s in sessions_df.index)
ntr = pd.Series({s: len(S[s]["trials"]) - int(S[s]["trials"].is_munged.sum()) for s in sessions_df.index if s in S})
print(f"Units with include True: {len(inc)}; found in their session's spike file: {found}")
print("Per region:", inc.region.value_counts().to_dict())
print(f"Region agrees with the descriptor's unit-number rule: {int((rule == inc.region).sum())} of {len(inc)}")
print(f"Sessions of sessions_df.csv among the data set's folders: {sess_found} of {len(sessions_df)}")
print(f"n_trials equals trial_timings rows less munged trials: {int((ntr == sessions_df.loc[ntr.index, 'n_trials']).sum())} of {len(ntr)}")
print("Sessions of unit_db (any include):", unit_db.session_name.nunique(), "; with include True units:", inc.session_name.nunique())
Units with include True: 220; found in their session's spike file: 220
Per region: {'PFC': 121, 'A1': 99}
Region agrees with the descriptor's unit-number rule: 220 of 220
Sessions of sessions_df.csv among the data set's folders: 55 of 55
n_trials equals trial_timings rows less munged trials: 55 of 55
Sessions of unit_db (any include): 56 ; with include True units: 47

Result: reproduced. All 220 units with include True have spikes in their session's spike file, 121 in mPFC and 99 in A1, the region column agrees with the descriptor's rule for all 220, and all 55 sessions of sessions_df.csv are in the data set, each with n_trials equal to its trial_timings rows less the munged trials.

fig2a-above-chance¶

Trained rats perform significantly above 50% correct in both localization and pitch discrimination blocks in the recording sessions, with a median of 698 trials per session; the best rats reach about 85% in both blocks. Sessions not above 50% in either block (4 of 55) were discarded.

Performance as 2-1-behavres/perf.py: hits over hits, errors and wrong-port trials of blocks 2 and 4, nonrandom 0, munged trials dropped (the code loads trials with load_trials_info). Sessions as main00.py: all 55 of sessions_df.csv (all marked include) less the catch-trial session CR20B_120613. Binomial test of hits against 0.5 in each block, two-sided (claims M5), with the one-sided test shown as a variant.

In [8]:
SESSIONS_BEH = [s for s in sessions_df.index[sessions_df.include.astype(bool)] if s != "CR20B_120613_001_behaving"]
beh = []
for s in SESSIONS_BEH:
    d = S[s]
    raw = pfc1.load_raw_trials_info(s, d["rat"])
    t = pfc1.analysis_trials(d["trials"])
    t = t[t.nonrandom == 0]
    r = {"session": s, "rat": d["rat"],
         "n_performed": int((raw.outcome != "future_trial").sum()),
         "n_timings": len(d["trials"]),
         "n_clean": int(((~d["trials"].is_munged.astype(bool)) & (d["trials"].nonrandom == 0)).sum()),
         "n_sessions_df": sessions_df.loc[s, "n_trials"]}
    for b, name in [(2, "LB"), (4, "PB")]:
        x = t[t.block == b]
        h = int((x.outcome == "hit").sum()); n = int(x.outcome.isin(["hit", "error", "wrong_port"]).sum())
        r[f"{name}_perf"] = 100 * h / n
        r[f"{name}_n"] = n
        r[f"{name}_p"] = stats.binomtest(h, n, 0.5).pvalue
        r[f"{name}_p_greater"] = stats.binomtest(h, n, 0.5, alternative="greater").pvalue
    beh.append(r)
BEH = pd.DataFrame(beh).set_index("session")
print(BEH.round(4).to_string())
                             rat  n_performed  n_timings  n_clean  n_sessions_df  LB_perf  LB_n  LB_p  LB_p_greater  PB_perf  PB_n    PB_p  PB_p_greater
session                                                                                                                                                 
CR17B_110727_001_behaving  CR17B          612        611      517          611.0  65.1961   204   0.0           0.0  77.6119   201  0.0000        0.0000
CR17B_110728_001_behaving  CR17B          558        557      471          557.0  80.3571   224   0.0           0.0  81.2865   171  0.0000        0.0000
CR17B_110731_001_behaving  CR17B          834        834      795          833.0  75.7962   314   0.0           0.0  59.5588   272  0.0019        0.0010
CR17B_110801_001_behaving  CR17B          838        835      746          835.0  75.4717   318   0.0           0.0  69.1120   259  0.0000        0.0000
CR17B_110803_001_behaving  CR17B         1159       1158      768          979.0  64.6341   328   0.0           0.0  70.9265   313  0.0000        0.0000
CR17B_110804_001_behaving  CR17B         1105       1100      745          923.0  70.9480   327   0.0           0.0  76.0417   288  0.0000        0.0000
CR17B_110805_001_behaving  CR17B         1009        596      502          594.0  70.0000   230   0.0           0.0  65.3846   182  0.0000        0.0000
CR17B_110806_001_behaving  CR17B          800        799      711          799.0  72.9537   281   0.0           0.0  65.2344   256  0.0000        0.0000
CR17B_110808_001_behaving  CR17B          961        959      745          959.0  76.5472   307   0.0           0.0  67.3139   309  0.0000        0.0000
YT6A_120201_behaving        YT6A          960        804      770          804.0  70.8475   295   0.0           0.0  71.0526   304  0.0000        0.0000
YT6A_120202_behaving        YT6A          466        466      465          465.0  72.7778   180   0.0           0.0  75.3012   166  0.0000        0.0000
CR20B_120531_001_behaving  CR20B          354        352      314          352.0  82.0312   128   0.0           0.0  73.3333   120  0.0000        0.0000
CR20B_120602_001_behaving  CR20B          938        936      930          936.0  86.6667   360   0.0           0.0  74.8521   338  0.0000        0.0000
CR20B_120603_001_behaving  CR20B          480        479      476          479.0  87.7778   180   0.0           0.0  83.8889   180  0.0000        0.0000
CR20B_120604_001_behaving  CR20B          764        746      746          746.0  79.3333   300   0.0           0.0  77.6515   264  0.0000        0.0000
CR20B_120605_001_behaving  CR20B          696        695      516          516.0  87.5000   216   0.0           0.0  92.2222   180  0.0000        0.0000
CR20B_120606_004_behaving  CR20B          570        570      569          569.0  93.7500   240   0.0           0.0  86.6667   180  0.0000        0.0000
CR20B_120609_001_behaving  CR20B          609        609      608          608.0  90.4167   240   0.0           0.0  80.3828   209  0.0000        0.0000
CR20B_120612_001_behaving  CR20B          482        482      481          481.0  88.3333   180   0.0           0.0  82.7778   180  0.0000        0.0000
CR21A_120502_003_behaving  CR21A          923        923      922          922.0  80.5556   360   0.0           0.0  68.4211   323  0.0000        0.0000
CR21A_120503_004_behaving  CR21A          747        747      737          746.0  84.0000   300   0.0           0.0  76.5690   239  0.0000        0.0000
CR21A_120504_004_behaving  CR21A          703        698      662          698.0  85.5124   283   0.0           0.0  79.9065   214  0.0000        0.0000
CR21A_120505_003_behaving  CR21A          918        918      917          917.0  88.3333   360   0.0           0.0  82.3899   318  0.0000        0.0000
CR21A_120506_003_behaving  CR21A          725        725      724          724.0  90.6667   300   0.0           0.0  90.8333   240  0.0000        0.0000
CR21A_120507_003_behaving  CR21A          867        867      863          866.0  87.3199   347   0.0           0.0  90.5724   297  0.0000        0.0000
CR21A_120508_001_behaving  CR21A          689        689      688          688.0  91.8216   269   0.0           0.0  92.0833   240  0.0000        0.0000
CR21A_120509_001_behaving  CR21A          658        657      657          657.0  89.1667   240   0.0           0.0  92.9167   240  0.0000        0.0000
CR21A_120510_004_behaving  CR21A          723        722      722          722.0  93.6667   300   0.0           0.0  94.1667   240  0.0000        0.0000
CR12B_110421_001_behaving  CR12B          480        480      342          479.0  78.3951   162   0.0           0.0  73.4848   132  0.0000        0.0000
CR12B_110422_001_behaving  CR12B          482        481      398          481.0  84.3931   173   0.0           0.0  61.1842   152  0.0072        0.0036
CR12B_110423_001_behaving  CR12B          387        386      310          386.0  76.9737   152   0.0           0.0  75.2577    97  0.0000        0.0000
CR12B_110426_001_behaving  CR12B          944        944      877          943.0  79.4444   360   0.0           0.0  68.5976   328  0.0000        0.0000
CR12B_110428_001_behaving  CR12B          380        380      327          379.0  87.3333   150   0.0           0.0  73.4694    98  0.0000        0.0000
CR12B_110429_001_behaving  CR12B          621        621      560          620.0  86.6667   240   0.0           0.0  63.7838   185  0.0002        0.0001
CR12B_110503_001_behaving  CR12B          368        368      351          367.0  89.8649   148   0.0           0.0  60.5769   104  0.0390        0.0195
CR12B_110504_001_behaving  CR12B          449        449      389          448.0  86.5922   179   0.0           0.0  63.4921   126  0.0031        0.0016
CR12B_110505_001_behaving  CR12B          808        807      745          807.0  75.9857   279   0.0           0.0  70.6522   276  0.0000        0.0000
CR12B_110507_001_behaving  CR12B          499        498      465          498.0  80.4734   169   0.0           0.0  71.2575   167  0.0000        0.0000
CR12B_110508_001_behaving  CR12B          942        940      551          620.0  73.1818   220   0.0           0.0  71.1538   208  0.0000        0.0000
CR12B_110511_001_behaving  CR12B          536        536      501          535.0  76.3285   207   0.0           0.0  71.7949   156  0.0000        0.0000
CR12B_110514_001_behaving  CR12B          636        636      588          635.0  86.0870   230   0.0           0.0  75.9615   208  0.0000        0.0000
CR12B_110517_001_behaving  CR12B          379        379      378          378.0  81.1321   159   0.0           0.0  75.8333   120  0.0000        0.0000
CR24A_121008_001_behaving  CR24A          367        367      317          366.0  72.5352   142   0.0           0.0  77.1739    92  0.0000        0.0000
CR24A_121019_001_behaving  CR24A         1055        885      790          875.0  82.7778   360   0.0           0.0  71.6667   240  0.0000        0.0000
CR24A_121021_001_behaving  CR24A         1433       1433     1307         1432.0  89.4444   540   0.0           0.0  70.9135   416  0.0000        0.0000
CR24A_121022_001_behaving  CR24A         1220       1220     1219         1219.0  87.7083   480   0.0           0.0  82.6190   420  0.0000        0.0000
CR24A_121023_001_behaving  CR24A         1077       1077     1076         1076.0  84.7619   420   0.0           0.0  85.1459   377  0.0000        0.0000
CR24A_121024_001_behaving  CR24A         1451       1451     1450         1450.0  92.4074   540   0.0           0.0  84.0741   540  0.0000        0.0000
CR24A_121026_001_behaving  CR24A         1039       1034     1034         1034.0  92.6014   419   0.0           0.0  89.7222   360  0.0000        0.0000
CR24A_121027_001_behaving  CR24A          924        924      915          923.0  86.6477   352   0.0           0.0  91.9753   324  0.0000        0.0000
CR24A_121029_001_behaving  CR24A         1113       1113     1112         1112.0  89.7619   420   0.0           0.0  89.5884   413  0.0000        0.0000
CR24A_121030_001_behaving  CR24A          541        541      533          540.0  85.9729   221   0.0           0.0  87.2832   173  0.0000        0.0000
CR24A_121031_001_behaving  CR24A          751        751      750          750.0  82.6667   300   0.0           0.0  91.2351   251  0.0000        0.0000
CR24A_121101_001_behaving  CR24A          922        910      908          908.0  91.3889   360   0.0           0.0  89.9676   309  0.0000        0.0000
In [9]:
fail = (BEH.LB_p >= 0.05) | (BEH.PB_p >= 0.05) | (BEH.LB_perf <= 50) | (BEH.PB_perf <= 50)
print(f"Sessions analysed: {len(BEH)}; failing the binomial test in either block: {int(fail.sum())}")
print("Largest p in either block:", f"{BEH[['LB_p', 'PB_p']].max().max():.3g}",
      "; lowest performance:", f"{BEH[['LB_perf', 'PB_perf']].min().min():.1f}%")
for col, label in [("n_performed", "(a) trials performed (outcome not future_trial)"),
                   ("n_clean", "(b) munged and nonrandom trials dropped"),
                   ("n_timings", "variant, rows of trial_timings"),
                   ("n_sessions_df", "variant, n_trials of sessions_df.csv")]:
    print(f"median trials per session, {label}: {BEH[col].median():.1f} "
          f"(expected 698 +/- 69.8; within: {abs(BEH[col].median() - 698) <= 69.8})")
for col in ["n_performed", "n_clean"]:
    allS = [s for s in sessions_df.index]
    print(f"  over all 55 sessions, {col}:",
          np.median([(pfc1.load_raw_trials_info(s, S[s]['rat']).outcome != 'future_trial').sum() if col == 'n_performed'
                     else ((~S[s]['trials'].is_munged.astype(bool)) & (S[s]['trials'].nonrandom == 0)).sum() for s in allS]))
per_rat = BEH.groupby("rat")[["LB_perf", "PB_perf"]].median()
per_rat["sessions"] = BEH.groupby("rat").size()
per_rat["both_within_85pm8.5"] = (abs(per_rat.LB_perf - 85) <= 8.5) & (abs(per_rat.PB_perf - 85) <= 8.5)
print("\nMedian performance over each rat's sessions (%):")
print(per_rat.round(1).to_string())
Sessions analysed: 54; failing the binomial test in either block: 0
Largest p in either block: 0.039 ; lowest performance: 59.6%
median trials per session, (a) trials performed (outcome not future_trial): 736.0 (expected 698 +/- 69.8; within: True)
median trials per session, (b) munged and nonrandom trials dropped: 699.5 (expected 698 +/- 69.8; within: True)
median trials per session, variant, rows of trial_timings: 723.5 (expected 698 +/- 69.8; within: True)
median trials per session, variant, n_trials of sessions_df.csv: 710.0 (expected 698 +/- 69.8; within: True)
  over all 55 sessions, n_performed: 725.0
  over all 55 sessions, n_clean: 688.0

Median performance over each rat's sessions (%):
       LB_perf  PB_perf  sessions  both_within_85pm8.5
rat                                                   
CR12B     80.8     71.2        14                False
CR17B     73.0     69.1         9                False
CR20B     87.6     81.6         8                 True
CR21A     88.3     90.6         9                 True
CR24A     87.2     86.2        12                 True
YT6A      71.8     73.2         2                False
In [10]:
fig, ax = plt.subplots(figsize=(7, 3))
order = ["CR12B", "CR17B", "YT6A", "CR20B", "CR21A", "CR24A"]
for i, rat in enumerate(order):
    g = BEH[BEH.rat == rat]
    ax.plot(np.full(len(g), 3 * i), g.LB_perf, "_", color="b", ms=12)
    ax.plot(np.full(len(g), 3 * i + 1), g.PB_perf, "_", color="r", ms=12)
ax.axhline(50, color="k", ls=":")
ax.set_xticks([3 * i + 0.5 for i in range(6)]); ax.set_xticklabels([f"Rat {pfc1.RAT_NUMBER[r]}" for r in order])
ax.set_ylim(40, 100); ax.set_ylabel("performance (%)")
ax.set_title("blue localization, red pitch discrimination")
plt.show()
print("Plotted range:", f"{BEH[['LB_perf', 'PB_perf']].min().min():.1f} to {BEH[['LB_perf', 'PB_perf']].max().max():.1f}%; none outside the axes")
No description has been provided for this image
Plotted range: 59.6 to 94.2%; none outside the axes

Result: reproduced. None of the 54 analysed sessions fails the binomial test in either block, so the criterion's bound of at most 4 failures holds (and reading (b), no failure, holds too). The median trial count is within tolerance of 698 under reading (a), trials performed, and under reading (b), after munged and nonrandom trials are dropped (printed above). CR20B, CR21A and CR24A each have a median within 8.5 points of 85% in both blocks. The data set holds 55 sessions, the number the paper reports after discarding four; 54 were tested here (the catch-trial session is left out), and all 54 pass.

figs1a-go-better-than-nogo¶

Performance is typically better on go trials than on nogo trials.

As 2-1-behavres/main02.py: per rat, the mean over sessions of the performance on go and on nogo trials of each block (perf.py, nonrandom 0, munged dropped), sessions as fig2a-above-chance.

In [11]:
gng = []
for s in SESSIONS_BEH:
    d = S[s]; t = pfc1.analysis_trials(d["trials"]); t = t[t.nonrandom == 0]
    for b, name in [(2, "localization"), (4, "pitch discrimination")]:
        for g in ["go", "nogo"]:
            x = t[(t.block == b) & (t.go_or_nogo == g)]
            n = x.outcome.isin(["hit", "error", "wrong_port"]).sum()
            gng.append({"rat": d["rat"], "session": s, "block": name, "gng": g,
                        "perf": 100 * (x.outcome == "hit").sum() / n})
GNG = pd.DataFrame(gng)
tab = GNG.groupby(["rat", "block", "gng"]).perf.mean().unstack("gng")
tab["go_minus_nogo"] = tab.go - tab.nogo
print(tab.round(1).to_string())
print(f"\nPairs with go above nogo: {int((tab.go_minus_nogo > 0).sum())} of {len(tab)} (criterion: at least 7)")
gng                           go  nogo  go_minus_nogo
rat   block                                          
CR12B localization          87.8  75.1           12.6
      pitch discrimination  73.8  66.3            7.6
CR17B localization          77.8  66.9           10.9
      pitch discrimination  85.4  54.8           30.6
CR20B localization          92.7  81.5           11.2
      pitch discrimination  86.6  76.0           10.6
CR21A localization          94.3  81.4           12.8
      pitch discrimination  88.8  82.1            6.8
CR24A localization          92.0  80.9           11.1
      pitch discrimination  89.2  78.9           10.3
YT6A  localization          84.4  58.7           25.8
      pitch discrimination  81.0  65.9           15.1

Pairs with go above nogo: 12 of 12 (criterion: at least 7)

Result: reproduced. Go performance exceeds nogo performance in the number of rat and block pairs printed above, which meets the criterion's majority of at least 7 of 12.

fig2d-block-switch¶

After each block change rats switch rapidly to the new target; performance dips briefly during the cue trials at the start of a block and recovers within a few trials.

As 2-1-behavres/main04.py: sessions as fig2a-above-chance, munged trials dropped, nonrandom 0, trials 1 to 20 (the first block) dropped, trials folded on their position in the 160-trial cycle, the hit fraction at each position pooled over sessions (the code's average weighted by trial counts). The criterion's choice: the first trial of each block below the mean over that block's non-cue trials (positions 21 to 80 or 101 to 160), and reaching that mean within the first 10 trials of the block (within 5 as a variant).

In [12]:
fold = []
for s in SESSIONS_BEH:
    t = pfc1.analysis_trials(S[s]["trials"]); t = t[t.nonrandom == 0]
    t = t[t.index > 20]
    fold.append(pd.DataFrame({"pos": (t.index.to_numpy() - 1) % 160 + 1, "hit": (t.outcome == "hit").to_numpy(),
                              "block": t.block.to_numpy()}))
FOLDT = pd.concat(fold)
FOLD = FOLDT.groupby("pos").hit.agg(["mean", "size"])
# The fold assumes 80-trial blocks starting at trial 1 (the code checks this with unique_or_error).
seg = pd.cut(FOLDT.pos, [0, 20, 80, 100, 160], labels=["1-20", "21-80", "81-100", "101-160"])
print("Block column against fold position (trials):")
print(pd.crosstab(seg, FOLDT.block).to_string())
print("Positions holding more than one block value:", int((FOLDT.groupby("pos").block.nunique() > 1).sum()), "of 160")
for name, start in [("localization", 1), ("pitch discrimination", 81)]:
    block_mean = FOLD.loc[start + 20:start + 79, "mean"].mean()
    first = FOLD.loc[start, "mean"]
    early = FOLD.loc[start:start + 9, "mean"]
    reach10 = early.index[early >= block_mean]
    reach5 = FOLD.loc[start:start + 4, "mean"]
    print(f"{name}: hit fraction at block trial 1 = {first:.3f} (n = {FOLD.loc[start, 'size']}), "
          f"mean over non-cue trials = {block_mean:.3f}")
    print("   first 10 trials:", np.round(early.to_numpy(), 3).tolist())
    print(f"   first trial below the mean: {first < block_mean}; first position reaching the mean within 10: "
          f"{(reach10[0] - start + 1) if len(reach10) else None}; within 5: {bool((reach5 >= block_mean).any())}")
print("Trials per position, range:", FOLD["size"].min(), "to", FOLD["size"].max())
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(FOLD.index, 100 * FOLD["mean"], "k-")
for x0, c in [(0.5, "SkyBlue"), (80.5, "pink")]:
    ax.axvspan(x0, x0 + 20, color=c)
ax.set_xlabel("trial in the 160-trial cycle"); ax.set_ylabel("hits (%)"); ax.set_ylim(0, 100)
plt.show()
print("Plotted range:", f"{100 * FOLD['mean'].min():.1f} to {100 * FOLD['mean'].max():.1f}%")
Block column against fold position (trials):
block       1      2     3      4
pos                              
1-20     3967      0     0      0
21-80       0  14993     0      0
81-100      0      0  4261      0
101-160     0      0     0  12995
Positions holding more than one block value: 0 of 160
localization: hit fraction at block trial 1 = 0.560 (n = 209), mean over non-cue trials = 0.833
   first 10 trials: [0.56, 0.665, 0.693, 0.797, 0.812, 0.862, 0.898, 0.911, 0.906, 0.872]
   first trial below the mean: True; first position reaching the mean within 10: 6; within 5: False
pitch discrimination: hit fraction at block trial 1 = 0.496 (n = 234), mean over non-cue trials = 0.785
   first 10 trials: [0.496, 0.574, 0.727, 0.729, 0.773, 0.862, 0.846, 0.838, 0.866, 0.884]
   first trial below the mean: True; first position reaching the mean within 10: 6; within 5: False
Trials per position, range: 169 to 259
No description has been provided for this image
Plotted range: 49.6 to 95.0%

Result: reproduced. In both blocks the hit fraction on the first trial is below the mean of the block's non-cue trials and reaches that mean within the first 10 trials, at the positions printed above; the within-5 variant is printed beside it. The fold's alignment holds: trials at positions 1 to 20, 21 to 80, 81 to 100 and 101 to 160 carry only block values 1, 2, 3 and 4, and no position holds more than one block value.

iti-median¶

The median intertrial interval is 4.0 s (interquartile range 2.7 to 5.3 s).

The criterion's readings: (a) time between consecutive stimulus onsets, (b) time between consecutive center-poke starts, each over all trials of the sessions with included units, pooled. Consecutive rows of trial_timings are used; the same with munged trials dropped is a variant.

In [13]:
iti_rows = []
SESS_UNITS = sorted(unit_db[unit_db.include].session_name.unique())
print("Sessions with included units:", len(SESS_UNITS))
res = {}
for label, col in [("(a) stimulus onsets", "stim_onset"), ("(b) center-poke starts", "cpoke_start")]:
    for drop in [False, True]:
        vals = []
        for s in SESS_UNITS:
            t = S[s]["trials"]
            if drop:
                t = pfc1.analysis_trials(t)
            vals.append(np.diff(t[col].dropna().to_numpy()))
        v = np.concatenate(vals)
        q1, q2, q3 = np.percentile(v, [25, 50, 75])
        ok = abs(q2 - 4.0) <= 0.4 and abs(q1 - 2.7) <= 0.27 and abs(q3 - 5.3) <= 0.53
        res[(label, drop)] = (q2, q1, q3)
        print(f"{label}{', munged dropped' if drop else ''}: median {q2:.2f} s, IQR {q1:.2f} to {q3:.2f} s "
              f"(n = {len(v)}; range {v.min():.2f} to {v.max():.1f} s); all within tolerance: {ok}")
Sessions with included units: 47
(a) stimulus onsets: median 3.99 s, IQR 2.65 to 5.23 s (n = 35741; range 1.05 to 440.1 s); all within tolerance: True
(a) stimulus onsets, munged dropped: median 3.99 s, IQR 2.64 to 5.23 s (n = 34853; range 1.05 to 440.1 s); all within tolerance: True
(b) center-poke starts: median 3.99 s, IQR 2.65 to 5.23 s (n = 35744; range 1.03 to 440.1 s); all within tolerance: True
(b) center-poke starts, munged dropped: median 3.99 s, IQR 2.64 to 5.22 s (n = 34853; range 1.03 to 440.1 s); all within tolerance: True

Result: reproduced. Between consecutive stimulus onsets (reading (a)) the median interval is 3.99 s with an interquartile range of 2.65 to 5.23 s, all three within tolerance of 4.0, 2.7 and 5.3 s; reading (b), consecutive center-poke starts, gives the same values, and dropping munged trials changes them by at most 0.01 s.

Hold-period rule encoding¶

The units are the 220 with include True in unit_db.csv (claims M1). Trials are hits of blocks 2 and 4, nonrandom 0, munged dropped, holds of 50 ms or less dropped (M2). Spikes are counted in the window ending at stimulus onset, 50 ms for CR12B, CR17B and YT6A and 250 ms for the others (M3). A unit encodes the rule when the Mann-Whitney test of its counts in the two blocks (R's wilcox.test, exact=FALSE) gives a Benjamini-Hochberg adjusted p below 0.05; reading (a) adjusts over all 220 units, as the code does, and reading (b) within each region. The preferred block is the one with the higher mean count.

In [14]:
H = pfc1.hold_table(S, unit_db)
print("Units:", len(H), H.region.value_counts().to_dict())
print("Hold-period spikes per unit, min:", H.n_spikes.min(), "(the Supplement's power rule asks for at least 20)")
print("Trials per unit, LB:", H.nLB.min(), "to", H.nLB.max(), "; PB:", H.nPB.min(), "to", H.nPB.max())
print("Hold rates (Hz), LB:", f"{H.LB_hz.min():.2f} to {H.LB_hz.max():.2f}", "; PB:", f"{H.PB_hz.min():.2f} to {H.PB_hz.max():.2f}")
enc_rows = []
for reading, col in [("(a) BH over all 220 units", "p_adj"), ("(b) BH within region", "p_adj_region")]:
    for reg in ["PFC", "A1"]:
        e = H[(H.region == reg) & (H[col] < 0.05)]
        nl, npb = int((e.pref == "LB").sum()), int((e.pref == "PB").sum())
        enc_rows.append({"reading": reading, "region": reg, "units": int((H.region == reg).sum()),
                         "encoding": len(e), "prefer_LB": nl, "prefer_PB": npb,
                         "binomial_p": stats.binomtest(nl, nl + npb, 0.5).pvalue})
ENC = pd.DataFrame(enc_rows)
print(ENC.round(4).to_string(index=False))
print("\nUnadjusted p < 0.05, for comparison:", H[H.p < 0.05].groupby("region").size().to_dict())
print("\nBy rat, reading (a):")
print(pd.crosstab([H.region, H.rat], H.p_adj < 0.05).rename(columns={True: "encoding", False: "not"}).to_string())
Units: 220 {'PFC': 121, 'A1': 99}
Hold-period spikes per unit, min: 21 (the Supplement's power rule asks for at least 20)
Trials per unit, LB: 50 to 499 ; PB: 22 to 454
Hold rates (Hz), LB: 0.06 to 39.51 ; PB: 0.02 to 41.61
                  reading region  units  encoding  prefer_LB  prefer_PB  binomial_p
(a) BH over all 220 units    PFC    121        76         36         40      0.7310
(a) BH over all 220 units     A1     99        36         13         23      0.1325
     (b) BH within region    PFC    121        81         37         44      0.5052
     (b) BH within region     A1     99        35         12         23      0.0895

Unadjusted p < 0.05, for comparison: {'A1': 40, 'PFC': 85}

By rat, reading (a):
p_adj         not  encoding
region rat                 
A1     CR12B   39        21
       CR17B   13         5
       CR20B    8         4
       CR21A    2         3
       CR24A    1         3
PFC    CR20B   18        22
       CR21A    2         5
       CR24A   22        43
       YT6A     3         6
In [15]:
fig, axs = plt.subplots(1, 2, figsize=(8, 3))
for ax, reg in zip(axs, ["PFC", "A1"]):
    g = H[H.region == reg]
    lr = np.log10(g.PB_hz.clip(lower=0.1) / g.LB_hz.clip(lower=0.1))
    sig = g.p_adj < 0.05
    bins = np.linspace(-1.5, 1.5, 31)
    ax.hist([lr[sig], lr[~sig]], bins=bins, stacked=True, color=["k", "w"], edgecolor="k")
    ax.set_title(reg); ax.set_xlabel("log10 PB / LB hold rate (rates floored at 0.1 Hz)")
    print(reg, "log ratio range:", f"{lr.min():.2f} to {lr.max():.2f}", "; outside the axes:", int(((lr < -1.5) | (lr > 1.5)).sum()))
plt.show()
PFC log ratio range: -0.98 to 1.08 ; outside the axes: 0
A1 log ratio range: -1.11 to 0.86 ; outside the axes: 0
No description has been provided for this image

fig3c-pfc-rule-encoding¶

In the hold period of correct trials, 63% (76 of 121) of mPFC neurons individually encode the selection rule; 36 prefer localization and 40 pitch discrimination, and neither preference is significantly more common.

Result: reproduced. Under reading (a), the code's pooled adjustment, 76 of 121 mPFC units encode the rule, 36 preferring localization and 40 pitch discrimination, the paper's counts exactly, and the two-sided binomial test gives p = 0.73. Under reading (b), BH within region, the counts are 81, 37 and 44, each within tolerance (44 at the edge of 40 +/- 4), with binomial p = 0.51, so the claim holds under both readings.

fig4c-a1-rule-encoding¶

In the hold period of correct trials, 36% (36 of 99) of A1 neurons encode the selection rule; 13 prefer localization and 23 pitch discrimination, and neither preference is significantly more common.

Result: reproduced. Under reading (a) 36 of 99 A1 units encode the rule, 13 preferring localization and 23 pitch discrimination, the paper's counts, with binomial p = 0.13. Under reading (b) the counts are 35, 12 and 23, also within tolerance (binomial p = 0.09).

a1-rule-encoding-not-audresp-dependent¶

In A1, rule encoding is not significantly more common among stimulus-responsive neurons (14 of 49) than among nonresponsive ones (22 of 50).

Responsiveness by M4 reading (a), audresp good, weak or sustained in unit_db.csv; rule encoding by M3 reading (a); two-sided Fisher's exact test as 3-1-hold/main3.py.

In [16]:
H = H.join(unit_db[["audresp", "audresp_t1", "audresp_t2"]])
H["responsive"] = H.audresp.isin(["good", "weak", "sustained"])
a1 = H[H.region == "A1"]
# reading (b) of M4 is computed in the evoked-response section below and shown there
for col, label in [("p_adj", "reading (a)"), ("p_adj_region", "reading (b) of M3")]:
    tab = pd.crosstab(a1.responsive, a1[col] < 0.05)
    odds, p = stats.fisher_exact(tab.to_numpy())
    print(f"{label}: responsive {int(tab.loc[True, True])} of {int(tab.loc[True].sum())} encode the rule; "
          f"nonresponsive {int(tab.loc[False, True])} of {int(tab.loc[False].sum())}; Fisher's exact p = {p:.3f}, odds ratio {odds:.2f}")
reading (a): responsive 14 of 49 encode the rule; nonresponsive 22 of 50; Fisher's exact p = 0.144, odds ratio 0.51
reading (b) of M3: responsive 14 of 49 encode the rule; nonresponsive 21 of 50; Fisher's exact p = 0.208, odds ratio 0.55

Result: reproduced. 14 of 49 responsive and 22 of 50 nonresponsive A1 units encode the rule, the paper's counts, and Fisher's exact test gives p above 0.05 (printed above), so the test finds no difference.

rule-encoding-effect-size¶

Among rule-encoding neurons, the median increase in hold-period firing rate in the preferred block is 74.7% in mPFC and 99.7% in A1.

As 3-1-hold/main3.py: per rule-encoding unit (reading (a)), the larger of the two ratios of mean hold rates, minus 1; the median per region.

In [17]:
ENCU = H[H.p_adj < 0.05].copy()
ENCU["increase_pct"] = 100 * (np.maximum(ENCU.mPB / ENCU.mLB, ENCU.mLB / ENCU.mPB) - 1)
for reg, exp in [("PFC", 74.7), ("A1", 99.7)]:
    v = ENCU[ENCU.region == reg].increase_pct
    print(f"{reg}: median increase {v.median():.1f}% over {len(v)} units (expected {exp} +/- {exp/10:.2f}); "
          f"range {v.min():.1f} to {v.max():.1f}%")
    print("   by rat:", ENCU[ENCU.region == reg].groupby("rat").increase_pct.median().round(1).to_dict())
PFC: median increase 74.7% over 76 units (expected 74.7 +/- 7.47); range 12.5 to 5178.9%
   by rat: {'CR20B': 77.4, 'CR21A': 113.6, 'CR24A': 74.2, 'YT6A': 87.2}
A1: median increase 99.8% over 36 units (expected 99.7 +/- 9.97); range 11.4 to 1197.4%
   by rat: {'CR12B': 147.0, 'CR17B': 84.1, 'CR20B': 236.0, 'CR21A': 26.9, 'CR24A': 24.9}

Result: reproduced. The medians are 74.7% in mPFC and 99.8% in A1, within tolerance of the paper's 74.7% and 99.7%.

fig3ab-pfc-example-units¶

Two simultaneously recorded mPFC units encode the rule with opposite preferences; one fires 12.1 Hz in localization against 7.2 Hz in pitch discrimination (483 and 295 trials), the other 5.4 Hz in pitch discrimination against 2.7 Hz in localization, both p < 0.001.

The units are those figures_generated_by_each_script.csv names for panels 3A and 3B.

In [18]:
print(fig_index[fig_index.panel.isin(["3A", "3B", "4A", "4B"])][["panel", "pyfile", "filename"]].to_string(index=False))
def example(ul):
    r = H.loc[ul]
    return {"unit": ul, "LB_hz": round(r.LB_hz, 2), "PB_hz": round(r.PB_hz, 2), "nLB": r.nLB, "nPB": r.nPB, "p_unadjusted": r.p}
ex3 = pd.DataFrame([example("CR24A_121021_001_behaving-257"), example("CR24A_121021_001_behaving-259")], index=["3A", "3B"])
print(ex3.to_string())
panel   pyfile                                   filename
   3A main2.py exemplar-CR24A_121021_001_behaving-257.pdf
   3B main2.py exemplar-CR24A_121021_001_behaving-259.pdf
   4A main2.py exemplar-CR20B_120602_001_behaving-612.pdf
   4B main2.py exemplar-CR20B_120602_001_behaving-712.pdf
                             unit  LB_hz  PB_hz  nLB  nPB  p_unadjusted
3A  CR24A_121021_001_behaving-257  12.07   7.19  483  295  2.024041e-21
3B  CR24A_121021_001_behaving-259   2.66   5.41  483  295  2.756715e-13

Result: reproduced. Unit 257 (3A) fires 12.07 Hz in localization against 7.19 Hz in pitch discrimination over 483 and 295 trials, and unit 259 (3B) 5.41 Hz in pitch discrimination against 2.66 Hz in localization; both tests give p below 0.001. All values are within tolerance.

fig4ab-a1-example-units¶

Two simultaneously recorded A1 units encode the rule; one fires 8.0 Hz in localization against 4.8 Hz in pitch discrimination, the other 10.1 Hz in pitch discrimination against 2.0 Hz in localization, both p < 0.001.

The pair is the two units the code's figure index names for 4A and 4B, units 612 and 712 of CR20B_120602. As the claims file has it after a reader's answer, the legends define the panels by preference, so unit A is whichever of the two prefers localization and unit B the other; the index's panel assignment is not binding and is shown for comparison. The trial counts are compared as a pair, 312 and 253 within 10% each, in either assignment of the blocks.

In [19]:
pair4 = ["CR20B_120602_001_behaving-612", "CR20B_120602_001_behaving-712"]
ex4 = pd.DataFrame([example(u) for u in pair4], index=["4A per index", "4B per index"])
print(ex4.to_string())
unit_a4 = next(u for u in pair4 if H.loc[u, "LB_hz"] > H.loc[u, "PB_hz"])
unit_b4 = next(u for u in pair4 if u != unit_a4)
print(f"\nUnit A (prefers localization): {unit_a4}; unit B (prefers pitch discrimination): {unit_b4}")
print(f"Index assignment {'agrees' if unit_a4 == pair4[0] else 'is swapped'} relative to the legends")
exp4 = {"A_LB": 8.0, "A_PB": 4.8, "B_PB": 10.1, "B_LB": 2.0}
def check4(ua, ub):
    a, b = H.loc[ua], H.loc[ub]
    got = {"A_LB": a.LB_hz, "A_PB": a.PB_hz, "B_PB": b.PB_hz, "B_LB": b.LB_hz}
    return {k: (round(v, 2), exp4[k], abs(v - exp4[k]) <= exp4[k] / 10) for k, v in got.items()}
print("\nBy preference, as the criterion has it (value, expected, within 10%):", check4(unit_a4, unit_b4))
print("Index assignment, for comparison (A = 612, B = 712):", check4(*pair4))
for u in pair4:
    print(f"{u}: unadjusted Mann-Whitney p = {H.loc[u, 'p']:.2g}, below 0.001: {H.loc[u, 'p'] < 0.001}")
for u in pair4:
    nl, npb = H.loc[u, "nLB"], H.loc[u, "nPB"]
    within = lambda got, want: abs(got - want) <= want / 10
    ok = (within(nl, 312) and within(npb, 253)) or (within(nl, 253) and within(npb, 312))
    print(f"{u}: localization {nl}, pitch discrimination {npb} trials; pair 312 and 253 within 10% in some assignment: {ok}")
                                       unit  LB_hz  PB_hz  nLB  nPB  p_unadjusted
4A per index  CR20B_120602_001_behaving-612   2.00  10.07  312  253  2.449432e-62
4B per index  CR20B_120602_001_behaving-712   8.01   4.76  312  253  3.859010e-12

Unit A (prefers localization): CR20B_120602_001_behaving-712; unit B (prefers pitch discrimination): CR20B_120602_001_behaving-612
Index assignment is swapped relative to the legends

By preference, as the criterion has it (value, expected, within 10%): {'A_LB': (np.float64(8.01), 8.0, np.True_), 'A_PB': (np.float64(4.76), 4.8, np.True_), 'B_PB': (np.float64(10.07), 10.1, np.True_), 'B_LB': (np.float64(2.0), 2.0, np.True_)}
Index assignment, for comparison (A = 612, B = 712): {'A_LB': (np.float64(2.0), 8.0, np.False_), 'A_PB': (np.float64(10.07), 4.8, np.False_), 'B_PB': (np.float64(4.76), 10.1, np.False_), 'B_LB': (np.float64(8.01), 2.0, np.False_)}
CR20B_120602_001_behaving-612: unadjusted Mann-Whitney p = 2.4e-62, below 0.001: True
CR20B_120602_001_behaving-712: unadjusted Mann-Whitney p = 3.9e-12, below 0.001: True
CR20B_120602_001_behaving-612: localization 312, pitch discrimination 253 trials; pair 312 and 253 within 10% in some assignment: True
CR20B_120602_001_behaving-712: localization 312, pitch discrimination 253 trials; pair 312 and 253 within 10% in some assignment: True

Result: reproduced. Of the pair 612 and 712, unit 712 prefers localization and is unit A: it fires 8.01 Hz in localization against 4.76 Hz in pitch discrimination. Unit 612 is unit B and fires 10.07 Hz in pitch discrimination against 2.00 Hz in localization. All four rates are within 10% of 8.0, 4.8, 10.1 and 2.0 Hz, both p are below 0.001, and both units have 312 localization and 253 pitch discrimination trials. The code's figure index assigns the two units to the panels the other way round (612 to 4A); under that assignment none of the four rates is within tolerance.

Error trials¶

As 3-2-errhold/main1.py and main2.py: hold counts (M3 windows, holds over 50 ms, munged dropped, nonrandom 0) on all trials of blocks 2 and 4 by stimulus and outcome. Hits; interference trials, wrong-port responses to stimuli whose distractor cues a go (localization le_lo_lc and ri_lo_lc, pitch discrimination le_hi_pc and le_lo_pc); go-on-nogo errors (localization ri_hi_lc and ri_lo_lc, pitch discrimination le_hi_pc and ri_hi_pc). Rule-encoding units (reading (a)) with at least 3 trials in every category; rates in Hz relabelled by preferred block (P) and non-preferred block (NP), normalized by subtracting the hit rate in the non-preferred block. Wilcoxon signed-rank tests across units (M5).

In [20]:
err_rows, err_n = [], []
for ul, u in ENCU.iterrows():
    d = S[u.session]; sp = d["spikes"][int(ul.split("-")[1])]
    cc = pfc1.category_counts(sp, d["trials"], d["rat"], pfc1.ERR_CATEGORIES)
    n = {k: len(v) for k, v in cc.items()}
    err_n.append({"ulabel": ul, "region": u.region, **n})
    if min(n.values()) < 3:
        continue
    P, N = u.pref, ("LB" if u.pref == "PB" else "PB")
    rec = {"ulabel": ul, "region": u.region, "rat": u.rat}
    for c in ["hit", "interference", "error"]:
        rec[c + "_P"] = cc[f"{c}_{P}"].mean() / u.win_s
        rec[c + "_NP"] = cc[f"{c}_{N}"].mean() / u.win_s
    err_rows.append(rec)
ERR = pd.DataFrame(err_rows).set_index("ulabel")
ERRN = pd.DataFrame(err_n).set_index("ulabel")
print("Rule-encoding units kept / dropped for fewer than 3 trials in a category:")
print(pd.DataFrame({"kept": ERR.groupby("region").size(), "encoding": ERRN.groupby("region").size()}).to_string())
NORM = ERR.copy()
cols = ["hit_NP", "interference_NP", "hit_P", "interference_P", "error_NP", "error_P"]
NORM[cols] = ERR[cols].sub(ERR.hit_NP, axis=0)
for reg in ["PFC", "A1"]:
    g = NORM[NORM.region == reg]
    print(f"\n{reg} (n = {len(g)}): mean normalized rate (Hz):", g[cols].mean().round(2).to_dict())
    for c1, c2 in [("hit_NP", "interference_NP"), ("hit_P", "interference_P"), ("interference_P", "interference_NP")]:
        print(f"   {c1} vs {c2}: mean {c2} minus {c1} = {(g[c2] - g[c1]).mean():.2f} Hz, "
              f"units with {c2} higher {int((g[c2] > g[c1]).sum())} of {len(g)}, signed-rank p = {pfc1.signedrank_r(g[c1], g[c2]):.4f}")
    print("   by rat, mean interference minus hit in NP and in P:",
          {r: (round((x.interference_NP - x.hit_NP).mean(), 2), round((x.interference_P - x.hit_P).mean(), 2), len(x))
           for r, x in g.groupby("rat")})
Rule-encoding units kept / dropped for fewer than 3 trials in a category:
        kept  encoding
region                
A1        16        36
PFC       57        76

PFC (n = 57): mean normalized rate (Hz): {'hit_NP': 0.0, 'interference_NP': 3.42, 'hit_P': 3.58, 'interference_P': 1.54, 'error_NP': -0.13, 'error_P': 3.72}
   hit_NP vs interference_NP: mean interference_NP minus hit_NP = 3.42 Hz, units with interference_NP higher 37 of 57, signed-rank p = 0.0012
   hit_P vs interference_P: mean interference_P minus hit_P = -2.05 Hz, units with interference_P higher 16 of 57, signed-rank p = 0.0011
   interference_P vs interference_NP: mean interference_NP minus interference_P = 1.88 Hz, units with interference_NP higher 26 of 57, signed-rank p = 0.6954
   by rat, mean interference minus hit in NP and in P: {'CR20B': (np.float64(1.65), np.float64(-1.99), 17), 'CR21A': (np.float64(13.43), np.float64(-2.19), 1), 'CR24A': (np.float64(1.22), np.float64(0.01), 33), 'YT6A': (np.float64(18.83), np.float64(-13.5), 6)}

A1 (n = 16): mean normalized rate (Hz): {'hit_NP': 0.0, 'interference_NP': 5.28, 'hit_P': 5.35, 'interference_P': 0.73, 'error_NP': 1.21, 'error_P': 5.17}
   hit_NP vs interference_NP: mean interference_NP minus hit_NP = 5.28 Hz, units with interference_NP higher 15 of 16, signed-rank p = 0.0009
   hit_P vs interference_P: mean interference_P minus hit_P = -4.61 Hz, units with interference_P higher 1 of 16, signed-rank p = 0.0006
   interference_P vs interference_NP: mean interference_NP minus interference_P = 4.55 Hz, units with interference_NP higher 14 of 16, signed-rank p = 0.0011
   by rat, mean interference minus hit in NP and in P: {'CR12B': (np.float64(7.16), np.float64(-4.76), 5), 'CR17B': (np.float64(8.76), np.float64(-8.34), 4), 'CR20B': (np.float64(2.26), np.float64(-3.66), 4), 'CR24A': (np.float64(1.51), np.float64(-0.68), 3)}

fig3d-pfc-interference¶

In mPFC rule-encoding neurons, rule encoding is weakened on interference trials; the hold-period response on interference trials is higher than on correct trials in the non-preferred block and lower in the preferred block (57 neurons).

Result: reproduced. 57 mPFC units have enough trials, the paper's count. On interference trials the rate is higher than on hits in the non-preferred block and lower in the preferred block, each with signed-rank p near 0.001 (printed above).

fig4d-a1-interference¶

In A1 rule-encoding neurons the rule encoding is reversed on interference trials; the hold-period response on interference trials is greater in the non-preferred block than in the preferred block (16 neurons).

Result: reproduced. 16 A1 units have enough trials, the paper's count, and the interference rate is higher in the non-preferred than in the preferred block, signed-rank p = 0.0011, below 0.01.

figs2c-s3c-hold-by-trial-type¶

In rule-encoding neurons of both regions, hold-period activity does not differ between correct go, correct nogo and go-on-nogo error trials within a block, while interference trials differ from all other trial types.

As 3-2-errhold/main3.py: the eight categories of the Figure S2C legend, units with at least 3 trials in each, rates relabelled by preferred block and normalized by the mean of the go and nogo hit rates of the non-preferred block (the code's normalization; a constant per unit, so it does not change the paired tests). Signed-rank tests between every pair of categories within each block, Bonferroni over the 12 comparisons of a region.

In [21]:
TT_ORDER = ["go", "nogo", "gonogo_err", "interf"]
tt_rows = []
for ul, u in ENCU.iterrows():
    d = S[u.session]; sp = d["spikes"][int(ul.split("-")[1])]
    cc = pfc1.category_counts(sp, d["trials"], d["rat"], pfc1.TYPE_CATEGORIES)
    if min(len(v) for v in cc.values()) < 3:
        continue
    P, N = u.pref, ("LB" if u.pref == "PB" else "PB")
    rec = {"ulabel": ul, "region": u.region}
    for c in TT_ORDER:
        rec[("P", c)] = cc[f"{c}_{P}"].mean() / u.win_s
        rec[("NP", c)] = cc[f"{c}_{N}"].mean() / u.win_s
    tt_rows.append(rec)
TT = pd.DataFrame(tt_rows).set_index("ulabel")
comp = []
for reg in ["PFC", "A1"]:
    g = TT[TT.region == reg]
    for blk in ["P", "NP"]:
        for i in range(4):
            for j in range(i + 1, 4):
                c1, c2 = TT_ORDER[i], TT_ORDER[j]
                x, y = g[(blk, c1)], g[(blk, c2)]
                comp.append({"region": reg, "block": blk, "c1": c1, "c2": c2, "n": len(g),
                             "mean_c2_minus_c1": (y - x).mean(), "p": pfc1.signedrank_r(x, y)})
COMP = pd.DataFrame(comp)
COMP["p_bonf"] = COMP.groupby("region").p.transform(lambda p: np.minimum(1, p * len(p)))
COMP["involves_interf"] = (COMP.c1 == "interf") | (COMP.c2 == "interf")
print(COMP.round(4).to_string(index=False))
for reg in ["PFC", "A1"]:
    g = COMP[COMP.region == reg]
    absent = (g[~g.involves_interf].p_bonf >= 0.05).all()
    present = (g[g.involves_interf].p_bonf < 0.05).all()
    print(f"{reg}: no non-interference comparison significant: {absent}; every interference comparison significant: {present} "
          f"({int((g[g.involves_interf].p_bonf < 0.05).sum())} of {int(g.involves_interf.sum())})")
region block         c1         c2  n  mean_c2_minus_c1      p  p_bonf  involves_interf
   PFC     P         go       nogo 57           -0.3532 0.3908  1.0000            False
   PFC     P         go gonogo_err 57           -0.0137 0.6853  1.0000            False
   PFC     P         go     interf 57           -2.2021 0.0010  0.0117             True
   PFC     P       nogo gonogo_err 57            0.3395 0.3324  1.0000            False
   PFC     P       nogo     interf 57           -1.8489 0.0016  0.0188             True
   PFC     P gonogo_err     interf 57           -2.1884 0.0002  0.0029             True
   PFC    NP         go       nogo 57            0.4036 0.4600  1.0000            False
   PFC    NP         go gonogo_err 57            0.0475 0.8550  1.0000            False
   PFC    NP         go     interf 57            3.5932 0.0007  0.0088             True
   PFC    NP       nogo gonogo_err 57           -0.3561 0.2428  1.0000            False
   PFC    NP       nogo     interf 57            3.1896 0.0013  0.0159             True
   PFC    NP gonogo_err     interf 57            3.5457 0.0004  0.0050             True
    A1     P         go       nogo 16            0.4978 0.3655  1.0000            False
    A1     P         go gonogo_err 16            0.0261 0.8564  1.0000            False
    A1     P         go     interf 16           -4.4155 0.0006  0.0070             True
    A1     P       nogo gonogo_err 16           -0.4717 0.7761  1.0000            False
    A1     P       nogo     interf 16           -4.9134 0.0009  0.0102             True
    A1     P gonogo_err     interf 16           -4.4416 0.0006  0.0070             True
    A1    NP         go       nogo 16           -0.0668 0.6233  1.0000            False
    A1    NP         go gonogo_err 16            1.1641 0.2243  1.0000            False
    A1    NP         go     interf 16            5.2345 0.0007  0.0085             True
    A1    NP       nogo gonogo_err 16            1.2309 0.1406  1.0000            False
    A1    NP       nogo     interf 16            5.3013 0.0010  0.0123             True
    A1    NP gonogo_err     interf 16            4.0704 0.0029  0.0353             True
PFC: no non-interference comparison significant: True; every interference comparison significant: True (6 of 6)
A1: no non-interference comparison significant: True; every interference comparison significant: True (6 of 6)

Result: reproduced. In each region (57 mPFC and 16 A1 units) none of the six comparisons among correct go, correct nogo and go-on-nogo errors has a Bonferroni-corrected p below 0.05 (all equal to 1 after correction), and all six comparisons of interference trials with another category have corrected p below 0.05 (largest 0.035, A1 non-preferred block, go-on-nogo against interference).

figs2f-s3f-bidirectional-vs-spont¶

Across rule-encoding neurons in both regions, the hold-period rate is significantly above the spontaneous rate in the preferred block and significantly below it in the non-preferred block.

As 3-3-vs_spont/main2.py and main3.py: the spontaneous rate of each unit is the spike count over the time between its session's first and last stimulus onset lying more than 2 s from every onset (all trials of trial_timings, munged included, time in 0.1 s steps). Hold rates as M3. Signed-rank tests of hold rate against spontaneous rate, in each region for the localization-preferring and pitch-discrimination-preferring units apart, each block. The pooled test per region is a variant.

In [22]:
H["spont"] = [pfc1.spont_rate(S[r.session]["spikes"][int(ul.split("-")[1])], S[r.session]["trials"]) for ul, r in H.iterrows()]
print("Spontaneous rates (Hz):", f"{H.spont.min():.2f} to {H.spont.max():.2f}", "; NaN:", int(H.spont.isna().sum()))
sp_rows = []
E2 = H[H.p_adj < 0.05]
for reg in ["PFC", "A1"]:
    for pref in ["LB", "PB"]:
        g = E2[(E2.region == reg) & (E2.pref == pref)]
        np_ = "PB" if pref == "LB" else "LB"
        pr, nr = g[f"{pref}_hz"], g[f"{np_}_hz"]
        sp_rows.append({"region": reg, "pref": pref, "n": len(g),
                        "pref_minus_spont": (pr - g.spont).mean(), "p_pref": pfc1.signedrank_r(pr, g.spont),
                        "nonpref_minus_spont": (nr - g.spont).mean(), "p_nonpref": pfc1.signedrank_r(nr, g.spont)})
    g = E2[E2.region == reg]
    pr = np.where(g.pref == "PB", g.PB_hz, g.LB_hz); nr = np.where(g.pref == "PB", g.LB_hz, g.PB_hz)
    sp_rows.append({"region": reg, "pref": "pooled (variant)", "n": len(g),
                    "pref_minus_spont": (pr - g.spont).mean(), "p_pref": pfc1.signedrank_r(pr, g.spont),
                    "nonpref_minus_spont": (nr - g.spont).mean(), "p_nonpref": pfc1.signedrank_r(nr, g.spont)})
SP = pd.DataFrame(sp_rows)
SP["holds"] = (SP.pref_minus_spont > 0) & (SP.p_pref < 0.05) & (SP.nonpref_minus_spont < 0) & (SP.p_nonpref < 0.05)
print(SP.round(4).to_string(index=False))
print("Groups (of 4) in which both hold:", int(SP[~SP.pref.str.startswith("pooled")].holds.sum()))
Spontaneous rates (Hz): 0.41 to 40.33 ; NaN: 0
region             pref  n  pref_minus_spont  p_pref  nonpref_minus_spont  p_nonpref  holds
   PFC               LB 36            2.1375  0.0022              -1.0784     0.0025   True
   PFC               PB 40            2.2589  0.0076              -1.2379     0.0164   True
   PFC pooled (variant) 76            2.2014  0.0001              -1.1624     0.0002   True
    A1               LB 13            3.4348  0.0079              -3.0911     0.0253   True
    A1               PB 23            4.1072  0.0001              -3.6938     0.0011   True
    A1 pooled (variant) 36            3.8644  0.0000              -3.4762     0.0001   True
Groups (of 4) in which both hold: 4

Result: reproduced. In all four region and preference groups the preferred-block hold rate is above the spontaneous rate and the non-preferred-block rate below it, each with signed-rank p below 0.05 (largest 0.025, A1 localization-preferring units against their non-preferred block, n = 13). The pooled variant gives p of 0.0002 or less in both regions.

figs2gh-s3gh-rt-mt¶

Anticipatory firing rate does not correlate with reaction time or movement time; few neurons correlate individually and the mean correlation does not differ from zero.

As 3-4-RT_vs_hold/main.py and main3.py: per unit (all 220) and block, the correlation (linear regression) between the square root of the hold count and reaction time (center-port exit minus stimulus onset) on all hits, and movement time (choice-port entry minus stimulus onset) on go hits; munged dropped, nonrandom 0, no hold-length cut (the code counts on all trials). One-sample t-test of the r values against 0 per region, block and measure; individually significant units by Benjamini-Hochberg over each set. The variant takes movement time from center-port exit.

In [23]:
rt_rows = []
for ul, u in H.iterrows():
    d = S[u.session]; sp = d["spikes"][int(ul.split("-")[1])]
    t = pfc1.analysis_trials(d["trials"]); t = t[(t.nonrandom == 0) & (t.outcome == "hit")]
    for b, bn in [(2, "LB"), (4, "PB")]:
        x = t[t.block == b]
        c = np.sqrt(pfc1.hold_counts(sp, x, d["rat"]))
        rt = (x.cpoke_stop - x.stim_onset).to_numpy()
        g = x.go_or_nogo.to_numpy() == "go"
        mt = (x.choice_made - x.stim_onset).to_numpy()
        mt2 = (x.choice_made - x.cpoke_stop).to_numpy()
        rec = {"ulabel": ul, "region": u.region, "block": bn}
        for name, xx, yy in [("RT", c, rt), ("MT", c[g], mt[g]), ("MT_from_exit", c[g], mt2[g])]:
            if np.std(xx) == 0:
                rec["r_" + name], rec["p_" + name] = np.nan, np.nan
            else:
                lr = stats.linregress(xx, yy)
                rec["r_" + name], rec["p_" + name] = lr.rvalue, lr.pvalue
        rt_rows.append(rec)
RT = pd.DataFrame(rt_rows)
print("Fits with a constant count (nothing to fit), dropped:", RT[["r_RT", "r_MT", "r_MT_from_exit"]].isna().sum().to_dict())
out = []
for name in ["RT", "MT", "MT_from_exit"]:
    for (reg, bn), g in RT.groupby(["region", "block"]):
        r = g["r_" + name].dropna(); p = g["p_" + name].dropna()
        out.append({"measure": name, "region": reg, "block": bn, "n": len(r), "mean_r": r.mean(),
                    "ci95_lo": r.mean() - stats.t.ppf(0.975, len(r) - 1) * stats.sem(r),
                    "ci95_hi": r.mean() + stats.t.ppf(0.975, len(r) - 1) * stats.sem(r),
                    "t_p": stats.ttest_1samp(r, 0).pvalue, "indiv_sig_BH": int((pfc1.bh(p) < 0.05).sum())})
RTO = pd.DataFrame(out)
print(RTO.round(4).to_string(index=False))
main = RTO[RTO.measure != "MT_from_exit"]
print("Main measures with mean r significantly different from 0:", int((main.t_p < 0.05).sum()), "of", len(main))
Fits with a constant count (nothing to fit), dropped: {'r_RT': 0, 'r_MT': 1, 'r_MT_from_exit': 1}
     measure region block   n  mean_r  ci95_lo  ci95_hi    t_p  indiv_sig_BH
          RT     A1    LB  99  0.0156  -0.0001   0.0313 0.0517             1
          RT     A1    PB  99 -0.0058  -0.0280   0.0164 0.6083             1
          RT    PFC    LB 121  0.0078  -0.0047   0.0202 0.2205             0
          RT    PFC    PB 121  0.0044  -0.0099   0.0186 0.5470             3
          MT     A1    LB  99  0.0056  -0.0182   0.0295 0.6395             2
          MT     A1    PB  99  0.0061  -0.0210   0.0332 0.6567             0
          MT    PFC    LB 121  0.0053  -0.0152   0.0258 0.6117             5
          MT    PFC    PB 120  0.0013  -0.0202   0.0229 0.9037             0
MT_from_exit     A1    LB  99 -0.0003  -0.0229   0.0222 0.9763             2
MT_from_exit     A1    PB  99  0.0093  -0.0174   0.0359 0.4921             0
MT_from_exit    PFC    LB 121 -0.0011  -0.0206   0.0184 0.9099             2
MT_from_exit    PFC    PB 120  0.0057  -0.0169   0.0283 0.6166             0
Main measures with mean r significantly different from 0: 0 of 8

Result: reproduced. For none of the eight region, block and measure combinations does the mean correlation differ from zero (one-sample t-test p from 0.052 to 0.90; the smallest, A1 localization reaction time, has mean r = 0.016). Between 0 and 5 units of 99 or 121 correlate individually after Benjamini-Hochberg. Movement time from center-port exit gives the same (p from 0.49 to 0.98). The 95% intervals of the mean correlation lie within -0.03 to +0.04 for all eight sets; the borderline A1 localization interval runs from -0.0001 to 0.031, so any correlation there is small.

fig5ab-single-unit-onset¶

The median rule-encoding unit first shows a significant block preference 0.55 s before the stimulus in A1 and 0.625 s before it in mPFC, so most develop it before the trial is initiated.

As 5-2-timecourse_exemplars/main0_dumpcounts.py to main4.py: per rule-encoding unit, hits of blocks 2 and 4 (nonrandom 0, munged dropped), spikes within the window around stimulus onset smoothed per trial with a 50 ms Gaussian and sampled every 50 ms (the code's sample points linspace(-W, W, 2W/0.05, endpoint=False) used as bin edges, values at the centres); a Mann-Whitney test between blocks in each bin, p adjusted by Benjamini-Hochberg over all bins and units together; the interval is the run of significant bins with the preferred direction reaching back from the bin just before onset (refbin, centre -25 ms), and its first bin is the onset, (t1 - refbin) * 0.05 s. The median over units per region (main4.py takes all intervals). The window is W = 3 s (Results; main reading) and W = 5 s (the code; variant).

In [24]:
def single_unit_onsets(W, disc=True):
    edges = np.linspace(-W, W, int(round(2 * W / 0.05)), endpoint=False)
    centers = edges[:-1] + np.diff(edges) / 2
    refbin = int(np.argmin(np.abs(edges - 0.0))) - 1
    pv, au, labels = [], [], []
    for ul, u in ENCU.iterrows():
        d = S[u.session]; sp = d["spikes"][int(ul.split("-")[1])]
        t = pfc1.hit_trials(d["trials"], blocks=[2, 4])
        sm = {b: pfc1.smoothed_trials(sp, t[t.block == b].stim_onset.to_numpy(), centers, 0.05, lo=-W, hi=W, discretize=disc) for b in (2, 4)}
        res = stats.mannwhitneyu(sm[4], sm[2], axis=0, alternative="two-sided", method="asymptotic", use_continuity=True)
        p = np.where(np.isnan(res.pvalue), 1.0, res.pvalue)
        pv.append(p); au.append(res.statistic / (sm[4].shape[0] * sm[2].shape[0])); labels.append(ul)
    pv, au = np.array(pv), np.array(au)
    padj = pfc1.bh(pv.ravel()).reshape(pv.shape)
    rows = []
    for k, ul in enumerate(labels):
        t1, t2 = pfc1.first_bin_of_interval(padj[k], au[k], refbin)
        rows.append({"ulabel": ul, "region": ENCU.loc[ul, "region"], "rat": ENCU.loc[ul, "rat"],
                     "onset_s_before": -(t1 - refbin) * 0.05, "end_s_after": (t2 - refbin) * 0.05,
                     "refbin_sig": padj[k, refbin] <= 0.05})
    return pd.DataFrame(rows).set_index("ulabel"), centers[refbin]

t0 = time.time()
ONS = {}
for W, disc in [(3, True), (5, True), (3, False), (5, False)]:
    ONS[(W, disc)], refc = single_unit_onsets(W, disc)
    print(f"W = {W} s, {'spikes moved to the sample grid (the code)' if disc else 'exact spike times (variant)'} (refbin centre {refc * 1000:.0f} ms):")
    for reg, exp in [("A1", 0.55), ("PFC", 0.625)]:
        g = ONS[(W, disc)][ONS[(W, disc)].region == reg]
        q = np.percentile(g.onset_s_before, [25, 50, 75])
        print(f"   {reg}: median onset {q[1]:.3f} s before stimulus (expected {exp} +/- 0.05), IQR {q[0]:.3f} to {q[2]:.3f}, "
              f"n = {len(g)}, units whose refbin is significant {int(g.refbin_sig.sum())}; "
              f"onset earlier than 0.35 s before stimulus: {int((g.onset_s_before > 0.35).sum())}")
        print("      by rat (median):", g.groupby("rat").onset_s_before.median().round(3).to_dict())
        gv = g[g.refbin_sig]
        print(f"      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): "
              f"median {gv.onset_s_before.median():.3f} s, n = {len(gv)}")
        gi = g[~g.refbin_sig]
        print(f"      units whose refbin is not significant, onsets (s before stimulus): {sorted(gi.onset_s_before.round(3).tolist())}")
        g0 = np.where(g.refbin_sig, g.onset_s_before, 0.0)
        print(f"      variant, those units counted as having no preference before the stimulus (onset 0): median {np.median(g0):.3f} s, n = {len(g0)}")
print(f"({time.time() - t0:.0f} s)")
W = 3 s, spikes moved to the sample grid (the code) (refbin centre -25 ms):
   A1: median onset 0.550 s before stimulus (expected 0.55 +/- 0.05), IQR 0.150 to 1.225, n = 36, units whose refbin is significant 34; onset earlier than 0.35 s before stimulus: 21
      by rat (median): {'CR12B': 0.5, 'CR17B': 0.6, 'CR20B': 0.825, 'CR21A': 0.35, 'CR24A': 0.7}
      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): median 0.650 s, n = 34
      units whose refbin is not significant, onsets (s before stimulus): [0.05, 0.15]
      variant, those units counted as having no preference before the stimulus (onset 0): median 0.550 s, n = 36
   PFC: median onset 0.625 s before stimulus (expected 0.625 +/- 0.05), IQR 0.338 to 1.050, n = 76, units whose refbin is significant 69; onset earlier than 0.35 s before stimulus: 57
      by rat (median): {'CR20B': 0.55, 'CR21A': 0.75, 'CR24A': 0.6, 'YT6A': 2.7}
      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): median 0.650 s, n = 69
      units whose refbin is not significant, onsets (s before stimulus): [0.0, 0.0, 0.0, 0.1, 0.75, 0.8, 1.35]
      variant, those units counted as having no preference before the stimulus (onset 0): median 0.600 s, n = 76
W = 5 s, spikes moved to the sample grid (the code) (refbin centre -25 ms):
   A1: median onset 0.550 s before stimulus (expected 0.55 +/- 0.05), IQR 0.150 to 1.225, n = 36, units whose refbin is significant 34; onset earlier than 0.35 s before stimulus: 21
      by rat (median): {'CR12B': 0.5, 'CR17B': 0.6, 'CR20B': 0.825, 'CR21A': 0.35, 'CR24A': 0.7}
      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): median 0.650 s, n = 34
      units whose refbin is not significant, onsets (s before stimulus): [0.05, 0.15]
      variant, those units counted as having no preference before the stimulus (onset 0): median 0.550 s, n = 36
   PFC: median onset 0.625 s before stimulus (expected 0.625 +/- 0.05), IQR 0.338 to 1.050, n = 76, units whose refbin is significant 69; onset earlier than 0.35 s before stimulus: 57
      by rat (median): {'CR20B': 0.55, 'CR21A': 0.75, 'CR24A': 0.6, 'YT6A': 2.85}
      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): median 0.650 s, n = 69
      units whose refbin is not significant, onsets (s before stimulus): [0.0, 0.0, 0.0, 0.1, 0.75, 0.8, 1.35]
      variant, those units counted as having no preference before the stimulus (onset 0): median 0.600 s, n = 76
W = 3 s, exact spike times (variant) (refbin centre -25 ms):
   A1: median onset 0.575 s before stimulus (expected 0.55 +/- 0.05), IQR 0.150 to 1.225, n = 36, units whose refbin is significant 33; onset earlier than 0.35 s before stimulus: 21
      by rat (median): {'CR12B': 0.5, 'CR17B': 0.65, 'CR20B': 0.925, 'CR21A': 0.35, 'CR24A': 0.7}
      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): median 0.700 s, n = 33
      units whose refbin is not significant, onsets (s before stimulus): [0.1, 0.1, 0.15]
      variant, those units counted as having no preference before the stimulus (onset 0): median 0.575 s, n = 36
   PFC: median onset 0.750 s before stimulus (expected 0.625 +/- 0.05), IQR 0.350 to 2.163, n = 76, units whose refbin is significant 67; onset earlier than 0.35 s before stimulus: 60
      by rat (median): {'CR20B': 0.7, 'CR21A': 1.0, 'CR24A': 0.7, 'YT6A': 2.675}
      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): median 0.750 s, n = 67
      units whose refbin is not significant, onsets (s before stimulus): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.95, 1.0, 1.35]
      variant, those units counted as having no preference before the stimulus (onset 0): median 0.700 s, n = 76
W = 5 s, exact spike times (variant) (refbin centre -25 ms):
   A1: median onset 0.575 s before stimulus (expected 0.55 +/- 0.05), IQR 0.150 to 1.225, n = 36, units whose refbin is significant 33; onset earlier than 0.35 s before stimulus: 21
      by rat (median): {'CR12B': 0.5, 'CR17B': 0.65, 'CR20B': 0.925, 'CR21A': 0.35, 'CR24A': 0.7}
      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): median 0.700 s, n = 33
      units whose refbin is not significant, onsets (s before stimulus): [0.0, 0.1, 0.15]
      variant, those units counted as having no preference before the stimulus (onset 0): median 0.575 s, n = 36
   PFC: median onset 0.750 s before stimulus (expected 0.625 +/- 0.05), IQR 0.350 to 2.163, n = 76, units whose refbin is significant 67; onset earlier than 0.35 s before stimulus: 60
      by rat (median): {'CR20B': 0.675, 'CR21A': 1.0, 'CR24A': 0.65, 'YT6A': 2.825}
      units with a significant refbin only (main3.py marks the others invalid; main4.py keeps them): median 0.750 s, n = 67
      units whose refbin is not significant, onsets (s before stimulus): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.95, 1.0, 1.35]
      variant, those units counted as having no preference before the stimulus (onset 0): median 0.675 s, n = 76
(9 s)

Result: reproduced, resting on an assumption. With the code's smoother (spikes moved to the 50 ms sample grid), the median rule-encoding unit first shows its block preference 0.550 s before the stimulus in A1 (36 units) and 0.625 s before it in mPFC (76 units), the paper's values, with W = 3 s and W = 5 s alike; both exceed 0.35 s. With exact spike times (variant) the medians are 0.575 s (within tolerance) and 0.750 s (outside it), so the match depends on the code's discretization, which the paper does not describe; the outcome follows the code, as reader step 2 directs where the Methods leave a choice open. Leaving out the units whose bin before onset is not significant (7 mPFC and 2 A1 units; main3.py marks them invalid, main4.py keeps them) gives 0.650 s in both regions with the code's smoother, outside tolerance in A1. The criterion defines the interval as the run that contains the bin just before onset, which these units lack, but also takes the median over units as main4.py does, and main4.py keeps them. The outcome assumes the median is over all rule-encoding units, as the paper's "the median rule-encoding unit" and the n of 36 and 76 of Figure 5C suggest; counting those units as having no preference before the stimulus (onset 0) gives 0.550 s in A1 and 0.600 s in mPFC, also within tolerance. Only leaving them out fails.

fig5c-population-onset¶

The population activity of rule-encoding neurons in their preferred block ramps up before the stimulus and is significantly elevated earlier in mPFC (from 2.7 s before stimulus onset) than in A1 (from 0.88 s).

As 5-1-timecourse/main1.py, shared.py and main2b.py: hits on the eight non-cue stimulus pairs, nonrandom 0, munged dropped, locked to stimulus onset, spikes within 3 s; 50 ms Gaussian smoothing sampled in 50 ms bins from -2.9 to 2.9 s; the rate of each stimulus pair is the smoothed count over trials times bin width; each unit's rates z-scored over all bins and pairs, averaged within the go and the nogo pairs of each block and then over go and nogo; the preferred block. Per bin a one-sample t-test against 0 over units, Benjamini-Hochberg over bins; the onset is the centre of the first significant bin with a positive mean.

In [25]:
GROUPS = {("LB", "GO"): ["le_lo_lc", "le_hi_lc"], ("LB", "NO"): ["ri_lo_lc", "ri_hi_lc"],
          ("PB", "GO"): ["ri_lo_pc", "le_lo_pc"], ("PB", "NO"): ["ri_hi_pc", "le_hi_pc"]}

def zscored_group_rates(event, edges, smooth, disc=True):
    centers = edges[:-1] + np.diff(edges) / 2
    bw = np.mean(np.diff(edges))
    out = {}
    for ul, u in ENCU.iterrows():
        d = S[u.session]; sp = d["spikes"][int(ul.split("-")[1])]
        t = pfc1.hit_trials(d["trials"], stims=pfc1.MIXED_STIMNAMES)
        rates = {}
        for s in pfc1.MIXED_STIMNAMES:
            ev = t[t.stim_name == s][event].dropna().to_numpy()
            if smooth:
                sm = pfc1.smoothed_trials(sp, ev, centers, 0.05, lo=-3.0, hi=3.0, discretize=disc).sum(0)
            else:
                i0, i1 = np.searchsorted(sp, ev - 3.0), np.searchsorted(sp, ev + 3.0)
                rel = np.concatenate([sp[a:b] - e for a, b, e in zip(i0, i1, ev)]) if len(ev) else np.array([])
                sm = np.histogram(rel, bins=edges)[0]
            rates[s] = sm / (len(ev) * bw)
        R = pd.DataFrame(rates)
        z = (R - R.to_numpy().mean()) / R.to_numpy().std()
        out[ul] = {k: z[v].mean(axis=1).to_numpy() for k, v in GROUPS.items()}
    return out, centers

pop_rows = []
for disc in [True, False]:
  ZC, cent_c = zscored_group_rates("stim_onset", np.linspace(-2.9, 2.9, 117), smooth=True, disc=disc)
  for reg, exp in [("PFC", 2.7), ("A1", 0.88)]:
      uls = ENCU.index[ENCU.region == reg]
      arr = np.array([(ZC[u][(ENCU.loc[u, "pref"], "GO")] + ZC[u][(ENCU.loc[u, "pref"], "NO")]) / 2 for u in uls])
      p = stats.ttest_1samp(arr, 0, axis=0).pvalue
      padj = pfc1.bh(p)
      m = arr.mean(0)
      sig = np.where((padj < 0.05) & (m > 0))[0]
      first = cent_c[sig[0]] if len(sig) else np.nan
      lose = (sig[0] + np.where(~(padj[sig[0]:] < 0.05))[0][0]) if len(sig) and (~(padj[sig[0]:] < 0.05)).any() else None
      pop_rows.append({"smoothing": "code (grid)" if disc else "exact times (variant)", "region": reg, "n": len(uls), "first_sig_s_before": -first, "expected": exp,
                       "within": abs(-first - exp) <= exp / 10, "loses_sig_at_s": cent_c[lose] if lose is not None else np.nan,
                       "unadjusted_first_s_before": -cent_c[np.where((p < 0.05) & (m > 0))[0][0]]})
      print(f"{reg}: mean z at -2.9, -1, -0.025 s:", np.round(m[[0, np.argmin(abs(cent_c + 1)), np.argmin(abs(cent_c + 0.025))]], 3))
  if disc:
      ZC_code = ZC
POP = pd.DataFrame(pop_rows)
print(POP.round(3).to_string(index=False))
fig, ax = plt.subplots(figsize=(5, 3))
for reg, c in [("PFC", "purple"), ("A1", "orange")]:
    uls = ENCU.index[ENCU.region == reg]
    arr = np.array([(ZC_code[u][(ENCU.loc[u, "pref"], "GO")] + ZC_code[u][(ENCU.loc[u, "pref"], "NO")]) / 2 for u in uls])
    ax.plot(cent_c, arr.mean(0), color=c, label=reg)
    print(reg, "plotted mean z range:", f"{arr.mean(0).min():.2f} to {arr.mean(0).max():.2f}")
ax.axvline(0, color="k", lw=0.5); ax.set_xlabel("time from stimulus onset (s)"); ax.set_ylabel("z-scored rate, preferred block"); ax.legend()
plt.show()
PFC: mean z at -2.9, -1, -0.025 s: [0.08  0.378 0.813]
A1: mean z at -2.9, -1, -0.025 s: [-0.2    0.165  1.196]
PFC: mean z at -2.9, -1, -0.025 s: [0.073 0.372 0.819]
A1: mean z at -2.9, -1, -0.025 s: [-0.204  0.158  1.201]
            smoothing region  n  first_sig_s_before  expected  within  loses_sig_at_s  unadjusted_first_s_before
          code (grid)    PFC 76               2.725      2.70    True           0.525                      2.775
          code (grid)     A1 36               0.875      0.88    True           0.175                      0.925
exact times (variant)    PFC 76               2.725      2.70    True           0.525                      2.775
exact times (variant)     A1 36               0.875      0.88    True           0.175                      0.925
PFC plotted mean z range: 0.03 to 0.98
A1 plotted mean z range: -0.24 to 1.20
No description has been provided for this image

Result: reproduced. The preferred-block population is first significantly above 0 at 2.725 s before stimulus onset in mPFC (76 units) and 0.875 s before in A1 (36 units), within tolerance of 2.7 and 0.88 s, and mPFC is earlier. Smoothing with exact spike times gives the same bins.

fig5d-go-nogo¶

In the preferred block, after the rat leaves the center port, the population rate of rule-encoding neurons stays above baseline for several seconds on nogo trials and falls below baseline on go trials, in both mPFC and A1.

As 5-1-timecourse/main2.py: locked to center-port exit, 50 ms bins from -3 to 3 s, counts without smoothing, z-scored per unit as in fig5c-population-onset (baseline 0), the preferred block, go and nogo apart. Readings: (a) per unit the mean z-scored rate from 0 to 3 s after exit, one-sample t-test over units; (b) per-bin one-sample t-tests, Benjamini-Hochberg over bins, holding when nogo is significantly above 0 and go significantly below 0 in most bins from 0.5 to 3 s.

In [26]:
ZD, cent_d = zscored_group_rates("cpoke_stop", np.linspace(-3, 3, 121), smooth=False)
d_rows = []
for reg in ["PFC", "A1"]:
    uls = ENCU.index[ENCU.region == reg]
    for g in ["GO", "NO"]:
        arr = np.array([ZD[u][(ENCU.loc[u, "pref"], g)] for u in uls])
        post = (cent_d > 0) & (cent_d < 3)
        a = arr[:, post].mean(1)
        p_a = stats.ttest_1samp(a, 0).pvalue
        pb = pfc1.bh(stats.ttest_1samp(arr, 0, axis=0).pvalue)
        late = (cent_d > 0.5) & (cent_d < 3)
        m = arr.mean(0)
        frac = np.mean((pb[late] < 0.05) & ((m[late] > 0) if g == "NO" else (m[late] < 0)))
        d_rows.append({"region": reg, "trials": g, "n": len(uls), "(a) mean z 0-3 s": a.mean(), "(a) p": p_a,
                       "(b) fraction of 0.5-3 s bins significant in the claimed direction": frac})
D = pd.DataFrame(d_rows)
print(D.round(4).to_string(index=False))
for reg in ["PFC", "A1"]:
    g = D[D.region == reg].set_index("trials")
    a_ok = g.loc["NO", "(a) mean z 0-3 s"] > 0 and g.loc["NO", "(a) p"] < 0.05 and g.loc["GO", "(a) mean z 0-3 s"] < 0 and g.loc["GO", "(a) p"] < 0.05
    b_ok = (g["(b) fraction of 0.5-3 s bins significant in the claimed direction"] > 0.5).all()
    print(f"{reg}: reading (a) holds {a_ok}; reading (b) holds {b_ok}")
region trials  n  (a) mean z 0-3 s  (a) p  (b) fraction of 0.5-3 s bins significant in the claimed direction
   PFC     GO 76           -0.1629 0.0210                                                               0.56
   PFC     NO 76            0.4372 0.0000                                                               0.96
    A1     GO 36           -0.4213 0.0001                                                               0.80
    A1     NO 36            0.2644 0.0007                                                               0.28
PFC: reading (a) holds True; reading (b) holds True
A1: reading (a) holds True; reading (b) holds False

Result: reproduced. Under reading (a), in mPFC the mean z-scored rate over the 3 s after exit is +0.437 on nogo trials (p < 0.0001) and -0.163 on go trials (p = 0.021); in A1 +0.264 (p = 0.0007) and -0.421 (p = 0.0001). Reading (b) holds in mPFC (96% of nogo and 56% of go bins from 0.5 to 3 s significant in the claimed direction) but not in A1, where only 28% of the nogo bins are. The pass rests on reading (a); in A1 the support for a nogo rate elevated "for at least several seconds" is weaker than in mPFC.

Evoked responses¶

Responsive units by M4 reading (a): audresp good, weak or sustained in unit_db.csv, with the response window audresp_t1 to audresp_t2 (s after stimulus onset). Reading (b), the variant, recomputes the window from the spikes as the Supplement's "Calculation of evoked responses" describes (pfc1.onset_window): all trials of all stimuli (munged dropped), 1 ms Gaussian smoothing, each 0.5 ms bin from 0 to 50 ms after onset against all 0.5 ms bins of the 50 ms before (Mann-Whitney, p < 0.05 uncorrected, the claims file's standard choice), the first run of bins all significantly greater, windows under 1 ms discarded. The four atypical units the Supplement discards cannot be identified, so none is discarded; windows that run to the end of the 50 ms (the code's class "lasts to end") are shown with and without exclusion. Evoked counts, as 6-1-evoked/main0.py: spikes in the window on hits of every stimulus (the twelve stimulus names), nonrandom 0, munged dropped.

In [27]:
RESP = H[H.responsive].copy()
print("Responsive units:", RESP.groupby("region").size().to_dict())
print("Response windows (ms): t1", f"{1000 * RESP.audresp_t1.min():.1f} to {1000 * RESP.audresp_t1.max():.1f}",
      "; t2", f"{1000 * RESP.audresp_t2.min():.1f} to {1000 * RESP.audresp_t2.max():.1f}",
      "; length", f"{1000 * (RESP.audresp_t2 - RESP.audresp_t1).min():.1f} to {1000 * (RESP.audresp_t2 - RESP.audresp_t1).max():.1f}")
print("audresp classes of the included units:")
print(pd.crosstab(H.audresp, H.region).to_string())
EVK = {}
for ul, u in RESP.iterrows():
    d = S[u.session]; sp = d["spikes"][int(ul.split("-")[1])]
    t = pfc1.hit_trials(d["trials"], stims=pfc1.ALL_STIMNAMES)
    EVK[ul] = {s: pfc1.evoked_counts(sp, t[t.stim_name == s], u.audresp_t1, u.audresp_t2) for s in pfc1.ALL_STIMNAMES}
RESP["evok_dt"] = RESP.audresp_t2 - RESP.audresp_t1
Responsive units: {'A1': 49, 'PFC': 31}
Response windows (ms): t1 4.5 to 29.5 ; t2 11.5 to 39.5 ; length 3.5 to 35.0
audresp classes of the included units:
region          A1  PFC
audresp                
good            19    1
lasts to end     5    2
lasts too long   3    2
nothing         31   60
sustained        6    0
too brief       11   26
weak            24   30
In [28]:
t0 = time.time()
win_b = {}
for ul, u in H.iterrows():
    d = S[u.session]
    on = pfc1.analysis_trials(d["trials"]).stim_onset.dropna().to_numpy()
    win_b[ul] = pfc1.onset_window(d["spikes"][int(ul.split("-")[1])], on)
H["b_t1"] = [w[0] if w else np.nan for w in win_b.values()]
H["b_t2"] = [w[1] if w else np.nan for w in win_b.values()]
H["b_len_ms"] = 1000 * (H.b_t2 - H.b_t1)
H["responsive_b"] = H.b_len_ms >= 1.0 - 1e-9
H["responsive_b_noend"] = H.responsive_b & (H.b_t2 < 0.05 - 1e-9)
print(f"Reading (b) computed for {len(H)} units in {time.time() - t0:.0f} s")
print(pd.crosstab([H.region, H.audresp], [H.responsive_b, H.responsive_b_noend], rownames=["region", "unit_db audresp"],
                  colnames=["(b) responsive", "(b) and not to end"]).to_string())
both = H[H.responsive & H.responsive_b]
print(f"Units responsive under both readings: {len(both)}; window start equal within 0.25 ms: {int((abs(both.b_t1 - both.audresp_t1) < 0.00025).sum())}, "
      f"end equal: {int((abs(both.b_t2 - both.audresp_t2) < 0.00025).sum())}")
Reading (b) computed for 220 units in 3 s
(b) responsive         False True       
(b) and not to end     False False True 
region unit_db audresp                  
A1     good                2     0    17
       lasts to end        0     2     3
       lasts too long      0     0     3
       nothing            28     0     3
       sustained           0     1     5
       too brief           5     0     6
       weak                3     0    21
PFC    good                0     0     1
       lasts to end        0     0     2
       lasts too long      0     0     2
       nothing            57     0     3
       too brief          10     0    16
       weak                8     0    22
Units responsive under both readings: 67; window start equal within 0.25 ms: 50, end equal: 50

audresp-prevalence¶

Auditory-responsive neurons are significantly rarer in mPFC (31 of 121) than in A1 (49 of 99).

Two-sided Fisher's exact test, as 6-2-evokmisc/main1.py.

In [29]:
tab = pd.crosstab(H.region, H.responsive)
table = [[int(tab.loc["A1", True]), int(tab.loc["A1", False])], [int(tab.loc["PFC", True]), int(tab.loc["PFC", False])]]
odds, p = stats.fisher_exact(table)
print(tab.to_string())
print(f"Reading (a): responsive mPFC {int(tab.loc['PFC', True])} of {int(tab.loc['PFC'].sum())}, A1 {int(tab.loc['A1', True])} of {int(tab.loc['A1'].sum())}; "
      f"Fisher's exact p = {p:.2g}, odds ratio {odds:.2f}")
for col in ["responsive_b", "responsive_b_noend"]:
    tb = pd.crosstab(H.region, H[col]).reindex(columns=[True, False], fill_value=0)
    o2, p2 = stats.fisher_exact([[int(tb.loc["A1", True]), int(tb.loc["A1", False])], [int(tb.loc["PFC", True]), int(tb.loc["PFC", False])]])
    print(f"Reading (b), {col}: mPFC {int(tb.loc['PFC', True])} of 121, A1 {int(tb.loc['A1', True])} of 99; Fisher's exact p = {p2:.2g}")
responsive  False  True 
region                  
A1             50     49
PFC            90     31
Reading (a): responsive mPFC 31 of 121, A1 49 of 99; Fisher's exact p = 0.0004, odds ratio 2.85
Reading (b), responsive_b: mPFC 46 of 121, A1 61 of 99; Fisher's exact p = 0.00067
Reading (b), responsive_b_noend: mPFC 46 of 121, A1 58 of 99; Fisher's exact p = 0.0028
In [30]:
# a1-rule-encoding-not-audresp-dependent under reading (b) of M4 (variant)
a1 = H[H.region == "A1"]
for col in ["responsive_b", "responsive_b_noend"]:
    tb = pd.crosstab(a1[col], a1.p_adj < 0.05).reindex(index=[True, False], columns=[True, False], fill_value=0)
    o3, p3 = stats.fisher_exact(tb.to_numpy())
    print(f"Variant, {col}: responsive {int(tb.loc[True, True])} of {int(tb.loc[True].sum())} encode the rule, nonresponsive "
          f"{int(tb.loc[False, True])} of {int(tb.loc[False].sum())}; Fisher's exact p = {p3:.3f}, odds ratio {o3:.2f}")
Variant, responsive_b: responsive 20 of 61 encode the rule, nonresponsive 16 of 38; Fisher's exact p = 0.394, odds ratio 0.67
Variant, responsive_b_noend: responsive 18 of 58 encode the rule, nonresponsive 18 of 41; Fisher's exact p = 0.209, odds ratio 0.57

Result: reproduced. 31 of 121 mPFC and 49 of 99 A1 units are responsive, the paper's counts, with Fisher's exact p below 0.001 (printed above). The counts come from the code's unit table (reading (a)), so this reproduces the paper's tabulation, not the classification. Recomputed from the spikes as the Supplement describes (reading (b), a variant), the counts are 46 and 61, both outside tolerance; the claim holds under reading (a) only.

figs5cd-evoked-strength¶

Onset responses are stronger in auditory-responsive A1 neurons than in mPFC neurons, 0.12 against 0.02 extra spikes per trial (median) and 209% against 171% of baseline.

As 6-2-evokmisc/main0.py and main1.py: all trials of every stimulus of each responsive unit (munged dropped, no outcome or nonrandom filter, as the code's 'all' picker); baseline rate from the 50 ms before onset, evoked rate in the response window; extra spikes = (evoked minus baseline rate) times the window length; percent = evoked over baseline rate. Mann-Whitney tests.

In [31]:
s5 = []
for ul, u in RESP.iterrows():
    d = S[u.session]; sp = d["spikes"][int(ul.split("-")[1])]
    t = pfc1.analysis_trials(d["trials"]); t = t[t.stim_name.isin(pfc1.ALL_STIMNAMES) & t.stim_onset.notna()]
    on = t.stim_onset.to_numpy()
    pre = pfc1.count_in_windows(sp, on - 0.05, on).mean() / 0.05
    ev = pfc1.count_in_windows(sp, on + u.audresp_t1, on + u.audresp_t2).mean() / u.evok_dt
    s5.append({"ulabel": ul, "region": u.region, "rat": u.rat, "extra_spikes": (ev - pre) * u.evok_dt,
               "pct_baseline": 100 * ev / pre, "latency_ms": 1000 * (u.audresp_t1 + u.audresp_t2) / 2})
S5 = pd.DataFrame(s5).set_index("ulabel")
for col, exp in [("extra_spikes", {"A1": 0.12, "PFC": 0.02}), ("pct_baseline", {"A1": 209, "PFC": 171})]:
    a, b = S5[S5.region == "A1"][col], S5[S5.region == "PFC"][col]
    print(f"{col}: median A1 {a.median():.3f} (expected {exp['A1']}), mPFC {b.median():.3f} (expected {exp['PFC']}); "
          f"Mann-Whitney p = {pfc1.mannwhitney_r(a, b):.2g}; ranges A1 {a.min():.3f} to {a.max():.3f}, mPFC {b.min():.3f} to {b.max():.3f}")
for col in ["responsive_b", "responsive_b_noend"]:
    rows_b = []
    for ul, u in H[H[col]].iterrows():
        d = S[u.session]; sp = d["spikes"][int(ul.split("-")[1])]
        t = pfc1.analysis_trials(d["trials"]); on = t[t.stim_name.isin(pfc1.ALL_STIMNAMES)].stim_onset.dropna().to_numpy()
        w = u.b_t2 - u.b_t1
        pre = pfc1.count_in_windows(sp, on - 0.05, on).mean() / 0.05
        ev = pfc1.count_in_windows(sp, on + u.b_t1, on + u.b_t2).mean() / w
        rows_b.append({"region": u.region, "extra_spikes": (ev - pre) * w, "pct": 100 * ev / pre if pre > 0 else np.nan,
                       "latency_ms": 1000 * (u.b_t1 + u.b_t2) / 2})
    B5 = pd.DataFrame(rows_b)
    a_, b_ = B5[B5.region == "A1"], B5[B5.region == "PFC"]
    print(f"Variant, reading (b) {col}: extra spikes median A1 {a_.extra_spikes.median():.3f}, mPFC {b_.extra_spikes.median():.3f} "
          f"(p = {pfc1.mannwhitney_r(a_.extra_spikes, b_.extra_spikes):.2g}); percent A1 {a_.pct.median():.1f}, mPFC {b_.pct.median():.1f} "
          f"(p = {pfc1.mannwhitney_r(a_.pct.dropna(), b_.pct.dropna()):.2g}); latency A1 {a_.latency_ms.median():.2f}, mPFC {b_.latency_ms.median():.2f} ms "
          f"(p = {pfc1.mannwhitney_r(a_.latency_ms, b_.latency_ms):.2g})")
print("by rat (median extra spikes, pct), reading (a):")
print(S5.groupby(["region", "rat"])[["extra_spikes", "pct_baseline"]].median().round(3).to_string())
extra_spikes: median A1 0.116 (expected 0.12), mPFC 0.019 (expected 0.02); Mann-Whitney p = 1.3e-09; ranges A1 0.007 to 1.442, mPFC 0.004 to 0.083
pct_baseline: median A1 209.117 (expected 209), mPFC 170.732 (expected 171); Mann-Whitney p = 0.00061; ranges A1 148.358 to 787.990, mPFC 114.030 to 372.671
Variant, reading (b) responsive_b: extra spikes median A1 0.064, mPFC 0.005 (p = 1.4e-10); percent A1 198.2, mPFC 145.2 (p = 1.2e-05); latency A1 16.25, mPFC 16.38 ms (p = 0.41)
Variant, reading (b) responsive_b_noend: extra spikes median A1 0.062, mPFC 0.005 (p = 4.9e-10); percent A1 198.2, mPFC 145.2 (p = 2.3e-05); latency A1 16.13, mPFC 16.38 ms (p = 0.65)
by rat (median extra spikes, pct), reading (a):
              extra_spikes  pct_baseline
region rat                              
A1     CR12B         0.137       223.544
       CR17B         0.053       172.662
       CR20B         0.055       266.204
       CR21A         0.336       189.343
PFC    CR20B         0.019       173.160
       CR21A         0.021       173.077
       CR24A         0.010       167.874
       YT6A          0.025       146.635

Result: reproduced. Over the 49 A1 and 31 mPFC responsive units the medians are 0.116 and 0.019 extra spikes per trial and 209.1% and 170.7% of baseline, all within tolerance of the paper's 0.12, 0.02, 209% and 171%, and the Mann-Whitney tests give p = 1.3e-09 and 0.00061, both below 0.001. Under reading (b) of M4 (variant) A1 is also stronger, with lower medians (0.064 and 0.005 extra spikes, 198% and 145%).

figs5e-latency¶

The median response latency of auditory-responsive mPFC neurons is slightly but significantly longer than in A1, 19.75 against 16.75 ms.

Latency is the centre of the response window (6-2-evokmisc/main1.py).

In [32]:
a, b = S5[S5.region == "A1"].latency_ms, S5[S5.region == "PFC"].latency_ms
print(f"median latency mPFC {b.median():.2f} ms (expected 19.75 +/- 1.975), A1 {a.median():.2f} ms (expected 16.75 +/- 1.675); "
      f"Mann-Whitney p = {pfc1.mannwhitney_r(a, b):.3f}; ranges A1 {a.min():.2f} to {a.max():.2f}, mPFC {b.min():.2f} to {b.max():.2f} ms")
median latency mPFC 19.75 ms (expected 19.75 +/- 1.975), A1 16.75 ms (expected 16.75 +/- 1.675); Mann-Whitney p = 0.010; ranges A1 8.00 to 28.00, mPFC 8.25 to 32.00 ms

Result: reproduced. The median latency is 19.75 ms in mPFC and 16.75 ms in A1, the paper's values, and the Mann-Whitney test gives p = 0.010. Under reading (b) of M4 (variant) the medians are 16.38 and 16.25 ms and do not differ (p = 0.41); the claim rests on the code's response windows.

fig6cd-baseline-evoked-correlation¶

Across auditory-responsive neurons, the change in hold-period rate between blocks correlates with the change in evoked rate, in A1 (43 neurons, trend slope close to 1) and in mPFC (17 neurons), p < 0.001 in each.

As 6-3-evokgain/main0.py and main2.py: units are dropped when a one-sample t-test of all their evoked rates on non-cue hits against their hold rate (weighted by block trial counts) gives p > 0.05. The evoked change is the stimulus-equalized bootstrap mean difference, pitch discrimination minus localization (10000 draws, at least 5 trials per stimulus pair), the hold change the difference of hold rates (M3). Linear regression of evoked change on hold change (scipy linregress). The A1 slope's 95% interval is the criterion's test of "close to 1".

In [33]:
rng_gain = np.random.default_rng(6301)
NOBLOCK = ["le_hi", "ri_hi", "le_lo", "ri_lo"]
gain_rows, too_weak = [], []
for ul, u in RESP.iterrows():
    e = EVK[ul]
    allc = np.concatenate([e[s] for s in pfc1.MIXED_STIMNAMES]) / u.evok_dt
    nlb = sum(len(e[s + "_lc"]) for s in NOBLOCK); npb = sum(len(e[s + "_pc"]) for s in NOBLOCK)
    hold = (nlb * u.mLB + npb * u.mPB) / (nlb + npb) / u.win_s
    p_ev = stats.ttest_1samp(allc, hold).pvalue
    if p_ev > 0.05:
        too_weak.append(ul)
        continue
    rec = {"ulabel": ul, "region": u.region, "rat": u.rat, "hold_diff_hz": (u.mPB - u.mLB) / u.win_s, "p_hold_adj": u.p_adj}
    for sub in [False, True]:
        lb = [e[s + "_lc"] / u.evok_dt - (u.LB_hz if sub else 0) for s in NOBLOCK]
        pb = [e[s + "_pc"] / u.evok_dt - (u.PB_hz if sub else 0) for s in NOBLOCK]
        r = pfc1.stim_equalized_bootstrap(lb, pb, 10000, rng_gain)
        key = "subhold" if sub else "whold"
        rec[f"mdiff_{key}"] = np.nan if r is None else r["mdiff"]
        rec[f"p_{key}"] = np.nan if r is None else max(r["p_boot"], 1e-4)
    gain_rows.append(rec)
GAIN = pd.DataFrame(gain_rows).set_index("ulabel")
print("Too weak (dropped):", pd.Series([RESP.loc[u, "region"] for u in too_weak]).value_counts().to_dict(),
      "; kept:", GAIN.groupby("region").size().to_dict(), "; bootstrap not possible (a pair with < 5 trials):", int(GAIN.mdiff_whold.isna().sum()))
for reg, exp in [("A1", 43), ("PFC", 17)]:
    g = GAIN[(GAIN.region == reg) & GAIN.mdiff_whold.notna()]
    lr = stats.linregress(g.hold_diff_hz, g.mdiff_whold)
    tcrit = stats.t.ppf(0.975, len(g) - 2)
    print(f"{reg}: n = {len(g)} (expected {exp}); slope {lr.slope:.3f} (95% CI {lr.slope - tcrit * lr.stderr:.3f} to "
          f"{lr.slope + tcrit * lr.stderr:.3f}), r = {lr.rvalue:.3f}, p = {lr.pvalue:.2g}; hold change {g.hold_diff_hz.min():.1f} to "
          f"{g.hold_diff_hz.max():.1f} Hz, evoked change {g.mdiff_whold.min():.1f} to {g.mdiff_whold.max():.1f} Hz")
Too weak (dropped): {'PFC': 14, 'A1': 6} ; kept: {'A1': 43, 'PFC': 17} ; bootstrap not possible (a pair with < 5 trials): 0
A1: n = 43 (expected 43); slope 0.977 (95% CI 0.478 to 1.477), r = 0.525, p = 0.0003; hold change -12.3 to 20.7 Hz, evoked change -13.4 to 35.4 Hz
PFC: n = 17 (expected 17); slope 1.455 (95% CI 0.953 to 1.956), r = 0.848, p = 1.7e-05; hold change -13.6 to 6.2 Hz, evoked change -15.3 to 14.9 Hz

Result: reproduced. After the code's weak-response filter 43 A1 and 17 mPFC units remain, the paper's counts. The regression of evoked change on hold change is positive in both, p = 0.0003 in A1 and 1.7e-05 in mPFC, both below 0.001. The A1 slope is 0.98 with a 95% interval of 0.48 to 1.48, which contains 1.

evoked-beyond-baseline-rare¶

After subtracting each block's baseline, only 6 of 43 A1 neurons (14%) change their evoked response significantly between blocks, 4 of the 6 from one rat (Rat 1), with higher rates in pitch discrimination.

As fig6cd-baseline-evoked-correlation with each block's hold rate subtracted from each trial's evoked rate; bootstrap p floored at 1/10000, Benjamini-Hochberg within region (the code); the unadjusted count is a variant.

In [34]:
for reg in ["A1", "PFC"]:
    g = GAIN[(GAIN.region == reg) & GAIN.p_subhold.notna()].copy()
    g["p_adj"] = pfc1.bh(g.p_subhold)
    for label, col in [("BH within region", "p_adj"), ("unadjusted (variant)", "p_subhold")]:
        sig = g[g[col] < 0.05]
        print(f"{reg}, {label}: {len(sig)} of {len(g)} significant; by rat {sig.rat.value_counts().to_dict()}; "
              f"higher in pitch discrimination: {int((sig.mdiff_subhold > 0).sum())}; CR12B higher in PB: "
              f"{int(((sig.rat == 'CR12B') & (sig.mdiff_subhold > 0)).sum())} of {int((sig.rat == 'CR12B').sum())}")
        if reg == "A1" and col == "p_adj":
            print(sig[["rat", "mdiff_subhold", "p_subhold", "p_adj"]].round(4).to_string())

# Stability of the count: the A1 units' bootstrap p under the seed above and two further seeds.
a1 = GAIN[(GAIN.region == "A1") & GAIN.p_subhold.notna()]
PSEED = pd.DataFrame({"rat": a1.rat, "mdiff_subhold": a1.mdiff_subhold, "p_6301": a1.p_subhold})
for seed in [6302, 6303]:
    rng_s = np.random.default_rng(seed)
    ps = []
    for ul in a1.index:
        e, u = EVK[ul], RESP.loc[ul]
        lb = [e[s + "_lc"] / u.evok_dt - u.LB_hz for s in NOBLOCK]
        pb = [e[s + "_pc"] / u.evok_dt - u.PB_hz for s in NOBLOCK]
        ps.append(max(pfc1.stim_equalized_bootstrap(lb, pb, 10000, rng_s)["p_boot"], 1e-4))
    PSEED[f"p_{seed}"] = ps
for c in [c for c in PSEED.columns if c.startswith("p_")]:
    adj = pfc1.bh(PSEED[c])
    sig = PSEED[adj < 0.05]
    print(f"seed {c[2:]}: {len(sig)} of {len(PSEED)} significant after BH, CR12B {int((sig.rat == 'CR12B').sum())}, "
          f"CR12B higher in PB {int(((sig.rat == 'CR12B') & (sig.mdiff_subhold > 0)).sum())}; unadjusted {int((PSEED[c] < 0.05).sum())}")
print("\nAll A1 units, sorted by the first seed's p (BH-adjusted p of the first seed in p_adj_6301):")
PSEED["p_adj_6301"] = pfc1.bh(PSEED.p_6301)
print(PSEED.sort_values("p_6301").round(4).to_string())
A1, BH within region: 6 of 43 significant; by rat {'CR12B': 4, 'CR17B': 2}; higher in pitch discrimination: 4; CR12B higher in PB: 4 of 4
                                 rat  mdiff_subhold  p_subhold   p_adj
ulabel                                                                
CR12B_110423_001_behaving-222  CR12B        24.2341     0.0001  0.0014
CR12B_110428_001_behaving-430  CR12B        16.7907     0.0001  0.0014
CR12B_110429_001_behaving-265  CR12B        10.7545     0.0008  0.0069
CR12B_110511_001_behaving-221  CR12B        20.7816     0.0001  0.0014
CR17B_110731_001_behaving-215  CR17B        -6.7071     0.0012  0.0086
CR17B_110731_001_behaving-318  CR17B       -11.5087     0.0008  0.0069
A1, unadjusted (variant): 12 of 43 significant; by rat {'CR12B': 9, 'CR17B': 3}; higher in pitch discrimination: 7; CR12B higher in PB: 6 of 9
PFC, BH within region: 1 of 17 significant; by rat {'CR24A': 1}; higher in pitch discrimination: 1; CR12B higher in PB: 0 of 0
PFC, unadjusted (variant): 3 of 17 significant; by rat {'CR24A': 2, 'CR20B': 1}; higher in pitch discrimination: 2; CR12B higher in PB: 0 of 0
seed 6301: 6 of 43 significant after BH, CR12B 4, CR12B higher in PB 4; unadjusted 12
seed 6302: 6 of 43 significant after BH, CR12B 4, CR12B higher in PB 4; unadjusted 13
seed 6303: 6 of 43 significant after BH, CR12B 4, CR12B higher in PB 4; unadjusted 14

All A1 units, sorted by the first seed's p (BH-adjusted p of the first seed in p_adj_6301):
                                 rat  mdiff_subhold  p_6301  p_6302  p_6303  p_adj_6301
ulabel                                                                                 
CR12B_110423_001_behaving-222  CR12B        24.2341  0.0001  0.0001  0.0001      0.0014
CR12B_110428_001_behaving-430  CR12B        16.7907  0.0001  0.0001  0.0001      0.0014
CR12B_110511_001_behaving-221  CR12B        20.7816  0.0001  0.0001  0.0001      0.0014
CR17B_110731_001_behaving-318  CR17B       -11.5087  0.0008  0.0010  0.0012      0.0069
CR12B_110429_001_behaving-265  CR12B        10.7545  0.0008  0.0010  0.0004      0.0069
CR17B_110731_001_behaving-215  CR17B        -6.7071  0.0012  0.0016  0.0012      0.0086
CR12B_110428_001_behaving-330  CR12B        14.5171  0.0102  0.0086  0.0098      0.0627
CR12B_110429_001_behaving-113  CR12B        14.1054  0.0188  0.0212  0.0232      0.1010
CR12B_110511_001_behaving-415  CR12B        -8.2276  0.0326  0.0330  0.0322      0.1558
CR17B_110731_001_behaving-406  CR17B         5.7881  0.0422  0.0432  0.0450      0.1680
CR12B_110422_001_behaving-314  CR12B       -10.3384  0.0442  0.0436  0.0390      0.1680
CR12B_110505_001_behaving-335  CR12B        -8.7928  0.0498  0.0502  0.0420      0.1680
CR17B_110728_001_behaving-209  CR17B        -5.1191  0.0508  0.0448  0.0464      0.1680
CR17B_110801_001_behaving-114  CR17B        -3.0991  0.0576  0.0486  0.0468      0.1769
CR12B_110423_001_behaving-111  CR12B         7.6571  0.0692  0.0666  0.0652      0.1984
CR12B_110429_001_behaving-328  CR12B        -6.1153  0.0852  0.0768  0.0744      0.2290
CR12B_110423_001_behaving-202  CR12B        -8.0340  0.0946  0.0998  0.0912      0.2393
CR17B_110806_001_behaving-313  CR17B         4.3962  0.1318  0.1312  0.1296      0.2987
CR12B_110426_001_behaving-419  CR12B         7.3035  0.1320  0.1458  0.1418      0.2987
CR17B_110731_001_behaving-317  CR17B        -6.3207  0.1622  0.1684  0.1682      0.3487
CR12B_110428_001_behaving-428  CR12B        -6.7391  0.1960  0.1966  0.1932      0.4013
CR17B_110804_001_behaving-332  CR17B        -5.5453  0.2236  0.2242  0.2314      0.4370
CR12B_110511_001_behaving-202  CR12B        -4.3384  0.2532  0.2484  0.2598      0.4734
CR20B_120605_001_behaving-603  CR20B         4.2870  0.2808  0.2810  0.2936      0.5031
CR12B_110422_001_behaving-203  CR12B         4.1617  0.3026  0.3084  0.3086      0.5205
CR12B_110426_001_behaving-230  CR12B         2.5728  0.3168  0.3008  0.3160      0.5239
CR12B_110423_001_behaving-218  CR12B         3.9171  0.3426  0.3566  0.3630      0.5456
CR12B_110422_001_behaving-119  CR12B         4.0525  0.3612  0.3628  0.3470      0.5547
CR12B_110428_001_behaving-427  CR12B         4.3554  0.3862  0.3854  0.3796      0.5726
CR20B_120606_004_behaving-706  CR20B         2.7043  0.4134  0.4290  0.4180      0.5899
CR12B_110511_001_behaving-114  CR12B         2.8719  0.4316  0.4316  0.4420      0.5899
CR12B_110508_001_behaving-302  CR12B        -3.2374  0.4390  0.4620  0.4504      0.5899
CR12B_110517_001_behaving-222  CR12B         3.4310  0.4854  0.4788  0.4822      0.6162
CR12B_110428_001_behaving-327  CR12B        -2.6630  0.4872  0.5096  0.4882      0.6162
CR20B_120602_001_behaving-712  CR20B         1.4924  0.5330  0.5498  0.5448      0.6548
CR12B_110426_001_behaving-229  CR12B        -1.5184  0.5546  0.5496  0.5562      0.6624
CR20B_120531_001_behaving-613  CR20B        -3.6288  0.5712  0.5724  0.5562      0.6638
CR21A_120503_004_behaving-604  CR21A         0.9955  0.6700  0.6764  0.6780      0.7582
CR20B_120602_001_behaving-612  CR20B         0.4835  0.7534  0.7600  0.7528      0.8307
CR20B_120531_001_behaving-732  CR20B         1.6961  0.8184  0.8308  0.8394      0.8798
CR12B_110428_001_behaving-106  CR12B        -0.4369  0.8578  0.8654  0.8684      0.8996
CR21A_120503_004_behaving-516  CR21A        -0.8284  0.8974  0.9136  0.9128      0.9188
CR17B_110728_001_behaving-202  CR17B         0.2091  0.9640  0.9820  0.9776      0.9640

Result: reproduced. With the hold rate subtracted, 6 of 43 A1 units change their evoked response significantly after Benjamini-Hochberg, 4 of them from CR12B (Rat 1), a majority, and all 4 CR12B units are higher in pitch discrimination; the 2 others (CR17B) are higher in localization. The unadjusted variant gives 12 of 43, 9 from CR12B. In mPFC 1 of 17 changes. The outcome rests on the code's Benjamini-Hochberg correction; the unadjusted variant, which the Supplement's wording also allows, fails the criterion (12 units, of which 6 of the 9 CR12B units are higher in pitch discrimination). The count is stable over bootstrap seeds: two further seeds also give 6 units, 4 from CR12B and all 4 higher in pitch discrimination, and the next unit in rank has adjusted p = 0.063.

fig6e-decoding¶

Sound identity is decoded more accurately from A1 ensembles (21 ensembles, 49 neurons) than from mPFC ensembles (17 ensembles, 31 neurons), but for neither sound nor region is decoding better in one block than the other.

As 6-1-evoked/main1.py, main2.py, main4.py and decoders.py: an ensemble is the responsive units of one region in one session. Per ensemble, block and sound (noise burst side sL, warble pitch sP), a logistic regression (scikit-learn, class weights balanced, C = 1; the liblinear solver, the default of the code's scikit-learn) on the trial-by-trial evoked counts of hits of the four stimulus pairs of the block, scored in sample as the fraction correct averaged over the two classes. A type II three-way ANOVA of the scores on region, sound and block; paired t-tests between blocks per region and sound, Benjamini-Hochberg over the four. Leave-one-out scores are a variant.

In [35]:
from sklearn.linear_model import LogisticRegression
import statsmodels.formula.api as smf
import statsmodels.api as sm

def cateq_score(X, y, cv=False):
    X = np.asarray(X, float); y = np.asarray(y)
    if X.ndim == 1:
        X = X[:, None]
    def fit(Xt, yt):
        return LogisticRegression(class_weight="balanced", C=1.0, solver="liblinear").fit(Xt, yt)
    if cv:
        pred = np.empty(len(y), dtype=y.dtype)
        for i in range(len(y)):
            m = np.ones(len(y), bool); m[i] = False
            pred[i] = fit(X[m], y[m]).predict(X[i:i + 1])[0]
    else:
        pred = fit(X, y).predict(X)
    return float(np.mean([np.mean(pred[y == v] == v) for v in np.unique(y)]))

dec_rows = []
for (reg, sess), g in RESP.groupby(["region", "session"]):
    for block in ["lc", "pc"]:
        stims = [s for s in pfc1.MIXED_STIMNAMES if s.endswith(block)]
        X = np.column_stack([np.concatenate([EVK[ul][s] for s in stims]) for ul in g.index])
        sL = np.concatenate([np.full(len(EVK[g.index[0]][s]), s[:2] == "ri") for s in stims]).astype(int)
        sP = np.concatenate([np.full(len(EVK[g.index[0]][s]), s[3:5] == "hi") for s in stims]).astype(int)
        for var, y in [("sL", sL), ("sP", sP)]:
            dec_rows.append({"ensem": reg, "session": sess, "block": block, "var": var, "n_units": len(g), "n_trials": len(y),
                             "score": cateq_score(X, y), "score_cv": cateq_score(X, y, cv=True)})
DEC = pd.DataFrame(dec_rows)
nens = DEC.groupby("ensem").session.nunique(); nun = DEC.drop_duplicates(["ensem", "session"]).groupby("ensem").n_units.sum()
print("Ensembles:", nens.to_dict(), "; units in them:", nun.to_dict())
for col in ["score", "score_cv"]:
    fit = smf.ols(f"{col} ~ C(ensem) * C(var) * C(block)", data=DEC).fit()
    aov = sm.stats.anova_lm(fit, typ=2)
    print(f"\n{col}: type II ANOVA")
    print(aov.round(4).to_string())
    print("mean score by region:", DEC.groupby("ensem")[col].mean().round(3).to_dict())
    pv = []
    for reg in ["A1", "PFC"]:
        for var in ["sL", "sP"]:
            piv = DEC[(DEC.ensem == reg) & (DEC["var"] == var)].pivot(index="session", columns="block", values=col)
            pv.append({"ensem": reg, "var": var, "n": len(piv), "mean_lc": piv.lc.mean(), "mean_pc": piv.pc.mean(),
                       "p": stats.ttest_rel(piv.lc, piv.pc).pvalue})
    PV = pd.DataFrame(pv); PV["p_adj"] = pfc1.bh(PV.p)
    print(PV.round(4).to_string(index=False))

# Chance level of the in-sample score: labels shuffled within each ensemble, block and sound (100 shuffles).
rng_dec = np.random.default_rng(6101)
sh_rows = []
for (reg, sess), g in RESP.groupby(["region", "session"]):
    for block in ["lc", "pc"]:
        stims = [s for s in pfc1.MIXED_STIMNAMES if s.endswith(block)]
        X = np.column_stack([np.concatenate([EVK[ul][s] for s in stims]) for ul in g.index])
        sL = np.concatenate([np.full(len(EVK[g.index[0]][s]), s[:2] == "ri") for s in stims]).astype(int)
        sP = np.concatenate([np.full(len(EVK[g.index[0]][s]), s[3:5] == "hi") for s in stims]).astype(int)
        for var, y in [("sL", sL), ("sP", sP)]:
            sh = [cateq_score(X, rng_dec.permutation(y)) for _ in range(100)]
            sh_rows.append({"ensem": reg, "session": sess, "block": block, "var": var, "shuffled_mean": np.mean(sh),
                            "shuffled_95": np.percentile(sh, 95)})
SH = pd.DataFrame(sh_rows).merge(DEC, on=["ensem", "session", "block", "var"])
print("\nShuffled-label in-sample score (chance level) and the real score, by region and sound:")
print(SH.groupby(["ensem", "var"]).agg(real=("score", "mean"), chance=("shuffled_mean", "mean"),
      above_95th=("score", "size")).assign(above_95th=SH.assign(a=SH.score > SH.shuffled_95).groupby(["ensem", "var"]).a.sum()).round(3).to_string())
for reg in ["A1", "PFC"]:
    g = SH[SH.ensem == reg]
    print(f"{reg}: real minus chance {(g.score - g.shuffled_mean).mean():+.3f}, paired t p = {stats.ttest_rel(g.score, g.shuffled_mean).pvalue:.2g} (n = {len(g)} scores)")
Ensembles: {'A1': 21, 'PFC': 17} ; units in them: {'A1': 49, 'PFC': 31}

score: type II ANOVA
                          sum_sq     df        F  PR(>F)
C(ensem)                  0.0886    1.0  39.3300  0.0000
C(var)                    0.0181    1.0   8.0186  0.0053
C(block)                  0.0020    1.0   0.8690  0.3528
C(ensem):C(var)           0.0110    1.0   4.9045  0.0284
C(ensem):C(block)         0.0000    1.0   0.0005  0.9825
C(var):C(block)           0.0000    1.0   0.0027  0.9590
C(ensem):C(var):C(block)  0.0001    1.0   0.0655  0.7983
Residual                  0.3244  144.0      NaN     NaN
mean score by region: {'A1': 0.57, 'PFC': 0.521}
ensem var  n  mean_lc  mean_pc      p  p_adj
   A1  sL 21   0.5837   0.5929 0.5390 0.5911
   A1  sP 21   0.5487   0.5536 0.5911 0.5911
  PFC  sL 17   0.5198   0.5254 0.2367 0.4733
  PFC  sP 17   0.5152   0.5243 0.0881 0.3525

score_cv: type II ANOVA
                          sum_sq     df        F  PR(>F)
C(ensem)                  0.0583    1.0  21.6010  0.0000
C(var)                    0.0177    1.0   6.5622  0.0114
C(block)                  0.0012    1.0   0.4536  0.5017
C(ensem):C(var)           0.0078    1.0   2.8862  0.0915
C(ensem):C(block)         0.0001    1.0   0.0530  0.8183
C(var):C(block)           0.0000    1.0   0.0040  0.9497
C(ensem):C(var):C(block)  0.0000    1.0   0.0051  0.9433
Residual                  0.3885  144.0      NaN     NaN
mean score by region: {'A1': 0.553, 'PFC': 0.514}
ensem var  n  mean_lc  mean_pc      p  p_adj
   A1  sL 21   0.5685   0.5724 0.8335 0.8335
   A1  sP 21   0.5340   0.5380 0.7702 0.8335
  PFC  sL 17   0.5134   0.5200 0.2806 0.5687
  PFC  sP 17   0.5065   0.5155 0.2844 0.5687
Shuffled-label in-sample score (chance level) and the real score, by region and sound:
            real  chance  above_95th
ensem var                           
A1    sL   0.588   0.539          17
      sP   0.551   0.539          10
PFC   sL   0.523   0.518           3
      sP   0.520   0.519           1
A1: real minus chance +0.031, paired t p = 1.6e-06 (n = 84 scores)
PFC: real minus chance +0.003, paired t p = 0.094 (n = 68 scores)

Result: reproduced. There are 21 A1 ensembles of 49 units and 17 mPFC ensembles of 31 units, the paper's counts. The main effect of region has F = 39.3, p < 0.001, with A1 higher (mean score 0.570 against 0.521), and none of the four paired t-tests between blocks is significant (adjusted p 0.35 to 0.59; unadjusted 0.088 to 0.59), so both the region claim and the block claim (an absence) hold. Leave-one-out scores give the same (region F = 21.6, block comparisons adjusted p 0.57 to 0.83). The in-sample score's chance level, from shuffled labels, is about 0.54 in A1 and 0.52 in mPFC. A1 scores exceed it (by 0.031 on average, p = 1.6e-06) and mPFC scores barely do (by 0.003, p = 0.094), so the mPFC block comparisons test scores near chance.

figs5fg-tuning-vs-rule¶

There is no correlation between a neuron's change in anticipatory activity and its tuning for the noise burst or the warble, in A1 or mPFC.

As 6-1-evoked/main2.py and main6.py: tuning is the single-unit in-sample decoding score (as fig6e-decoding) of the cue sound on cue-trial hits of each responsive unit, the noise burst from localization cue trials (le_lc_go, ri_lc_no) and the warble from pitch discrimination cue trials (lo_pc_go, hi_pc_no); units with at least 10 evoked spikes on the cue trials and at least 25 cue trials in each block; the anticipatory change is log10 of the pitch discrimination over localization hold rate. Linear regression of the change on each tuning, per region.

In [36]:
tun = []
for ul, u in RESP.iterrows():
    e = EVK[ul]
    rec = {"ulabel": ul, "region": u.region, "lograt": np.log10(u.mPB / u.mLB)}
    n_sp, n_tr = 0, []
    for block, (s0, s1) in [("lc", ("le_lc_go", "ri_lc_no")), ("pc", ("lo_pc_go", "hi_pc_no"))]:
        X = np.concatenate([e[s0], e[s1]]); y = np.r_[np.zeros(len(e[s0])), np.ones(len(e[s1]))].astype(int)
        rec[block + "_tuneQ"] = cateq_score(X, y) if len(np.unique(y)) == 2 else np.nan
        n_sp += X.sum(); n_tr.append(len(y))
    rec["n_spikes"], rec["min_trials"] = n_sp, min(n_tr)
    tun.append(rec)
TUN = pd.DataFrame(tun).set_index("ulabel")
keep = (TUN.n_spikes >= 10) & (TUN.min_trials >= 25)
print("Units kept:", TUN[keep].groupby("region").size().to_dict(), "; dropped:", TUN[~keep].groupby("region").size().to_dict())
for reg in ["A1", "PFC"]:
    g = TUN[keep & (TUN.region == reg)].dropna()
    for m in ["lc_tuneQ", "pc_tuneQ"]:
        lr = stats.linregress(g[m], g.lograt)
        z = np.arctanh(lr.rvalue); se = 1 / np.sqrt(len(g) - 3)
        print(f"{reg}, {m}: n = {len(g)}, r = {lr.rvalue:.3f} (95% CI {np.tanh(z - 1.96 * se):.2f} to {np.tanh(z + 1.96 * se):.2f}), "
              f"p = {lr.pvalue:.3f}; tuning {g[m].min():.2f} to {g[m].max():.2f}; smallest |r| detectable with 80% power at "
              f"p < 0.05: {np.tanh((1.96 + 0.8416) * se):.2f}")
Units kept: {'A1': 23, 'PFC': 9} ; dropped: {'A1': 26, 'PFC': 22}
A1, lc_tuneQ: n = 23, r = 0.156 (95% CI -0.27 to 0.53), p = 0.478; tuning 0.50 to 0.79; smallest |r| detectable with 80% power at p < 0.05: 0.56
A1, pc_tuneQ: n = 23, r = 0.037 (95% CI -0.38 to 0.44), p = 0.868; tuning 0.50 to 0.71; smallest |r| detectable with 80% power at p < 0.05: 0.56
PFC, lc_tuneQ: n = 9, r = -0.214 (95% CI -0.77 to 0.52), p = 0.581; tuning 0.50 to 0.58; smallest |r| detectable with 80% power at p < 0.05: 0.82
PFC, pc_tuneQ: n = 9, r = 0.513 (95% CI -0.23 to 0.88), p = 0.158; tuning 0.51 to 0.56; smallest |r| detectable with 80% power at p < 0.05: 0.82

Result: reproduced. After the code's spike and trial minimums (23 A1 and 9 mPFC units kept), none of the four regressions of the anticipatory change on tuning is significant (r from -0.21 to 0.51, p from 0.16 to 0.87). This absence has little power: with 9 mPFC units only a correlation of 0.82 or more would be detected with 80% power (0.56 for 23 A1 units), and the 95% intervals of r are wide (mPFC -0.77 to 0.52 and -0.23 to 0.88).

figs5hi-stimulus-pairs¶

No stimulus pair shows a greater change in evoked response between blocks than the others, with or without baseline subtraction, and in absolute value; and no stimulus pair's change differs from zero.

As 6-1-evoked/main5.py: per responsive unit and stimulus pair, the square root of the mean evoked rate on hits in pitch discrimination minus that in localization; baseline-subtracted as the square root of the evoked rate minus the square root of the block's hold rate. Kruskal-Wallis across the four pairs per region, raw and baseline-subtracted, and on absolute values; Wilcoxon signed-rank (scipy's default, as the code) against zero per pair, Benjamini-Hochberg over the four pairs.

In [37]:
hi_rows = []
for ul, u in RESP.iterrows():
    e = EVK[ul]
    rec = {"ulabel": ul, "region": u.region}
    for s in NOBLOCK:
        lb = np.sqrt(e[s + "_lc"].mean() / u.evok_dt); pb = np.sqrt(e[s + "_pc"].mean() / u.evok_dt)
        rec[("raw", s)] = pb - lb
        rec[("subhold", s)] = (pb - np.sqrt(u.PB_hz)) - (lb - np.sqrt(u.LB_hz))
    hi_rows.append(rec)
HI = pd.DataFrame(hi_rows).set_index("ulabel")
tests = []
for reg in ["A1", "PFC"]:
    g = HI[HI.region == reg]
    for kind in ["raw", "subhold"]:
        for take_abs in [False, True]:
            vals = [np.abs(g[(kind, s)]) if take_abs else g[(kind, s)] for s in NOBLOCK]
            tests.append({"region": reg, "kind": kind, "abs": take_abs, "test": "Kruskal-Wallis", "pair": "all",
                          "p": stats.kruskal(*vals).pvalue, "n": len(g)})
            if not take_abs:
                ps = [stats.wilcoxon(v).pvalue for v in vals]
                for s, p, pa, v in zip(NOBLOCK, ps, pfc1.bh(ps), vals):
                    tests.append({"region": reg, "kind": kind, "abs": False, "test": "Wilcoxon vs 0 (BH)", "pair": s,
                                  "p": pa, "n": len(g), "median": float(np.median(v))})
TESTS = pd.DataFrame(tests)
print(TESTS.round(4).to_string(index=False))
print("Tests with p < 0.05:", int((TESTS.p < 0.05).sum()), "of", len(TESTS))
region    kind   abs               test  pair      p  n  median
    A1     raw False     Kruskal-Wallis   all 0.9210 49     NaN
    A1     raw False Wilcoxon vs 0 (BH) le_hi 0.4353 49  0.2972
    A1     raw False Wilcoxon vs 0 (BH) ri_hi 0.4353 49  0.2252
    A1     raw False Wilcoxon vs 0 (BH) le_lo 0.4353 49  0.0000
    A1     raw False Wilcoxon vs 0 (BH) ri_lo 0.1171 49  0.2741
    A1     raw  True     Kruskal-Wallis   all 0.0611 49     NaN
    A1 subhold False     Kruskal-Wallis   all 0.8470 49     NaN
    A1 subhold False Wilcoxon vs 0 (BH) le_hi 0.9921 49  0.1579
    A1 subhold False Wilcoxon vs 0 (BH) ri_hi 0.9921 49 -0.1328
    A1 subhold False Wilcoxon vs 0 (BH) le_lo 0.9921 49 -0.0132
    A1 subhold False Wilcoxon vs 0 (BH) ri_lo 0.9921 49  0.0630
    A1 subhold  True     Kruskal-Wallis   all 0.1730 49     NaN
   PFC     raw False     Kruskal-Wallis   all 0.1131 31     NaN
   PFC     raw False Wilcoxon vs 0 (BH) le_hi 0.2483 31  0.1254
   PFC     raw False Wilcoxon vs 0 (BH) ri_hi 0.2081 31 -0.3489
   PFC     raw False Wilcoxon vs 0 (BH) le_lo 0.7189 31 -0.1562
   PFC     raw False Wilcoxon vs 0 (BH) ri_lo 0.7189 31  0.0000
   PFC     raw  True     Kruskal-Wallis   all 0.2323 31     NaN
   PFC subhold False     Kruskal-Wallis   all 0.0828 31     NaN
   PFC subhold False Wilcoxon vs 0 (BH) le_hi 0.1519 31  0.2611
   PFC subhold False Wilcoxon vs 0 (BH) ri_hi 0.1519 31 -0.6336
   PFC subhold False Wilcoxon vs 0 (BH) le_lo 0.6079 31  0.3314
   PFC subhold False Wilcoxon vs 0 (BH) ri_lo 0.8092 31  0.0394
   PFC subhold  True     Kruskal-Wallis   all 0.8050 31     NaN
Tests with p < 0.05: 0 of 24

Result: reproduced. None of the 24 tests gives p below 0.05: the Kruskal-Wallis tests across stimulus pairs give p from 0.061 to 0.92, raw, baseline-subtracted and absolute, and the Wilcoxon tests of each pair against zero adjusted p from 0.12 to 0.99.

Head angle¶

figs2i-head-angle¶

The rat's head angle during the center poke differs between blocks by about 30 degrees, 26.9, 36.6 and 24.1 degrees in the three scored sessions.

As 3-5-vidtrack/main0.py and main1.py: the head angle of each scored trial (degrees), joined to the trials of the hold analysis (M2: hits of blocks 2 and 4 with a hold over 50 ms); the difference of the block means per session, compared with the three reported values as a sorted set.

In [38]:
ANG = {s: pfc1.load_head_angles(s) for s in pfc1.VIDTRACK_SESSIONS}
ang_rows = []
for s, a in ANG.items():
    d = S[s]
    lb = pfc1.hold_trials(d["trials"], d["rat"], block=2, outcome="hit").index
    pb = pfc1.hold_trials(d["trials"], d["rat"], block=4, outcome="hit").index
    j = a.join(pd.Series(np.where(a.index.isin(lb), "LB", np.where(a.index.isin(pb), "PB", None)), index=a.index, name="block"))
    j = j.dropna(subset=["block", "angl"])
    ang_rows.append({"session": s, "scored_trials": len(a), "in_hold_analysis": len(j), "LB_mean": j[j.block == "LB"].angl.mean(),
                     "PB_mean": j[j.block == "PB"].angl.mean(), "angle_range": f"{a.angl.min():.1f} to {a.angl.max():.1f}"})
    ANG[s] = j
ANGT = pd.DataFrame(ang_rows).set_index("session")
ANGT["diff_LB_minus_PB"] = ANGT.LB_mean - ANGT.PB_mean
print(ANGT.round(2).to_string())
got = np.sort(np.abs(ANGT.diff_LB_minus_PB.to_numpy())); exp = np.sort([26.9, 36.6, 24.1])
print("sorted |differences|:", np.round(got, 2), "expected", exp, "within 10% each:", (np.abs(got - exp) <= exp / 10).tolist())
                           scored_trials  in_hold_analysis  LB_mean  PB_mean    angle_range  diff_LB_minus_PB
session                                                                                                      
CR24A_121022_001_behaving            934               768     3.17    30.09  -23.9 to 55.0            -26.92
CR20B_120602_001_behaving            662               565    -5.91    30.68  -28.9 to 59.0            -36.60
CR17B_110803_001_behaving            440               207    -1.49    22.57  -30.1 to 52.1            -24.07
sorted |differences|: [24.07 26.92 36.6 ] expected [24.1 26.9 36.6] within 10% each: [True, True, True]

Result: reproduced. The localization minus pitch discrimination differences of mean head angle are -26.92, -36.60 and -24.07 degrees in CR24A_121022, CR20B_120602 and CR17B_110803; their sizes, sorted, are within tolerance of 24.1, 26.9 and 36.6 degrees. The paper's order of values matches this order of sessions.

figs2kl-s3kl-fev¶

For most rule-encoding neurons, block explains far more of the hold-period variance than head angle; the median fraction explained by block is 94.1% in mPFC and 83.0% in A1 (head angle 5.9% and 17.0%), and only 3 of 16 mPFC and 1 A1 neuron are mostly explained by head angle.

As 3-5-vidtrack/main7.py: rule-encoding units of the three sessions; per unit a type II ANOVA of the square root of hold counts on head angle plus block; the FEV of a factor is its sum of squares over the sum for both. The A1 unit whose overall F-test gives p > 0.05 is left out (Supplement).

In [39]:
fev_rows, FULL = [], {}
for ul, u in ENCU[ENCU.session.isin(pfc1.VIDTRACK_SESSIONS)].iterrows():
    j = ANG[u.session]
    counts = pd.Series(np.r_[u.LB_counts, u.PB_counts], index=np.r_[u.LB_trials, u.PB_trials])
    df = j.join(counts.rename("counts"), how="inner").dropna(subset=["counts"])
    df["sqrt_counts"] = np.sqrt(df.counts)
    FULL[ul] = df
    fit = smf.ols("sqrt_counts ~ angl + C(block)", data=df).fit()
    aov = sm.stats.anova_lm(fit, typ=2)
    ssa, ssb = aov.loc["angl", "sum_sq"], aov.loc["C(block)", "sum_sq"]
    fev_rows.append({"ulabel": ul, "region": u.region, "session": u.session, "n_trials": len(df),
                     "fev_block": 100 * ssb / (ssa + ssb), "fev_angl": 100 * ssa / (ssa + ssb), "pF": fit.f_pvalue})
FEV = pd.DataFrame(fev_rows).set_index("ulabel")
print(FEV.round(4).sort_values(["region", "fev_angl"]).to_string())
for reg in ["PFC", "A1"]:
    g = FEV[FEV.region == reg]; gk = g[g.pF <= 0.05]
    print(f"{reg}: units {len(g)}, overall F p > 0.05: {int((g.pF > 0.05).sum())}; after dropping them, median FEV block "
          f"{gk.fev_block.median():.1f}%, head angle {gk.fev_angl.median():.1f}%; head-angle FEV > 50%: {int((gk.fev_angl > 50).sum())}; "
          f"with all units: block {g.fev_block.median():.1f}%, angle {g.fev_angl.median():.1f}%, > 50%: {int((g.fev_angl > 50).sum())}")
                              region                    session  n_trials  fev_block  fev_angl      pF
ulabel                                                                                                
CR24A_121022_001_behaving-511     A1  CR24A_121022_001_behaving       768    97.2757    2.7243  0.0000
CR17B_110803_001_behaving-343     A1  CR17B_110803_001_behaving       207    97.1250    2.8750  0.0004
CR17B_110803_001_behaving-339     A1  CR17B_110803_001_behaving       207    96.3404    3.6596  0.0209
CR24A_121022_001_behaving-610     A1  CR24A_121022_001_behaving       768    84.7272   15.2728  0.1290
CR20B_120602_001_behaving-712     A1  CR20B_120602_001_behaving       565    83.0156   16.9844  0.0000
CR20B_120602_001_behaving-612     A1  CR20B_120602_001_behaving       565    70.0128   29.9872  0.0000
CR17B_110803_001_behaving-340     A1  CR17B_110803_001_behaving       207    68.5329   31.4671  0.0115
CR20B_120602_001_behaving-606     A1  CR20B_120602_001_behaving       565    33.9374   66.0626  0.0000
CR24A_121022_001_behaving-112    PFC  CR24A_121022_001_behaving       768    99.6105    0.3895  0.0000
CR24A_121022_001_behaving-122    PFC  CR24A_121022_001_behaving       768    98.9473    1.0527  0.0000
CR24A_121022_001_behaving-222    PFC  CR24A_121022_001_behaving       768    98.6634    1.3366  0.0000
CR24A_121022_001_behaving-411    PFC  CR24A_121022_001_behaving       768    98.5630    1.4370  0.0001
CR24A_121022_001_behaving-102    PFC  CR24A_121022_001_behaving       768    98.3632    1.6368  0.0006
CR24A_121022_001_behaving-209    PFC  CR24A_121022_001_behaving       768    98.0440    1.9560  0.0000
CR24A_121022_001_behaving-116    PFC  CR24A_121022_001_behaving       768    96.5896    3.4104  0.0000
CR20B_120602_001_behaving-222    PFC  CR20B_120602_001_behaving       565    96.3886    3.6114  0.0000
CR24A_121022_001_behaving-408    PFC  CR24A_121022_001_behaving       768    91.8255    8.1745  0.0000
CR24A_121022_001_behaving-111    PFC  CR24A_121022_001_behaving       768    87.2900   12.7100  0.0088
CR24A_121022_001_behaving-417    PFC  CR24A_121022_001_behaving       768    71.2436   28.7564  0.0000
CR20B_120602_001_behaving-437    PFC  CR20B_120602_001_behaving       565    68.4676   31.5324  0.0000
CR20B_120602_001_behaving-223    PFC  CR20B_120602_001_behaving       565    51.7679   48.2321  0.0061
CR24A_121022_001_behaving-311    PFC  CR24A_121022_001_behaving       768    31.9706   68.0294  0.0001
CR24A_121022_001_behaving-221    PFC  CR24A_121022_001_behaving       768    25.4944   74.5056  0.0000
CR20B_120602_001_behaving-439    PFC  CR20B_120602_001_behaving       565     9.4697   90.5303  0.0000
PFC: units 16, overall F p > 0.05: 0; after dropping them, median FEV block 94.1%, head angle 5.9%; head-angle FEV > 50%: 3; with all units: block 94.1%, angle 5.9%, > 50%: 3
A1: units 8, overall F p > 0.05: 1; after dropping them, median FEV block 83.0%, head angle 17.0%; head-angle FEV > 50%: 1; with all units: block 83.9%, angle 16.1%, > 50%: 1

Result: reproduced. Over 16 mPFC units the median FEV is 94.1% for block and 5.9% for head angle, and 3 units have head-angle FEV above 50%. In A1 one of 8 units has an overall F-test p > 0.05 (0.129); without it the medians are 83.0% and 17.0% and one unit is above 50%. All values match the paper.

posture-equalized-sign¶

On posture-equalized trials the rule encoding persists; its population spread (0.471 in mPFC, 0.318 in A1) exceeds that of shuffles (p < 0.005), and only 1 of 16 mPFC and 0 of 8 A1 cells switch preferred block (binomial p = 0.0005 and 0.008).

As 3-5-vidtrack/main3.py to main5.py: per session, from the first unit's trials, the localization trials with the highest head angles and the pitch discrimination trials with the lowest, the largest equal number for which the localization mean stays above the pitch discrimination mean (the code's loop stops at the first number where it does not, less one). Rule encoding is log10 of the pitch discrimination over localization mean count; PRE is the scaled MAD over units, centered on the median as statsmodels' robust.mad (stand_mad) computes it; the code's comment says its statsmodels did not subtract the median, so the uncentered MAD is a variant; 10000 shuffles of block labels among the posture-equalized trials, p = (shuffles with a larger PRE + 1) / 10000. A cell switches when the sign of its posture-equalized rule encoding differs from that on all trials; two-sided binomial test of the switch count.

In [40]:
rng_pe = np.random.default_rng(3505)
SUBIDX = {}
for ul, df in FULL.items():
    s = ENCU.loc[ul, "session"]
    if s in SUBIDX:
        continue
    lbs = df[df.block == "LB"].sort_values("angl", kind="mergesort"); pbs = df[df.block == "PB"].sort_values("angl", kind="mergesort")
    for n in range(1, len(df)):
        if lbs.angl.to_numpy()[-n:].mean() < pbs.angl.to_numpy()[:n].mean():
            break
    n -= 1
    SUBIDX[s] = {"LB": lbs.index.to_numpy()[-n:], "PB": pbs.index.to_numpy()[:n]}
    print(f"{s}: {n} posture-equalized trials per block; head-angle means LB {df.loc[SUBIDX[s]['LB'], 'angl'].mean():.2f}, "
          f"PB {df.loc[SUBIDX[s]['PB'], 'angl'].mean():.2f} degrees")
pe_rows, FAKE = [], {}
for ul, df in FULL.items():
    u = ENCU.loc[ul]; si = SUBIDX[u.session]
    c = df.counts
    sub_lb, sub_pb = c.loc[si["LB"]], c.loc[si["PB"]]
    rest = df.drop(index=np.r_[si["LB"], si["PB"]])
    pool = np.r_[sub_lb.to_numpy(), sub_pb.to_numpy()]; nl = len(sub_lb)
    perm = np.argsort(rng_pe.random((10000, len(pool))), axis=1)
    fake = pool[perm]
    FAKE[ul] = fake[:, nl:].mean(1) / fake[:, :nl].mean(1)
    pe_rows.append({"ulabel": ul, "region": u.region, "rdiff": u.mPB / u.mLB, "sub_rdiff": sub_pb.mean() / sub_lb.mean(),
                    "nsub_rdiff": rest[rest.block == "PB"].counts.mean() / rest[rest.block == "LB"].counts.mean()})
PE = pd.DataFrame(pe_rows).set_index("ulabel")
PE["switch"] = np.sign(np.log10(PE.sub_rdiff)) != np.sign(np.log10(PE.rdiff))
for reg, exp in [("PFC", 0.471), ("A1", 0.318)]:
    g = PE[PE.region == reg]
    fk = np.log10(np.array([FAKE[u] for u in g.index]))
    for name, f in [("centered (statsmodels robust.mad)", pfc1.stand_mad_centered), ("uncentered (variant)", pfc1.stand_mad_uncentered)]:
        real = f(np.log10(g.sub_rdiff))
        sh = f(fk, axis=0)
        p = (np.sum(sh > real) + 1) / fk.shape[1]
        print(f"{reg} {name}: PRE {real:.3f} (expected {exp} +/- {exp / 10:.4f}), all-trials PRE {f(np.log10(g.rdiff)):.3f}, "
              f"non-equalized PRE {f(np.log10(g.nsub_rdiff)):.3f}; shuffle PRE median {np.median(sh):.3f}, p = {p:.4f}; "
              f"non-finite shuffles {int((~np.isfinite(sh)).sum())}")
    k = int(g.switch.sum())
    print(f"{reg}: {k} of {len(g)} cells switch; two-sided binomial p = {stats.binomtest(k, len(g), 0.5).pvalue:.4f}")
CR17B_110803_001_behaving: 39 posture-equalized trials per block; head-angle means LB 10.51, PB 10.28 degrees
CR20B_120602_001_behaving: 33 posture-equalized trials per block; head-angle means LB 11.44, PB 10.87 degrees
CR24A_121022_001_behaving: 103 posture-equalized trials per block; head-angle means LB 15.98, PB 15.97 degrees
PFC centered (statsmodels robust.mad): PRE 0.471 (expected 0.471 +/- 0.0471), all-trials PRE 0.345, non-equalized PRE 0.398; shuffle PRE median 0.098, p = 0.0001; non-finite shuffles 0
PFC uncentered (variant): PRE 0.327 (expected 0.471 +/- 0.0471), all-trials PRE 0.462, non-equalized PRE 0.506; shuffle PRE median 0.103, p = 0.0001; non-finite shuffles 0
PFC: 1 of 16 cells switch; two-sided binomial p = 0.0005
A1 centered (statsmodels robust.mad): PRE 0.318 (expected 0.318 +/- 0.0318), all-trials PRE 0.372, non-equalized PRE 0.440; shuffle PRE median 0.087, p = 0.0001; non-finite shuffles 0
A1 uncentered (variant): PRE 0.343 (expected 0.318 +/- 0.0318), all-trials PRE 0.373, non-equalized PRE 0.430; shuffle PRE median 0.097, p = 0.0002; non-finite shuffles 0
A1: 0 of 8 cells switch; two-sided binomial p = 0.0078

Result: reproduced. On the posture-equalized trials (39, 33 and 103 per block in the three sessions, with block head-angle means within 0.6 degrees), the PRE is 0.471 in mPFC and 0.318 in A1, the paper's values, and the fraction of shuffles with a larger PRE is 0.0001 and 0.0001 in the two regions, below 0.005. One of 16 mPFC cells and none of 8 A1 cells switch preferred block, with binomial p = 0.0005 and 0.0078. The uncentered MAD (variant) gives 0.327 and 0.343.

posture-equalized-magnitude¶

The mean magnitude of rule encoding is not significantly altered on posture-equalized trials, in mPFC or A1.

Absolute rule encoding |log10 ratio| on posture-equalized and on the other trials, Wilcoxon signed-rank per region (M5). The code's own test (main5.py), the signed log ratio per region and preferred block, is a variant.

In [41]:
for reg in ["PFC", "A1"]:
    g = PE[PE.region == reg]
    a, b = np.abs(np.log10(g.sub_rdiff)), np.abs(np.log10(g.nsub_rdiff))
    print(f"{reg}: mean |log ratio| posture-equalized {a.mean():.3f}, other trials {b.mean():.3f}, change {(a - b).mean():+.3f}; "
          f"signed-rank p = {pfc1.signedrank_r(b, a):.3f} (n = {len(g)}); 95% CI of the mean change "
          f"{(a - b).mean() - stats.t.ppf(0.975, len(g) - 1) * stats.sem(a - b):+.3f} to "
          f"{(a - b).mean() + stats.t.ppf(0.975, len(g) - 1) * stats.sem(a - b):+.3f}; lower on posture-equalized trials in "
          f"{int((a < b).sum())} of {len(g)} cells")
    for pref, gg in g.groupby(np.where(g.rdiff > 1, "PB", "LB")):
        print(f"   variant, {pref}-preferring (n = {len(gg)}): signed p = {pfc1.signedrank_r(np.log10(gg.nsub_rdiff), np.log10(gg.sub_rdiff)):.3f}")
PFC: mean |log ratio| posture-equalized 0.308, other trials 0.418, change -0.110; signed-rank p = 0.059 (n = 16); 95% CI of the mean change -0.237 to +0.016; lower on posture-equalized trials in 11 of 16 cells
   variant, LB-preferring (n = 6): signed p = 0.093
   variant, PB-preferring (n = 10): signed p = 0.221
A1: mean |log ratio| posture-equalized 0.218, other trials 0.401, change -0.183; signed-rank p = 0.141 (n = 8); 95% CI of the mean change -0.442 to +0.076; lower on posture-equalized trials in 6 of 8 cells
   variant, LB-preferring (n = 4): signed p = 0.361
   variant, PB-preferring (n = 4): signed p = 0.361

Result: reproduced. The signed-rank test finds no change in the magnitude of rule encoding, p = 0.059 in mPFC (16 cells) and 0.141 in A1 (8 cells). The magnitude is smaller on the posture-equalized trials in both (mean |log10 ratio| 0.308 against 0.418, and 0.218 against 0.401), so the absence rests on a test of few cells; the code's per-preference variant gives p from 0.09 to 0.36. The 95% intervals of the mean change in |log10 ratio| are -0.237 to +0.016 in mPFC and -0.442 to +0.076 in A1. In mPFC a reduction of up to about half the magnitude (0.237 of 0.418) is not excluded; in A1 the interval reaches beyond the whole magnitude (0.442 against 0.401), so even a complete loss of rule encoding on posture-equalized trials is not excluded there.

Disruption of mPFC¶

fig7-disruption-by-block¶

Electrical disruption of mPFC impairs performance; across sessions the impairment is significant in pitch discrimination for all three rats and in localization for two of three.

As 7-1-zap/zap.py and main1.py on miscellaneous/zap/TI_d: per session, the fraction of hits on disruption (zap 1) and control (zap 0) trials of block 2 and of block 4, munged trials dropped, the code's minimum of 5 trials per side; per rat (CR25A Z1, CR28A Z2, CR28B Z3), a two-sided binomial test of the number of sessions with control above disruption performance. Dropping nonrandom trials is a variant.

In [42]:
TI_d = pfc1.load_old_pickle(pfc1.read_member(pfc1.ROOT + "miscellaneous/zap/TI_d"))
ZRAT = {"CR25A": "Z1", "CR28A": "Z2", "CR28B": "Z3"}
print("Sessions per rat:", pd.Series([k[:5] for k in TI_d]).value_counts().sort_index().to_dict())
print("Columns:", list(next(iter(TI_d.values())).columns))
print("zap values:", sorted(set().union(*[set(t.zap.unique()) for t in TI_d.values()])),
      "; fraction of zap trials (munged dropped, non-cue blocks):",
      round(np.mean(np.concatenate([t[(~t.is_munged.astype(bool)) & t.block.isin([2, 4])].zap.to_numpy() for t in TI_d.values()])), 3))

def zap_table(drop_nonrandom):
    rows = []
    for sess, TI in TI_d.items():
        t = TI[~TI.is_munged.astype(bool)]
        t = t[t.outcome.isin(["hit", "error", "wrong_port"])]
        if drop_nonrandom:
            t = t[t.nonrandom == 0]
        hit = (t.outcome == "hit").astype(int)
        for block in [2, 4]:
            for gng in [None, "go", "nogo"]:
                m = (t.block == block) & ((t.go_or_nogo == gng) if gng else True)
                z, c = hit[m & (t.zap == 1)], hit[m & (t.zap == 0)]
                if len(z) < 5 or len(c) < 5:
                    continue
                rows.append({"session": sess, "rat": sess[:5], "block": block, "gng": gng or "all",
                             "zap_m": z.mean(), "ctl_m": c.mean(), "n_zap": len(z), "n_ctl": len(c)})
    return pd.DataFrame(rows)

def rat_tests(Z):
    out = []
    for (rat, block, gng), g in Z.groupby(["rat", "block", "gng"]):
        k = int((g.ctl_m > g.zap_m).sum())
        out.append({"rat": ZRAT[rat], "block": {2: "localization", 4: "pitch discrimination"}[block], "gng": gng,
                    "sessions": len(g), "impaired_sessions": k, "mean_ctl_minus_zap": (g.ctl_m - g.zap_m).mean(),
                    "p": stats.binomtest(k, len(g), 0.5).pvalue})
    return pd.DataFrame(out)

ZT = {dn: zap_table(dn) for dn in [False, True]}
RT7 = {dn: rat_tests(ZT[dn]) for dn in [False, True]}
for dn in [False, True]:
    print(f"\n{'nonrandom trials dropped (variant)' if dn else 'as the code (nonrandom kept)'}:")
    print(RT7[dn][RT7[dn].gng == "all"].round(4).to_string(index=False))
Sessions per rat: {'CR25A': 6, 'CR28A': 8, 'CR28B': 8}
Columns: ['correct_side', 'stim_number', 'nonrandom', 'outcome', 'go_or_nogo', 'block', 'stim_name', 'zap', 'is_munged']
zap values: [np.int64(0), np.int64(1)] ; fraction of zap trials (munged dropped, non-cue blocks): 0.201

as the code (nonrandom kept):
rat                block gng  sessions  impaired_sessions  mean_ctl_minus_zap      p
 Z1         localization all         6                  5              0.0543 0.2188
 Z1 pitch discrimination all         6                  6              0.1908 0.0312
 Z2         localization all         8                  8              0.1244 0.0078
 Z2 pitch discrimination all         8                  8              0.1872 0.0078
 Z3         localization all         8                  8              0.2748 0.0078
 Z3 pitch discrimination all         8                  8              0.1302 0.0078

nonrandom trials dropped (variant):
rat                block gng  sessions  impaired_sessions  mean_ctl_minus_zap      p
 Z1         localization all         6                  5              0.0543 0.2188
 Z1 pitch discrimination all         6                  6              0.1908 0.0312
 Z2         localization all         8                  8              0.1244 0.0078
 Z2 pitch discrimination all         8                  8              0.1872 0.0078
 Z3         localization all         8                  8              0.2748 0.0078
 Z3 pitch discrimination all         8                  8              0.1302 0.0078

Result: reproduced. Control performance exceeds disruption performance in pitch discrimination in 6 of 6, 8 of 8 and 8 of 8 sessions of Z1, Z2 and Z3 (binomial p = 0.031, 0.0078, 0.0078), and in localization in 5 of 6 (p = 0.22), 8 of 8 and 8 of 8 (p = 0.0078 each): significant in pitch discrimination for all three rats and in localization for two. Session counts are 6, 8 and 8. Dropping nonrandom trials changes nothing.

fig7c-disruption-nogo¶

Disruption impairs nogo trials in particular; every rat is significantly impaired on nogo trials in one block or the other, and Z2 also on localization go trials.

As fig7-disruption-by-block, split by go and nogo in each block (compute_by_block_and_gonogo).

In [43]:
for dn in [False, True]:
    r = RT7[dn][RT7[dn].gng != "all"]
    print(f"\n{'nonrandom trials dropped (variant)' if dn else 'as the code (nonrandom kept)'}:")
    print(r.round(4).to_string(index=False))
    nogo_ok = r[(r.gng == "nogo") & (r.p < 0.05)].groupby("rat").size().reindex(["Z1", "Z2", "Z3"]).fillna(0)
    go_sig = r[(r.gng == "go") & (r.p < 0.05)][["rat", "block"]].values.tolist()
    print("rats with a significant nogo impairment in some block:", nogo_ok.to_dict(), "; significant go cases:", go_sig)
as the code (nonrandom kept):
rat                block  gng  sessions  impaired_sessions  mean_ctl_minus_zap      p
 Z1         localization   go         6                  3             -0.0025 1.0000
 Z1         localization nogo         6                  4              0.0932 0.6875
 Z1 pitch discrimination   go         6                  4              0.1432 0.6875
 Z1 pitch discrimination nogo         6                  6              0.2416 0.0312
 Z2         localization   go         8                  8              0.1995 0.0078
 Z2         localization nogo         8                  6              0.1244 0.2891
 Z2 pitch discrimination   go         8                  5              0.0896 0.7266
 Z2 pitch discrimination nogo         8                  8              0.2711 0.0078
 Z3         localization   go         8                  3             -0.0017 0.7266
 Z3         localization nogo         8                  8              0.5640 0.0078
 Z3 pitch discrimination   go         8                  3              0.0352 0.7266
 Z3 pitch discrimination nogo         8                  7              0.1974 0.0703
rats with a significant nogo impairment in some block: {'Z1': 1, 'Z2': 1, 'Z3': 1} ; significant go cases: [['Z2', 'localization']]

nonrandom trials dropped (variant):
rat                block  gng  sessions  impaired_sessions  mean_ctl_minus_zap      p
 Z1         localization   go         6                  3             -0.0025 1.0000
 Z1         localization nogo         6                  4              0.0932 0.6875
 Z1 pitch discrimination   go         6                  4              0.1432 0.6875
 Z1 pitch discrimination nogo         6                  6              0.2416 0.0312
 Z2         localization   go         8                  8              0.1995 0.0078
 Z2         localization nogo         8                  6              0.1244 0.2891
 Z2 pitch discrimination   go         8                  5              0.0896 0.7266
 Z2 pitch discrimination nogo         8                  8              0.2711 0.0078
 Z3         localization   go         8                  3             -0.0017 0.7266
 Z3         localization nogo         8                  8              0.5640 0.0078
 Z3 pitch discrimination   go         8                  3              0.0352 0.7266
 Z3 pitch discrimination nogo         8                  7              0.1974 0.0703
rats with a significant nogo impairment in some block: {'Z1': 1, 'Z2': 1, 'Z3': 1} ; significant go cases: [['Z2', 'localization']]

Result: reproduced. Each rat has a significant nogo impairment in one block (Z1 and Z2 in pitch discrimination, p = 0.031 and 0.0078; Z3 in localization, p = 0.0078), and the only significant go impairment is Z2 in localization (8 of 8 sessions, p = 0.0078).

figs1bc-catch¶

Rats perform as well when the distractor is replaced by a novel neutral sound as on standard trials, so they select the target and do not memorize the four stimulus pairs.

As 2-1-behavres/main05.py on miscellaneous/catch_trial_task: for each rat and each catch stimulus, hits and trials on it against the two standard stimuli with the same target pooled; two-sided Fisher's exact test; all trials of the file, as the code.

In [44]:
COMPG = [["ri_ca_lc", "ri_lo_lc", "ri_hi_lc"], ["le_ca_lc", "le_lo_lc", "le_hi_lc"],
         ["ca_hi_pc", "le_hi_pc", "ri_hi_pc"], ["ca_lo_pc", "le_lo_pc", "ri_lo_pc"]]
catch_rows = []
for rat in ["CR20B", "CR21A"]:
    TI = pfc1.load_old_pickle(pfc1.read_member(pfc1.ROOT + f"miscellaneous/catch_trial_task/{rat}_trials_info"))
    print(rat, TI.shape, "outcomes", TI.outcome.value_counts().to_dict(), "; catch trials", int(TI.stim_name.str.contains("ca").sum()))
    nh = TI.groupby("stim_name").outcome.apply(lambda x: (x == "hit").sum()); nt = TI.groupby("stim_name").size()
    for g in COMPG:
        s0, n0 = nh[g[0]], nt[g[0]]; s1, n1 = nh[g[1]] + nh[g[2]], nt[g[1]] + nt[g[2]]
        p = stats.fisher_exact([[s0, n0 - s0], [s1, n1 - s1]])[1]
        catch_rows.append({"rat": rat, "catch": g[0], "catch_perf": s0 / n0, "n_catch": n0, "standard_perf": s1 / n1, "n_standard": n1, "p": p})
CATCH = pd.DataFrame(catch_rows)
print(CATCH.round(4).to_string(index=False))
print("Tests with p < 0.05:", int((CATCH.p < 0.05).sum()), "of", len(CATCH))
CR20B (390, 8) outcomes {'hit': 351, 'error': 31, 'wrong_port': 8} ; catch trials 51
CR21A (663, 8) outcomes {'hit': 596, 'error': 50, 'wrong_port': 17} ; catch trials 99
  rat    catch  catch_perf  n_catch  standard_perf  n_standard      p
CR20B ri_ca_lc      1.0000       19         0.8333          66 0.1131
CR20B le_ca_lc      0.7500       12         0.8767          73 0.3638
CR20B ca_hi_pc      1.0000        9         0.7872          47 0.1893
CR20B ca_lo_pc      1.0000       11         0.9811          53 1.0000
CR21A ri_ca_lc      0.9545       22         0.9250          80 1.0000
CR21A le_ca_lc      0.9259       27         0.9386         114 0.6823
CR21A ca_hi_pc      0.8235       17         0.8316          95 1.0000
CR21A ca_lo_pc      0.9697       33         0.9368          95 0.6764
Tests with p < 0.05: 0 of 8

Result: reproduced. None of the eight Fisher's exact tests gives p below 0.05 (smallest 0.11, CR20B ri_ca_lc, where catch performance is 1.00 against 0.83). CR20B's file holds one session of 390 trials, 51 of them catch trials; CR21A's 663 trials, 99 catch trials.

fig8-model¶

In the network model with 320 neurons, a task signal alone lets the network perform above 80% correct with a sensory signal-to-noise ratio as low as 0.0625, and 100% at an SNR of 0.25 for virtually any positive task signal.

From the deposited simulation results, as 8-1-model/main1.py: N = 320, the broad (exponentially spaced) task-signal gains, the score over 4 x NT_TEST trials, averaged over simulations and the median taken over repetitions; task 1 (score1b) for positive gains and task 2 (score2b) for the mirrored negative gains. The code labels the curves SNR = 2^-log2(noise level), that is 1 / noise level, the gain/noise reading of the criterion (gain/sqrt(noise) does not give the printed grid of 2^-6 to 2^-2).

In [45]:
t0 = time.time()
resdf = pfc1.load_old_pickle(pfc1.read_member(pfc1.ROOT + "miscellaneous/model/simulation_resdf"))
params = pfc1.load_old_pickle(pfc1.read_member(pfc1.ROOT + "miscellaneous/model/simulation_params.pickle"))
print(f"simulation_resdf: {resdf.shape} rows x columns, read in {time.time() - t0:.0f} s; columns {list(resdf.columns)}")
N_l, noise_l, gains_l, NT = np.asarray(params["N_l"]), np.asarray(params["noise_level_l"]), np.asarray(params["gains_l"]), params["NT_TEST"]
print("N_l", N_l.tolist(), "; noise_level_l", noise_l.tolist(), "; NT_TEST", NT, "; gains", len(gains_l), f"{gains_l.min()} to {gains_l.max()}")
print("SNR (1/noise):", (1 / noise_l).tolist(), "; 1/sqrt(noise):", np.round(1 / np.sqrt(noise_l), 4).tolist())
ggains = np.concatenate([-10 ** (np.linspace(-3, 3, 40))[::-1], 10 ** (np.linspace(-3, 3, 40)), np.linspace(-20, 20, 80)])
assert np.allclose(np.sort(ggains), gains_l)
broad = np.argsort(np.argsort(ggains))[:80]
sub_all = resdf[resdf.nN == int(np.where(N_l == 320)[0][0])]
sub = sub_all[sub_all.ngain.isin(broad)]
del resdf
print("score1b, score2b ranges:", sub.score1b.min(), "to", sub.score1b.max(), ",", sub.score2b.min(), "to", sub.score2b.max(), f"(over 4 x {NT} trials)")
piv = sub.groupby(["n_noise_level", "ngain", "nrep"])[["score1b", "score2b"]].mean() / 4.0 / NT
med = piv.groupby(["n_noise_level", "ngain"]).median()
for snr in [0.0625, 0.25]:
    nl = int(np.where(np.isclose(1 / noise_l, snr))[0][0])
    m = med.loc[nl]
    g = gains_l[m.index.to_numpy()]
    pos1 = m.score1b[g > 0]; neg2 = m.score2b[g < 0]
    print(f"SNR {snr}: task 1 at positive gains, max {pos1.max():.3f}, fraction of gains >= 0.99: {np.mean(pos1 >= 0.99):.2f}, >0.8: {np.mean(pos1 > 0.8):.2f}; "
          f"task 2 at negative gains, max {neg2.max():.3f}, fraction >= 0.99: {np.mean(neg2 >= 0.99):.2f}, >0.8: {np.mean(neg2 > 0.8):.2f}")
    x = g / noise_l[nl]
    inplot = (x > 0) & (x <= 10)
    print(f"   within Figure 8B's plotted range (task signal / noise from 0 to 10, 8-1-model/main1.py set_xlim): "
          f"{int(inplot.sum())} gains, fraction >= 0.99: {np.mean(m.score1b[inplot] >= 0.99):.2f}; "
          f"for task signal / noise >= 0.3: {np.mean(m.score1b[(x >= 0.3) & (x <= 10)] >= 0.99):.2f}")
    print("   task 1 by positive gain:", dict(zip(np.round(g[g > 0], 3)[::4].tolist(), np.round(pos1.to_numpy(), 3)[::4].tolist())))
for nl in range(len(noise_l)):
    m = med.loc[nl]; g = gains_l[m.index.to_numpy()]
    print(f"   SNR {1 / noise_l[nl]:.4g}: best task 1 {m.score1b[g > 0].max():.3f}, best task 2 {m.score2b[g < 0].max():.3f}")

# Variants: the narrow linear gains (linspace -20 to 20), and the share of Figure 8B's positive
# axis (symlog, matplotlib's default linthresh 2, x from 0 to 10) where task 1 is at least 99%.
from matplotlib.scale import SymmetricalLogTransform
narrow = np.argsort(np.argsort(ggains))[80:]
pivn = sub_all[sub_all.ngain.isin(narrow)].groupby(["n_noise_level", "ngain", "nrep"])[["score1b", "score2b"]].mean() / 4.0 / NT
medn = pivn.groupby(["n_noise_level", "ngain"]).median()
tr = SymmetricalLogTransform(10, 2, 1)
for snr in [0.0625, 0.25]:
    nl = int(np.where(np.isclose(1 / noise_l, snr))[0][0])
    m = medn.loc[nl]; g = gains_l[m.index.to_numpy()]
    pos1 = m.score1b[g > 0]
    print(f"SNR {snr}, narrow gains: {int((g > 0).sum())} positive gains ({g[g > 0].min():.2f} to {g.max():.2f}, task signal / noise "
          f"{g[g > 0].min() / noise_l[nl]:.3f} to {g.max() / noise_l[nl]:.2f}); task 1 max {pos1.max():.3f}, fraction >= 0.99: "
          f"{np.mean(pos1 >= 0.99):.2f}, range {pos1.min():.3f} to {pos1.max():.3f}")
    print("   task 1 by positive gain:", dict(zip(np.round(g[g > 0], 2)[::4].tolist(), np.round(pos1.to_numpy(), 3)[::4].tolist())))
    # All positive gains of both ranges, sorted by task signal / noise, on the plotted axis
    mb = pd.concat([med.loc[nl], m]); gb = gains_l[mb.index.to_numpy()]; xb = gb / noise_l[nl]
    keep = (xb > 0) & (xb <= 10)
    order = np.argsort(xb[keep]); xs = xb[keep][order]; ok = (mb.score1b.to_numpy()[keep][order] >= 0.99)
    if not ok[-1]:
        print("   both ranges: task 1 is below 0.99 at the largest plotted x")
        continue
    first_ok_run = xs[np.where(~ok)[0].max() + 1] if (~ok).any() else xs[0]
    y0, y1, y10 = tr.transform([0.0, first_ok_run, 10.0])
    print(f"   both ranges: task 1 >= 0.99 at every sampled x from {first_ok_run:.3f} to 10; share of the positive plotted axis: "
          f"{(y10 - y1) / (y10 - y0):.2f}; share of the linear x range 0 to 10: {(10 - first_ok_run) / 10:.2f}")
simulation_resdf: (14400000, 9) rows x columns, read in 8 s; columns ['ngain', 'nrep', 'nsim', 'score1', 'score1b', 'score2', 'score2b', 'nN', 'n_noise_level']
N_l [640, 320, 160, 120, 80, 60, 40, 30, 20, 10] ; noise_level_l [0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0] ; NT_TEST 100 ; gains 160 -1000.0 to 1000.0
SNR (1/noise): [2.0, 1.0, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125] ; 1/sqrt(noise): [1.4142, 1.0, 0.7071, 0.5, 0.3536, 0.25, 0.1768, 0.125, 0.0884]
score1b, score2b ranges: 0 to 400 , 0 to 400 (over 4 x 100 trials)
SNR 0.0625: task 1 at positive gains, max 0.932, fraction of gains >= 0.99: 0.00, >0.8: 0.28; task 2 at negative gains, max 0.932, fraction >= 0.99: 0.00, >0.8: 0.28
   within Figure 8B's plotted range (task signal / noise from 0 to 10, 8-1-model/main1.py set_xlim): 34 gains, fraction >= 0.99: 0.00; for task signal / noise >= 0.3: 0.00
   task 1 by positive gain: {0.001: 0.61, 0.004: 0.61, 0.017: 0.612, 0.07: 0.618, 0.289: 0.645, 1.194: 0.752, 4.924: 0.93, 20.309: 0.92, 83.768: 0.758, 345.511: 0.5}
SNR 0.25: task 1 at positive gains, max 1.000, fraction of gains >= 0.99: 0.25, >0.8: 0.38; task 2 at negative gains, max 1.000, fraction >= 0.99: 0.25, >0.8: 0.38
   within Figure 8B's plotted range (task signal / noise from 0 to 10, 8-1-model/main1.py set_xlim): 30 gains, fraction >= 0.99: 0.30; for task signal / noise >= 0.3: 1.00
   task 1 by positive gain: {0.001: 0.625, 0.004: 0.628, 0.017: 0.635, 0.07: 0.662, 0.289: 0.772, 1.194: 0.988, 4.924: 1.0, 20.309: 1.0, 83.768: 0.521, 345.511: 0.5}
   SNR 2: best task 1 1.000, best task 2 1.000
   SNR 1: best task 1 1.000, best task 2 1.000
   SNR 0.5: best task 1 1.000, best task 2 1.000
   SNR 0.25: best task 1 1.000, best task 2 1.000
   SNR 0.125: best task 1 1.000, best task 2 1.000
   SNR 0.0625: best task 1 0.932, best task 2 0.932
   SNR 0.03125: best task 1 0.760, best task 2 0.760
   SNR 0.01562: best task 1 0.618, best task 2 0.618
   SNR 0.007812: best task 1 0.540, best task 2 0.542
SNR 0.0625, narrow gains: 40 positive gains (0.25 to 20.00, task signal / noise 0.016 to 1.25); task 1 max 0.932, fraction >= 0.99: 0.00, range 0.642 to 0.932
   task 1 by positive gain: {0.25: 0.642, 2.28: 0.848, 4.3: 0.922, 6.33: 0.932, 8.35: 0.932, 10.38: 0.93, 12.41: 0.928, 14.43: 0.925, 16.46: 0.922, 18.48: 0.922}
   both ranges: task 1 is below 0.99 at the largest plotted x
SNR 0.25, narrow gains: 40 positive gains (0.25 to 20.00, task signal / noise 0.063 to 5.00); task 1 max 1.000, fraction >= 0.99: 0.95, range 0.755 to 1.000
   task 1 by positive gain: {0.25: 0.755, 2.28: 1.0, 4.3: 1.0, 6.33: 1.0, 8.35: 1.0, 10.38: 1.0, 12.41: 1.0, 14.43: 1.0, 16.46: 1.0, 18.48: 1.0}
   both ranges: task 1 >= 0.99 at every sampled x from 0.316 to 10; share of the positive plotted axis: 0.90; share of the linear x range 0 to 10: 0.97

Result: reproduced. With 320 neurons and an SNR of 0.0625 the best positive task signal gives 93.2% correct in both tasks, above 80%. At an SNR of 0.25 task 1 is at least 99% at every sampled task signal over noise from 0.32 to 10, which is 90% of Figure 8B's positive plotted axis (symlog) and 97% of the linear range 0 to 10, and at 38 of the 40 positive gains of the code's narrow linear sweep (95%). Within the plotted range it is below 99% only for task signals under 0.3 times the noise, where task 1 performance runs from about 0.63 at the smallest gains to 0.988 at a gain of 1.194 (task signal / noise 0.30); outside the plotted range it falls for gains of 84 and more (0.52 at 84). Counted over the code's log-spaced broad gains, which crowd near zero, only 25% of the positive gains reach 99% (30% within the plotted range). The outcome reads "most positive task signals" as most of the range of task signals the paper plots, which the narrow sweep confirms; counted per log-spaced sample the second part would not hold.

Summary¶

Claim Outcome
unit-table-link (link) reproduced
fig2a-above-chance reproduced
figs1a-go-better-than-nogo reproduced
fig2d-block-switch reproduced
iti-median reproduced
fig3c-pfc-rule-encoding reproduced
fig4c-a1-rule-encoding reproduced
a1-rule-encoding-not-audresp-dependent reproduced
rule-encoding-effect-size reproduced
fig3ab-pfc-example-units reproduced
fig4ab-a1-example-units reproduced
fig3d-pfc-interference reproduced
fig4d-a1-interference reproduced
figs2c-s3c-hold-by-trial-type reproduced
figs2f-s3f-bidirectional-vs-spont reproduced
figs2gh-s3gh-rt-mt reproduced
fig5ab-single-unit-onset reproduced
fig5c-population-onset reproduced
fig5d-go-nogo reproduced
audresp-prevalence reproduced
figs5cd-evoked-strength reproduced
figs5e-latency reproduced
fig6cd-baseline-evoked-correlation reproduced
evoked-beyond-baseline-rare reproduced
fig6e-decoding reproduced
figs5fg-tuning-vs-rule reproduced
figs5hi-stimulus-pairs reproduced
figs2i-head-angle reproduced
figs2kl-s3kl-fev reproduced
posture-equalized-sign reproduced
posture-equalized-magnitude reproduced
fig7-disruption-by-block reproduced
fig7c-disruption-nogo reproduced
figs1bc-catch reproduced
fig8-model reproduced

How the analysis differs from the paper's. Every analysis follows the paper's code at commit 390b608 where the claims file names it, ported to Python 3 (R's Mann-Whitney and signed-rank tests are reproduced with scipy's normal approximations with continuity correction; Benjamini-Hochberg with statsmodels; logistic regression with scikit-learn's liblinear solver and balanced class weights). The auditory response class and window come from the code's unit table (M4 reading (a)); recomputing them from the spikes as the Supplement describes (reading (b), a variant) gives 46 mPFC and 61 A1 responsive units in place of 31 and 49. Part of the difference comes from rules of the table that the paper does not state (units the table classes "too brief", "lasts too long" or "lasts to end" are responsive under reading (b)), and part from the threshold and trial choices of reading (b): 6 units the table classes "nothing" become responsive, and 13 the table counts as responsive (5 A1, 8 mPFC) are not responsive under reading (b). The single-unit onsets of Figure 5A and 5B match the paper only with the code's smoother, which moves each spike to the 50 ms sample grid; with exact spike times the mPFC median is 0.75 s. They also need the units whose bin just before onset is not significant to be kept, as main4.py keeps them; leaving them out gives 0.65 s in A1, and the outcome is marked as resting on this assumption. The latency difference of Figure S5E rests on the code's windows: recomputed windows give medians of 16.38 and 16.25 ms, which do not differ. The count of evoked changes beyond baseline matches only with the code's Benjamini-Hochberg correction. The model's second condition holds over the plotted range of task signals and the narrow linear sweep, not over the log-spaced samples counted one by one. Bootstrap and shuffle draws use fixed seeds of their own, so their p-values differ from the paper's draws by sampling error.

What was found about the data set. The spike files are pandas 0.10 pickles from Python 2 that current pandas cannot open, and they hold 2977 clusters of which only the 220 well-sorted units listed in the code's table were analysed: without that table the units, their quality and their auditory response windows cannot be identified from the data set. Three sessions have no spike file (their klusters0/ holds a README), and two CR21A sessions carry a second spike file outside klusters0/ with the same spike times but tetrode groups numbered 0 to 7 and different unit numbers. The descriptor names the stimulus column stimulus_name (it is stim_name) and gives a stimulus numbering that the files do not follow. The code's figure index names the units of Figures 4A and 4B the other way round from the legends; after a reader's answer the claims file identifies them by preference, as the legends do.