Reproducing Bech, Dard et al. (eLife) from dandiset 001847¶

Paper: Bech, Dard, Lebert, Smith, Bisi, Renard, Crochet & Petersen, "Retrosplenial cortex enables context-dependent goal-directed sensorimotor transformation", eLife reviewed preprint, doi:10.7554/eLife.109717. Claims: claims/001847/10.7554-elife.109717.yaml, written from the eLife Reviewed Preprint version 1 (30 December 2025), its Methods and figure-supplement legends.

Dataset: DANDI:001847, version 0.260610.1400 (doi:10.48324/dandi.001847/0.260610.1400). The paper cites no dandiset version; this is the only published version and the most recent one, and it is the version the READMEs of the paper's two analysis repositories name. The draft has the same 1497 assets. Every file is streamed; nothing is downloaded.

Outside input: the session lists of the paper's processing code (github.com/LSENS-BMI-EPFL/Bech_Dard_process_NWB at commit 212a6310, configs/session_groups). The claims file selects sessions by these lists, and they are the only record of which mice carry VGAT-ChR2, jRGECO1a, GCaMP6f, tdTomato or GFP, and which sessions are Context Off or muscimol days: the files give the genotype "WT" for every subject but one. They name sessions only, so they are used as labels (with_labels) and their link is tested in session-list-link.

claim tested here
session-list-link (added) tested
expert-sessions, fig1c (3 claims), fig1d, fig1e, fig1g, fig1f, fig1h, supp1c, supp1d tested
fig1i-pupil-larger-wplus, fig1i-posture-before-lick, fig1j-jaw-speed-context, fig3c-jaw-onset tested
fig2c, fig2d, fig2e (2 claims), fig2-no-effect-control-mice, fig2cd-rsc, fig2f run under every reading; blocked where the readings disagree
supp2-muscimol-ws1-rsc tested
fig3e, fig3f, fig3-gcamp-consistent-controls-flat tested on the grid ROI traces
fig3h-rsc-first-context-discrimination tested, ROI part on the grid ROI traces and pixel part on windowed reads of the ΔF/F0 stack
fig4c, fig4d, fig4e, fig4fg, supp4d tested on the grid ROI traces
fig1k-model-accuracy, fig1k-context-strongest-feature, fig1l-shap-whisker-trial-in-block tested (the code's XGBoost model rebuilt)
fig4b (3 claims) blocked, other (the seed-to-pixel analysis was not run in this attempt); a variant on the grid ROI traces is shown
supp3c-rsc-projects-to-wm blocked, data_missing
In [1]:
import time; T0_NB = time.time()  # notebook start, for the run-time estimate of fig4b
import numpy as np, pandas as pd, matplotlib.pyplot as plt
from scipy import stats
import bech
pd.set_option('display.width', 200); pd.set_option('display.max_columns', 40)
A = bech.list_assets()
T, E, M = bech.load_trials(A)
LISTS = {n: bech.code_list(n) for n in [
    'sessions_Context_sessions', 'sessions_Context_sessions_expert', 'sessions_Context_sessions_opto',
    'sessions_Context_sessions_opto_control', 'sessions_Context_sound_off', 'sessions_Context_sound_off_only',
    'sessions_Context_muscimol_wS1', 'sessions_Context_muscimol_fpS1', 'sessions_Context_muscimol_RSC',
    'sessions_Context_ringer_wS1', 'sessions_Context_ringer_fpS1', 'sessions_Context_ringer_RSC',
    'sessions_Context_sessions_expert_WF_jrGECO', 'sessions_Context_sessions_expert_WF_gcamp',
    'sessions_Context_sessions_expert_WF_tomato', 'sessions_Context_sessions_expert_WF_GFP',
    'sessions_Context_sessions_wf_opto', 'sessions_Context_sessions_wf_opto_photoactivation',
    'session_context_expert_behaviour_model']}

Data check¶

In [2]:
print('assets', len(A), 'subjects', A.subject.nunique(), 'by kind:', A.kind.value_counts().to_dict())
print('files whose trial table could not be read:', M.error.notna().sum() if 'error' in M else 0)
if 'error' in M: print(M.loc[M.error.notna(), ['session_id', 'error']].to_string())
print('session types (experiment_description):', M.session_type.value_counts().to_dict())
print('genotype field:', M.genotype.value_counts().to_dict())
print('session_description prefixes:', M.session_description.str.replace(r'[-+]?\d+$', '', regex=True).value_counts().to_dict())
print('trials', len(T), 'sessions with trials', T.session_id.nunique(), 'mice', T.mouse_id.nunique())
print('trial types', T.trial_type.value_counts().to_dict(), '| context', T.context.value_counts().to_dict(),
      '| noise', T.context_background.value_counts().to_dict())
print('perf code x trial type'); print(pd.crosstab(T.perf, T.trial_type))
print('early_lick equals perf 6 for', (T.early_lick.eq(1) == T.perf.eq(6)).mean().round(4), 'of trials')
print('lick_flag 1 with no lick_time:', ((T.lick_flag == 1) & T.lick_time.isna()).sum(),
      '| lick_time - stim_time on lick trials without early lick (s):',
      (T.lick_time - T.stim_time)[(T.lick_flag == 1) & (T.early_lick == 0) & (T.trial_type != 'no_stim_trial')].describe().round(3).to_dict())
print('whisker amplitude', T.loc[T.trial_type == 'whisker_trial', 'whisker_stim_amplitude'].value_counts().head().to_dict(),
      '| whisker duration (ms)', T.loc[T.trial_type == 'whisker_trial', 'whisker_stim_duration'].value_counts().head().to_dict())
print('auditory frequency', T.loc[T.trial_type == 'auditory_trial', 'auditory_stim_frequency'].value_counts().head().to_dict(),
      '| duration (ms)', T.loc[T.trial_type == 'auditory_trial', 'auditory_stim_duration'].value_counts().head().to_dict())
# reward available only for whisker trials in W+ and for auditory trials
print('reward_available by trial type and context'); print(T.groupby(['trial_type', 'context']).reward_available.mean().round(3))
# noise to context: each mouse has one W+ noise
nz = T.groupby(['mouse_id', 'context']).context_background.agg(lambda x: x.value_counts(normalize=True).iloc[0]).unstack()
print('fraction of trials with the majority noise per mouse and context, min:', nz.min().round(3).to_dict())
# epochs against trial context
E2 = E.copy(); E2['ctx'] = (E2.epoch == 'rewarded').astype(int)
print('epochs', len(E2), '| epoch duration (s)', (E2.stop - E2.start).describe().round(1).to_dict())
chk = []
for sid, g in T.groupby('session_id'):
    e = E2[E2.session_id == sid]
    if len(e) == 0: continue
    i = np.searchsorted(e.start.values[np.argsort(e.start.values)], g.start_time.values, side='right') - 1
    es = e.sort_values('start')
    ctx = np.where(i >= 0, es.ctx.values[np.clip(i, 0, None)], -1)
    chk.append((ctx == g.context.values).mean())
print('fraction of trials whose context matches the epoch they fall in: median', np.median(chk).round(4), 'min', np.min(chk).round(4), 'sessions', len(chk))
blocks_e = E2.groupby('session_id').size(); blocks_t = T.groupby('session_id').block.max() + 1
print('blocks per session, epochs against context runs of the trial table: equal in',
      (blocks_e.reindex(blocks_t.index) == blocks_t).mean().round(3), 'of sessions')
# duplicates
h = T.groupby('session_id').start_time.apply(lambda x: hash(tuple(np.round(x.values, 3))))
print('sessions with identical trial times as another session:', h.duplicated(keep=False).sum())
assets 1497 subjects 73 by kind: {'behavior': 1051, 'behavior+image+ophys': 320, 'behavior+image': 90, 'behavior+ophys': 36}
files whose trial table could not be read: 3
                session_id                                                                                      error
284  PB185_20240801_095038  KeyError("Unable to synchronously open object (object 'BehavioralEpochs' doesn't exist)")
309  PB186_20240801_110359  KeyError("Unable to synchronously open object (object 'BehavioralEpochs' doesn't exist)")
397  PB189_20240902_155436  KeyError("Unable to synchronously open object (object 'BehavioralEpochs' doesn't exist)")
session types (experiment_description): {'behaviour_only_session': 947, 'wf_session': 364, 'wf_opto_session': 80, 'opto_session': 74, 'pharma_session': 29}
genotype field: {'WT': 1491, 'Ai148': 3}
session_description prefixes: {'whisker_context_': 1434, 'context_': 60}
trials 625401 sessions with trials 1494 mice 73
trial types {'whisker_trial': 250692, 'no_stim_trial': 250526, 'auditory_trial': 124183} | context {1: 313129, 0: 312272} | noise {'brown': 312681, 'pink': 309890}
perf code x trial type
trial_type  auditory_trial  no_stim_trial  whisker_trial
perf                                                    
0                        0              0          92601
1                    12093              0              0
2                        0              0         156981
3                   111583              0              0
4                        0         217658              0
5                        0          31723              0
6                      507           1145           1110
early_lick equals perf 6 for 1.0 of trials
lick_flag 1 with no lick_time: 2762 | lick_time - stim_time on lick trials without early lick (s): {'count': 268564.0, 'mean': 0.454, 'std': 0.183, 'min': 0.192, '25%': 0.311, '50%': 0.415, '75%': 0.525, 'max': 1.392}
whisker amplitude {2.7: 40540, 2.6: 37962, 2.8: 25436, 2.4: 22653, 2.5: 19469} | whisker duration (ms) {3: 250692}
auditory frequency {10000: 124183} | duration (ms) {10: 113951, 4: 10232}
reward_available by trial type and context
trial_type      context
auditory_trial  0          1.000
                1          1.000
no_stim_trial   0          0.000
                1          0.000
whisker_trial   0          0.459
                1          1.000
Name: reward_available, dtype: float64
fraction of trials with the majority noise per mouse and context, min: {0: 0.928, 1: 0.929}
epochs 32306 | epoch duration (s) {'count': 32306.0, 'mean': 201.0, 'std': 71.4, 'min': 3.2, '25%': 183.8, '50%': 193.4, '75%': 211.2, 'max': 6359.3}
fraction of trials whose context matches the epoch they fall in: median 1.0 min 0.2176 sessions 1494
blocks per session, epochs against context runs of the trial table: equal in 0.996 of sessions
sessions with identical trial times as another session: 0

session-list-link¶

The code's session lists are matched to the dandiset's sessions by identifier (PB170_20240220_155608 in the code is ses-PB170-20240220-155608 here). The lists also state counts in the claims file's opening comment, which are compared.

In [3]:
S = set(A.session_id)
expect = {'sessions_Context_sessions': (65, 1449), 'sessions_Context_sessions_expert': (41, 201),
          'sessions_Context_sessions_opto': (7, 56), 'sessions_Context_sessions_opto_control': (4, 39),
          'sessions_Context_sound_off': (7, 21), 'sessions_Context_sessions_expert_WF_jrGECO': (6, 25),
          'sessions_Context_sessions_expert_WF_gcamp': (8, 33), 'sessions_Context_sessions_expert_WF_tomato': (4, 15),
          'sessions_Context_sessions_expert_WF_GFP': (6, 24), 'sessions_Context_sessions_wf_opto': (4, 40),
          'sessions_Context_sessions_wf_opto_photoactivation': (2, 6), 'session_context_expert_behaviour_model': (21, 60)}
rows = []
for n, l in LISTS.items():
    rows.append((n, len(l), len(set(l) & S), len(set(l) & set(T.session_id)), len({x.split('_')[0] for x in l}), expect.get(n)))
link = pd.DataFrame(rows, columns=['list', 'sessions', 'in dandiset', 'with trial table', 'mice', 'claims file (mice, sessions)'])
print(link.to_string())
allids = set().union(*LISTS.values())
print('sessions named by any list', len(allids), 'found', len(allids & S), f'({len(allids & S) / len(allids):.1%})')
missing = sorted(set(LISTS['sessions_Context_sessions']) - S)
print('pool list sessions not in the dandiset:', len(missing), missing[:10])
pool = LISTS['sessions_Context_sessions']
plain = {'_'.join(x.split('_')[:3]) for x in missing}
print('of these, the plain identifier is in the dandiset:', len(plain & S), '| also listed plainly in the pool list:', len(plain & set(pool)),
      '| pool list entries', len(pool), 'distinct', len(set(pool)), 'distinct sessions after cutting the suffix', len({'_'.join(x.split('_')[:3]) for x in pool}))
print('pool list sessions in the dandiset without a readable trial table:', sorted((set(pool) & S) - set(T.session_id)))
# session types of the listed sessions agree with the list's purpose
st = M.set_index('session_id').session_type
for n in ['sessions_Context_sessions_opto', 'sessions_Context_sessions_opto_control', 'sessions_Context_sessions_wf_opto',
          'sessions_Context_sessions_expert_WF_jrGECO', 'sessions_Context_muscimol_wS1', 'sessions_Context_ringer_RSC']:
    print(n, st.reindex(LISTS[n]).value_counts().to_dict())
opto = T[T.session_id.isin(LISTS['sessions_Context_sessions_opto'])]
print('opto list: sites per session', opto[opto.opto_stim == 1].groupby('session_id').apply(lambda g: len(set(zip(g.opto_grid_ap, g.opto_grid_ml)))).describe().round(1).to_dict())
                                                 list  sessions  in dandiset  with trial table  mice claims file (mice, sessions)
0                           sessions_Context_sessions      1451         1421              1418    65                   (65, 1449)
1                    sessions_Context_sessions_expert       201          201               201    41                    (41, 201)
2                      sessions_Context_sessions_opto        56           56                56     7                      (7, 56)
3              sessions_Context_sessions_opto_control        39           39                39     4                      (4, 39)
4                          sessions_Context_sound_off        21           21                21     7                      (7, 21)
5                     sessions_Context_sound_off_only         7            7                 7     7                         None
6                       sessions_Context_muscimol_wS1        14           14                14     5                         None
7                      sessions_Context_muscimol_fpS1        13           13                13     5                         None
8                       sessions_Context_muscimol_RSC        21           21                21     8                         None
9                         sessions_Context_ringer_wS1        12           12                12     4                         None
10                       sessions_Context_ringer_fpS1        12           12                12     4                         None
11                        sessions_Context_ringer_RSC        12           12                12     4                         None
12         sessions_Context_sessions_expert_WF_jrGECO        25           25                25     6                      (6, 25)
13          sessions_Context_sessions_expert_WF_gcamp        33           33                33     8                      (8, 33)
14         sessions_Context_sessions_expert_WF_tomato        15           15                15     4                      (4, 15)
15            sessions_Context_sessions_expert_WF_GFP        24           24                24     6                      (6, 24)
16                  sessions_Context_sessions_wf_opto        40           40                40     4                      (4, 40)
17  sessions_Context_sessions_wf_opto_photoactivation         6            6                 6     2                       (2, 6)
18             session_context_expert_behaviour_model        60           60                60    21                     (21, 60)
sessions named by any list 1497 found 1467 (98.0%)
pool list sessions not in the dandiset: 30 ['PB165_20231115_144956_2023_12_01', 'PB165_20231116_115704_2023_12_01', 'PB165_20231121_123419_2023_12_01', 'PB165_20231123_113642_2023_12_01', 'PB165_20231124_145031_2023_12_01', 'PB165_20231130_105037_2023_12_01', 'PB165_20231201_101931_2023_12_02', 'PB165_20231202_110906_2023_12_03', 'PB165_20231203_133045_2023_12_07', 'PB165_20231205_113439_2023_12_07']
of these, the plain identifier is in the dandiset: 30 | also listed plainly in the pool list: 0 | pool list entries 1451 distinct 1451 distinct sessions after cutting the suffix 1451
pool list sessions in the dandiset without a readable trial table: ['PB185_20240801_095038', 'PB186_20240801_110359', 'PB189_20240902_155436']
sessions_Context_sessions_opto {'wf_opto_session': 38, 'opto_session': 18}
sessions_Context_sessions_opto_control {'wf_opto_session': 34, 'opto_session': 5}
sessions_Context_sessions_wf_opto {'wf_opto_session': 40}
sessions_Context_sessions_expert_WF_jrGECO {'wf_session': 25}
sessions_Context_muscimol_wS1 {'behaviour_only_session': 12, 'pharma_session': 2}
sessions_Context_ringer_RSC {'behaviour_only_session': 8, 'pharma_session': 4}
opto list: sites per session {'count': 56.0, 'mean': 15.7, 'std': 0.4, 'min': 15.0, '25%': 15.0, '50%': 16.0, '75%': 16.0, 'max': 16.0}

Result: partially reproduced. Every session of every list a claim selects from is in the dandiset under the same identifier with a readable trial table, and those lists' counts of mice and sessions equal the claims file's. The pool list sessions_Context_sessions, used for the expert rule's pool variant, does not match in full: it has 1451 entries for the stated 1449, 30 of them carry a processing-date suffix and are not dandiset identifiers, and 3 of its sessions have no readable trial table (printed above). 98.0% of the sessions named by any list are found.

Behaviour (Figure 1 and its supplement)¶

Selection readings for "expert sessions" (claims file, opening comment): (a) the Methods' rule recomputed on every behavioural session of the dataset (session description whisker_context), (b) the code's list sessions_Context_sessions_expert.

expert-sessions¶

The expert sessions of the behavioural data come from 41 mice and number 201, with an average of 23 context blocks per session.

In [4]:
behS = M[M.session_description.str.startswith('whisker_context')].session_id
beh = T[T.session_id.isin(behS)]
con = bech.block_contrast(beh, 'epochs'); ex = bech.is_expert(con, seed=1)
expA = sorted(s for s, (lo, e) in ex.items() if e)
expB = LISTS['sessions_Context_sessions_expert']
con20 = bech.block_contrast(beh, '20'); ex20 = bech.is_expert(con20, seed=2)
exp20 = sorted(s for s, (lo, e) in ex20.items() if e)
nblocks = (T.groupby('session_id').block.max() + 1)
nb_ep = E.groupby('session_id').size()
for name, Sx in [('(a) rule, epoch blocks', expA), ('rule, 20-trial blocks (variant)', exp20), ('(b) code list', expB)]:
    print(f'{name}: sessions {len(Sx)}, mice {len({s.split("_")[0] for s in Sx})}, '
          f'blocks per session (epochs) {nb_ep.reindex(Sx).mean():.2f}, (context runs) {nblocks.reindex(Sx).mean():.2f}')
print('behavioural sessions tested', len(con), '| with < 2 contrasts', sum(len(c) < 2 for c in con.values()))
print('overlap of (a) with the code list', len(set(expA) & set(expB)), 'of', len(expB))
print('overlap of the 20-trial variant with the code list', len(set(exp20) & set(expB)))
inpool = set(LISTS['sessions_Context_sessions'])
eA_pool = [s for s in expA if s in inpool]
print('(a) restricted to the code pool list: sessions', len(eA_pool), 'mice', len({s.split('_')[0] for s in eA_pool}))
lo = pd.Series({s: v[0] for s, v in ex.items()})
print('lower bound of the code-list sessions under the rule: min', lo.reindex(expB).min().round(3), ', below 0.375:', (lo.reindex(expB) <= 0.375).sum())
# which sessions the rule is run on: session types, and the 60 sessions described 'context_...'
print('session types of the sessions tested:', M[M.session_id.isin(con)].session_type.value_counts().to_dict())
ctxS = M[M.session_description.str.startswith('context_')]
print('sessions described context_...:', len(ctxS), 'mice', sorted(ctxS.mouse_id.unique()), 'types', ctxS.session_type.value_counts().to_dict())
print('   in the code lists:', {n: len(set(ctxS.session_id) & set(l)) for n, l in LISTS.items() if set(ctxS.session_id) & set(l)})
conC = bech.block_contrast(T[T.session_id.isin(ctxS.session_id)], 'epochs'); exC = bech.is_expert(conC, seed=3)
withC = expA + sorted(s for s, (l_, e) in exC.items() if e)
onlyB = [s for s in expA if M.set_index('session_id').session_type.get(s) == 'behaviour_only_session']
for name, Sx in [('variant, rule also on the context_ sessions', withC), ('variant, rule on behaviour_only sessions only', onlyB)]:
    print(f'{name}: sessions {len(Sx)}, mice {len({s.split("_")[0] for s in Sx})}, blocks per session (epochs) {nb_ep.reindex(Sx).mean():.2f}')
/home/runner/work/encore/encore/entries/001847-bech-2026/bech.py:167: RuntimeWarning: Mean of empty slice
  c = [np.nanmean([abs(hr[i] - hr[i - 1]), abs(hr[i] - hr[i + 1])]) for i in range(1, len(hr) - 1)]
(a) rule, epoch blocks: sessions 318, mice 49, blocks per session (epochs) 24.73, (context runs) 24.72
rule, 20-trial blocks (variant): sessions 316, mice 48, blocks per session (epochs) 24.74, (context runs) 24.73
(b) code list: sessions 201, mice 41, blocks per session (epochs) 23.89, (context runs) 23.89
behavioural sessions tested 1434 | with < 2 contrasts 0
overlap of (a) with the code list 189 of 201
overlap of the 20-trial variant with the code list 187
(a) restricted to the code pool list: sessions 293 mice 42
lower bound of the code-list sessions under the rule: min 0.299 , below 0.375: 12
session types of the sessions tested: {'behaviour_only_session': 888, 'wf_session': 364, 'wf_opto_session': 80, 'opto_session': 74, 'pharma_session': 28}
sessions described context_...: 60 mice ['RD003', 'RD027', 'RD029', 'RD030', 'RD031', 'RD032'] types {'behaviour_only_session': 59, 'pharma_session': 1}
   in the code lists: {'sessions_Context_sessions': 51, 'sessions_Context_sound_off': 3, 'sessions_Context_sound_off_only': 1, 'sessions_Context_muscimol_wS1': 9, 'sessions_Context_muscimol_fpS1': 3}
variant, rule also on the context_ sessions: sessions 322, mice 52, blocks per session (epochs) 24.63
variant, rule on behaviour_only sessions only: sessions 112, mice 42, blocks per session (epochs) 23.77

Result: not reproduced under the rule. The Methods' rule applied to every behavioural session gives the session and mouse counts printed above, outside the tolerance of 201 ± 20.1 sessions and 41 ± 4.1 mice; neither variant (the rule with the context_ sessions added, 322 sessions in 52 mice, or on behaviour-only sessions, 112 sessions in 42 mice) gives all three counts within tolerance. The code's list matches the paper's counts and its blocks per session are within 23 ± 2.3.

In [5]:
def lick_by_mouse(Sx):
    D = T[T.session_id.isin(Sx) & (T.early_lick == 0)]
    return bech.mouse_avg(D, 'lick_flag', ['trial_type', 'context']).pivot_table('lick_flag', 'mouse_id', ['trial_type', 'context']) * 100
LB = {'a': lick_by_mouse(expA), 'b': lick_by_mouse(expB)}
for k, m in LB.items():
    print(f'reading ({k}), {len(m)} mice: mean'); print(m.mean().round(1).to_string()); print('SD'); print(m.std().round(1).to_string())
reading (a), 49 mice: mean
trial_type      context
auditory_trial  0          88.4
                1          93.0
no_stim_trial   0           4.3
                1          14.5
whisker_trial   0          31.4
                1          84.3
SD
trial_type      context
auditory_trial  0          20.8
                1          11.3
no_stim_trial   0           1.9
                1           8.2
whisker_trial   0           6.4
                1           5.3
reading (b), 41 mice: mean
trial_type      context
auditory_trial  0          93.7
                1          95.7
no_stim_trial   0           4.4
                1          13.3
whisker_trial   0          31.7
                1          83.9
SD
trial_type      context
auditory_trial  0          5.2
                1          3.6
no_stim_trial   0          2.2
                1          7.5
whisker_trial   0          7.0
                1          6.1

fig1c-auditory-hit-both-contexts¶

In expert sessions mice lick to the auditory tone in both contexts, with hit rates of 96 ± 4% in W+ and 94 ± 5% in W- (mean ± SD over 41 mice).

In [6]:
for k, m in LB.items():
    wp, wm = m[('auditory_trial', 1)].mean(), m[('auditory_trial', 0)].mean()
    print(f'({k}) auditory W+ {wp:.1f} (96 ± 4: {abs(wp - 96) <= 4}), W- {wm:.1f} (94 ± 5: {abs(wm - 94) <= 5}); n mice {len(m)}')
    print('   by mouse, min W+ / W-:', m[('auditory_trial', 1)].min().round(1), m[('auditory_trial', 0)].min().round(1))
(a) auditory W+ 93.0 (96 ± 4: True), W- 88.4 (94 ± 5: False); n mice 49
   by mouse, min W+ / W-: 38.6 3.5
(b) auditory W+ 95.7 (96 ± 4: True), W- 93.7 (94 ± 5: True); n mice 41
   by mouse, min W+ / W-: 86.1 76.9

Result: reproduced under reading (b). With the code's list the auditory hit rates are within the paper's SDs in both contexts (printed above); under reading (a) the W- value is below the tolerance. The criterion accepts either reading of the selection, and reading (b) is the one whose mice and sessions are the paper's (41 mice and 201 sessions, expert-sessions).

fig1c-whisker-context-modulation¶

Licking to the whisker stimulus depends strongly on context, 84 ± 6% in W+ against 32 ± 7% in W- (mean ± SD over mice).

In [7]:
for k, m in LB.items():
    wp, wm = m[('whisker_trial', 1)].mean(), m[('whisker_trial', 0)].mean()
    r = stats.ttest_rel(m[('whisker_trial', 1)], m[('whisker_trial', 0)])
    print(f'({k}) whisker W+ {wp:.1f} (84 ± 6: {abs(wp - 84) <= 6}), W- {wm:.1f} (32 ± 7: {abs(wm - 32) <= 7}); paired t {r.statistic:.1f}, p {r.pvalue:.1e}, n {len(m)}')
(a) whisker W+ 84.3 (84 ± 6: True), W- 31.4 (32 ± 7: True); paired t 74.4, p 3.1e-51, n 49
(b) whisker W+ 83.9 (84 ± 6: True), W- 31.7 (32 ± 7: True); paired t 54.7, p 3.2e-39, n 41

Result: reproduced. Both means are within tolerance under both readings (printed above).

fig1d-independent-of-noise-identity¶

The context modulation of whisker licking holds whichever background noise (pink or brown) is associated with each context.

In [8]:
wplus_noise = T[T.context == 1].groupby('mouse_id').context_background.agg(lambda x: x.value_counts().index[0])
for k, m in LB.items():
    for noise in ['pink', 'brown']:
        mm = m[m.index.map(wplus_noise) == noise]
        r = stats.ttest_rel(mm[('whisker_trial', 1)], mm[('whisker_trial', 0)])
        print(f'({k}) W+ noise {noise}: {len(mm)} mice, whisker W+ {mm[("whisker_trial", 1)].mean():.1f}, '
              f'W- {mm[("whisker_trial", 0)].mean():.1f}, paired t {r.statistic:.1f}, p {r.pvalue:.1e}')
(a) W+ noise pink: 26 mice, whisker W+ 83.8, W- 30.9, paired t 61.3, p 9.1e-29
(a) W+ noise brown: 23 mice, whisker W+ 84.8, W- 32.1, paired t 44.8, p 4.1e-23
(b) W+ noise pink: 21 mice, whisker W+ 84.4, W- 31.9, paired t 51.2, p 1.1e-22
(b) W+ noise brown: 20 mice, whisker W+ 83.4, W- 31.6, paired t 31.3, p 8.4e-18

Result: reproduced. In both groups of mice, under both readings, W+ is higher with p < 0.05 (printed above).

fig1c-catch-higher-wplus¶

Catch-trial (spontaneous) lick rates are low but slightly higher in W+ blocks, 13 ± 7% against 4 ± 2% in W-.

In [9]:
for k, m in LB.items():
    wp, wm = m[('no_stim_trial', 1)].mean(), m[('no_stim_trial', 0)].mean()
    r = stats.ttest_rel(m[('no_stim_trial', 0)], m[('no_stim_trial', 1)])
    print(f'({k}) catch W+ {wp:.1f} (13 ± 7: {abs(wp - 13) <= 7}), W- {wm:.1f} (4 ± 2: {abs(wm - 4) <= 2}); '
          f't (W- vs W+) {r.statistic:.2f}, p {r.pvalue:.1e}; paper t = -9, p = 1.6e-10')
(a) catch W+ 14.5 (13 ± 7: True), W- 4.3 (4 ± 2: True); t (W- vs W+) -9.03, p 6.4e-12; paper t = -9, p = 1.6e-10
(b) catch W+ 13.3 (13 ± 7: True), W- 4.4 (4 ± 2: True); t (W- vs W+) -8.52, p 1.6e-10; paper t = -9, p = 1.6e-10

Result: reproduced. Both means within tolerance, W+ higher, p < 0.05, under both readings.

fig1g-first-trial-switch¶

Mice change their whisker response at the first whisker trial after a context change, from 26 ± 8% to 73 ± 13% from W- to W+, and from 87 ± 7% to 57 ± 13% from W+ to W-.

In [10]:
TR = {}
for k, Sx in [('a', expA), ('b', expB)]:
    tr = bech.transition_table(T[T.session_id.isin(Sx)])
    TR[k] = tr.groupby(['mouse_id', 'session_id', 'direction', 'position']).lick.mean().groupby(['mouse_id', 'direction', 'position']).mean().unstack([1, 2]) * 100
exp_vals = {('W-toW+', -1): 26, ('W-toW+', 1): 73, ('W+toW-', -1): 87, ('W+toW-', 1): 57}
tol = {('W-toW+', -1): 8, ('W-toW+', 1): 13, ('W+toW-', -1): 7, ('W+toW-', 1): 13}
for k, pm in TR.items():
    print(f'reading ({k}), {len(pm)} mice')
    for key, v in exp_vals.items():
        print(f'   {key}: {pm[key].mean():.1f} (expected {v} ± {tol[key]}: {abs(pm[key].mean() - v) <= tol[key]}), SD {pm[key].std():.1f}')
    for d in ['W-toW+', 'W+toW-']:
        r = stats.ttest_rel(pm[(d, 1)], pm[(d, -1)])
        print(f'   {d}: t {r.statistic:.1f}, p {r.pvalue:.1e}, Bonferroni x2 {min(1, 2 * r.pvalue):.1e}')
reading (a), 49 mice
   ('W-toW+', -1): 25.7 (expected 26 ± 8: True), SD 8.2
   ('W-toW+', 1): 72.4 (expected 73 ± 13: True), SD 9.3
   ('W+toW-', -1): 86.8 (expected 87 ± 7: True), SD 6.6
   ('W+toW-', 1): 54.7 (expected 57 ± 13: True), SD 13.2
   W-toW+: t 27.1, p 8.9e-31, Bonferroni x2 1.8e-30
   W+toW-: t -18.3, p 3.1e-23, Bonferroni x2 6.2e-23
reading (b), 41 mice
   ('W-toW+', -1): 25.5 (expected 26 ± 8: True), SD 8.6
   ('W-toW+', 1): 70.9 (expected 73 ± 13: True), SD 12.2
   ('W+toW-', -1): 86.2 (expected 87 ± 7: True), SD 7.5
   ('W+toW-', 1): 56.8 (expected 57 ± 13: True), SD 12.9
   W-toW+: t 20.9, p 3.8e-23, Bonferroni x2 7.5e-23
   W+toW-: t -14.2, p 3.4e-17, Bonferroni x2 6.7e-17

Result: reproduced. The four values are within the paper's SDs and both tests give p < 0.05 in the stated direction, under both readings (printed above).

fig1f-gradual-further-adaptation¶

After the first whisker trial of a new block, whisker responses adapt slightly further over the following whisker trials, the second whisker trial already closer to the new context than the first.

In [11]:
for k, pm in TR.items():
    print(f'reading ({k}): mean lick probability (%) by position'); print(pm.mean().unstack(0).round(1).T.to_string())
    for d, sgn in [('W-toW+', 1), ('W+toW-', -1)]:
        m1, m2, m4 = pm[(d, 1)].mean(), pm[(d, 2)].mean(), pm[(d, 4)].mean()
        r = stats.ttest_rel(pm[(d, 2)], pm[(d, 1)])
        print(f'   {d}: +2 closer than +1: {sgn * (m2 - m1) > 0}; +4 at least as close as +2: {sgn * (m4 - m2) >= 0} '
              f'(+1 {m1:.1f}, +2 {m2:.1f}, +4 {m4:.1f}); +2 vs +1 t {r.statistic:.1f}, p {r.pvalue:.1e}')
reading (a): mean lick probability (%) by position
position     -3    -2    -1     1     2     3     4
direction                                          
W+toW-     87.9  88.0  86.8  54.7  38.7  28.3  24.6
W-toW+     25.1  27.4  25.7  72.4  82.6  85.9  85.4
   W-toW+: +2 closer than +1: True; +4 at least as close as +2: True (+1 72.4, +2 82.6, +4 85.4); +2 vs +1 t 9.4, p 1.9e-12
   W+toW-: +2 closer than +1: True; +4 at least as close as +2: True (+1 54.7, +2 38.7, +4 24.6); +2 vs +1 t -10.7, p 2.7e-14
reading (b): mean lick probability (%) by position
position     -3    -2    -1     1     2     3     4
direction                                          
W+toW-     87.6  88.0  86.2  56.8  38.2  27.2  25.4
W-toW+     27.1  27.4  25.5  70.9  82.6  86.1  84.8
   W-toW+: +2 closer than +1: True; +4 at least as close as +2: True (+1 70.9, +2 82.6, +4 84.8); +2 vs +1 t 9.3, p 1.4e-11
   W+toW-: +2 closer than +1: True; +4 at least as close as +2: True (+1 56.8, +2 38.2, +4 25.4); +2 vs +1 t -10.6, p 3.8e-13

Result: reproduced. In both directions and under both selections, trial +2 is closer to the new context than +1 and +4 at least as close as +2, with paired t of +2 against +1 above 9 in absolute value.

fig1h-temporal-integration¶

The lick probability to the first whisker trial of a block rises with the time elapsed since a transition to W+ and falls with it after a transition to W-, while the last whisker trial before a transition shows no sign of anticipating the switch.

Transition time is the start of the new context epoch. Bins of 10 s, bin -1 = [-10, 0) s, bin +1 = [0, 10) s.

In [12]:
def fig1h_table(Sx, drop_early):
    rows = []
    D = T[T.session_id.isin(Sx) & (T.trial_type == 'whisker_trial')]
    if drop_early: D = D[D.early_lick == 0]
    for sid, g in D.groupby('session_id'):
        g = g.sort_values('start_time'); full = T[T.session_id == sid].sort_values('start_time')
        for b in range(1, full.block.max() + 1):
            tt = full[full.block == b].start_time.min()  # first trial of the new block
            ep = E[(E.session_id == sid)]
            # transition time: start of the epoch the first trial of the block falls in
            st = ep.start.values; st = st[st <= tt + 1e-6]
            t0 = st.max() if len(st) else tt
            pre, post = g[g.block == b - 1], g[g.block == b]
            ctx = full[full.block == b].context.iloc[0]
            if len(pre): rows.append((sid, 'To W+' if ctx == 1 else 'To W-', pre.stim_time.iloc[-1] - t0, pre.lick_flag.iloc[-1]))
            if len(post): rows.append((sid, 'To W+' if ctx == 1 else 'To W-', post.stim_time.iloc[0] - t0, post.lick_flag.iloc[0]))
    R = pd.DataFrame(rows, columns=['session_id', 'transition', 't', 'lick'])
    R['bin'] = np.where(R.t < 0, np.floor(R.t / 10).astype(int), np.floor(R.t / 10).astype(int) + 1)
    return R
def expo(t, A_, tau, C): return A_ * np.exp(-t / tau) + C
from scipy.optimize import curve_fit
for k, Sx in [('a', expA), ('b', expB)]:
    for drop in [False, True]:
        R = fig1h_table(Sx, drop)
        tab = R[(R.bin >= -5) & (R.bin <= 5)].groupby(['transition', 'bin']).lick.agg(['mean', 'size']).unstack(0)
        print(f'reading ({k}), early licks {"dropped" if drop else "kept (code)"}'); print(tab.round(3).to_string())
        for tr, sgn in [('To W+', 1), ('To W-', -1)]:
            y = tab[('mean', tr)].reindex([-1, 1, 2, 3, 4, 5]).values; x = np.array([0, 1, 2, 3, 4, 5])
            try:
                p, _ = curve_fit(expo, x, y, p0=[y[0] - y[-1], 3, y[-1]], bounds=([-np.inf, 0.1, -np.inf], [np.inf, 50, np.inf]), maxfev=10000)
                f1, f5 = expo(1, *p), expo(5, *p)
                print(f'   {tr}: fit A {p[0]:.3f}, tau {p[1]:.2f} bins, C {p[2]:.3f}; fitted +1 {f1:.3f}, +5 {f5:.3f}; in the stated direction: {sgn * (f5 - f1) > 0}')
            except Exception as e:
                print('   fit failed', tr, e)
            pre = R[(R.transition == tr) & (R.bin >= -5) & (R.bin <= -1)]
            bm = pre.groupby('bin').lick.mean()
            rr = stats.pearsonr(bm.index * 10 - 5, bm.values)
            b1 = pre[pre.bin == -1].lick; b25 = pre[pre.bin <= -2].lick
            ft = stats.fisher_exact([[b1.sum(), len(b1) - b1.sum()], [b25.sum(), len(b25) - b25.sum()]])
            print(f'   {tr} anticipation: (a) Pearson r {rr.statistic:.2f}, p {rr.pvalue:.3f}; (b) bin -1 {b1.mean():.3f} vs bins -5..-2 {b25.mean():.3f}, Fisher p {ft.pvalue:.3f}')
reading (a), early licks kept (code)
             mean         size      
transition  To W+  To W- To W+ To W-
bin                                 
-5          0.235  0.833   230   227
-4          0.231  0.857   307   377
-3          0.238  0.865   608   554
-2          0.215  0.841   885   803
-1          0.252  0.855  1538  1527
 1          0.641  0.591  1505  1596
 2          0.740  0.459   891   915
 3          0.758  0.428   594   587
 4          0.792  0.360   327   308
 5          0.804  0.349   199   166
   To W+: fit A -0.537, tau 0.81 bins, C 0.791; fitted +1 0.634, +5 0.790; in the stated direction: True
   To W+ anticipation: (a) Pearson r 0.21, p 0.729; (b) bin -1 0.252 vs bins -5..-2 0.227, Fisher p 0.081
   To W-: fit A 0.516, tau 1.45 bins, C 0.338; fitted +1 0.596, +5 0.354; in the stated direction: True
   To W- anticipation: (a) Pearson r 0.35, p 0.559; (b) bin -1 0.855 vs bins -5..-2 0.850, Fisher p 0.665
reading (a), early licks dropped
             mean         size      
transition  To W+  To W- To W+ To W-
bin                                 
-5          0.235  0.833   230   227
-4          0.231  0.857   307   377
-3          0.238  0.865   608   554
-2          0.215  0.841   885   803
-1          0.252  0.855  1538  1527
 1          0.638  0.587  1492  1582
 2          0.738  0.455   897   925
 3          0.756  0.426   590   589
 4          0.790  0.350   328   306
 5          0.799  0.343   204   169
   To W+: fit A -0.535, tau 0.81 bins, C 0.788; fitted +1 0.632, +5 0.787; in the stated direction: True
   To W+ anticipation: (a) Pearson r 0.21, p 0.729; (b) bin -1 0.252 vs bins -5..-2 0.227, Fisher p 0.081
   To W-: fit A 0.523, tau 1.46 bins, C 0.330; fitted +1 0.593, +5 0.347; in the stated direction: True
   To W- anticipation: (a) Pearson r 0.35, p 0.559; (b) bin -1 0.855 vs bins -5..-2 0.850, Fisher p 0.665
reading (b), early licks kept (code)
             mean         size      
transition  To W+  To W- To W+ To W-
bin                                 
-5          0.244  0.859   123   128
-4          0.260  0.874   204   222
-3          0.228  0.877   416   367
-2          0.212  0.834   523   500
-1          0.252  0.859   934   940
 1          0.615  0.605   908   997
 2          0.739  0.477   589   564
 3          0.745  0.450   385   380
 4          0.776  0.401   165   172
 5          0.824  0.343   119   102
   To W+: fit A -0.543, tau 0.94 bins, C 0.796; fitted +1 0.609, +5 0.793; in the stated direction: True
   To W+ anticipation: (a) Pearson r -0.27, p 0.663; (b) bin -1 0.252 vs bins -5..-2 0.228, Fisher p 0.206
   To W-: fit A 0.507, tau 1.56 bins, C 0.348; fitted +1 0.615, +5 0.368; in the stated direction: True
   To W- anticipation: (a) Pearson r -0.38, p 0.523; (b) bin -1 0.859 vs bins -5..-2 0.857, Fisher p 0.950
reading (b), early licks dropped
             mean         size      
transition  To W+  To W- To W+ To W-
bin                                 
-5          0.244  0.859   123   128
-4          0.260  0.874   204   222
-3          0.228  0.877   416   367
-2          0.212  0.834   523   500
-1          0.252  0.859   934   940
 1          0.615  0.605   908   997
 2          0.739  0.475   589   564
 3          0.745  0.450   385   380
 4          0.776  0.401   165   172
 5          0.824  0.343   119   102
   To W+: fit A -0.543, tau 0.94 bins, C 0.796; fitted +1 0.609, +5 0.793; in the stated direction: True
   To W+ anticipation: (a) Pearson r -0.27, p 0.663; (b) bin -1 0.252 vs bins -5..-2 0.228, Fisher p 0.206
   To W-: fit A 0.506, tau 1.55 bins, C 0.348; fitted +1 0.614, +5 0.368; in the stated direction: True
   To W- anticipation: (a) Pearson r -0.38, p 0.523; (b) bin -1 0.859 vs bins -5..-2 0.857, Fisher p 0.950

Result: reproduced. The fitted values rise from bin +1 to +5 after transitions to W+ and fall after transitions to W-, under every selection and early-lick reading, and neither anticipation reading finds an effect (all p above 0.05).

supp1c-wplus-blocks-longer¶

Whisker-rewarded context blocks last longer than whisker-non-rewarded blocks (196 ± 13 against 185 ± 4 s).

In [13]:
E['dur'] = E.stop - E.start
for k, Sx in [('a', expA), ('b', expB)]:
    D = E[E.session_id.isin(Sx)]
    m = D.groupby(['mouse_id', 'session_id', 'epoch']).dur.mean().groupby(['mouse_id', 'epoch']).mean().unstack()
    r = stats.ttest_rel(m.rewarded, m['non-rewarded'])
    print(f'({k}) {len(m)} mice: W+ {m.rewarded.mean():.1f} ± {m.rewarded.std():.1f} s (196 ± 13: {abs(m.rewarded.mean() - 196) <= 13}), '
          f'W- {m["non-rewarded"].mean():.1f} ± {m["non-rewarded"].std():.1f} s (185 ± 4: {abs(m["non-rewarded"].mean() - 185) <= 4}); t {r.statistic:.2f}, p {r.pvalue:.1e}')
    print('    epoch durations range (s)', D.dur.min().round(1), D.dur.max().round(1))
(a) 49 mice: W+ 203.6 ± 20.2 s (196 ± 13: True), W- 189.4 ± 9.4 s (185 ± 4: False); t 5.29, p 3.0e-06
    epoch durations range (s) 4.4 6359.3
(b) 41 mice: W+ 195.5 ± 12.7 s (196 ± 13: True), W- 185.4 ± 3.7 s (185 ± 4: True); t 5.39, p 3.4e-06
    epoch durations range (s) 4.4 698.4

Result: reproduced under the code's list. W+ 195.5 s and W- 185.4 s, both within tolerance, W+ longer with p 3.4e-6; under the rule the W- mean is outside its tolerance. As for fig1c-auditory-hit-both-contexts, the code's list is the reading whose mice and sessions are the paper's.

supp1d-faster-response-wplus¶

Spout contact after the stimulus is slightly faster in W+ than in W-, for auditory (370 ± 9 against 400 ± 9 ms) and whisker trials (392 ± 9 against 418 ± 9 ms).

In [14]:
for k, Sx in [('a', expA), ('b', expB)]:
    D = T[T.session_id.isin(Sx) & (T.early_lick == 0) & (T.lick_flag == 1) & T.trial_type.isin(['auditory_trial', 'whisker_trial'])].copy()
    D['rt'] = (D.lick_time - D.stim_time) * 1000
    m = bech.mouse_avg(D, 'rt', ['trial_type', 'context']).pivot_table('rt', 'mouse_id', ['trial_type', 'context'])
    print(f'reading ({k})')
    for tt, (ep, em) in [('auditory_trial', (370, 400)), ('whisker_trial', (392, 418))]:
        mm = m[tt].dropna()
        r = stats.ttest_rel(mm[1], mm[0])
        print(f'   {tt}: W+ {mm[1].mean():.0f} (SD {mm[1].std():.0f}, SEM {mm[1].sem():.0f}; {ep} ± 9: {abs(mm[1].mean() - ep) <= 9}), '
              f'W- {mm[0].mean():.0f} (SD {mm[0].std():.0f}, SEM {mm[0].sem():.0f}; {em} ± 9: {abs(mm[0].mean() - em) <= 9}); '
              f't {r.statistic:.2f}, p x2 {min(1, 2 * r.pvalue):.1e}, mice {len(mm)}')
# variant: lick time measured from the opening of the response window (response_window_start_time)
D = T[T.session_id.isin(expB) & (T.early_lick == 0) & (T.lick_flag == 1) & T.trial_type.isin(['auditory_trial', 'whisker_trial'])].copy()
print('response window start minus stimulus time (ms):', ((D.response_window_start_time - D.stim_time) * 1000).round().value_counts().head(3).to_dict())
D['rt'] = (D.lick_time - D.response_window_start_time) * 1000
m = bech.mouse_avg(D, 'rt', ['trial_type', 'context']).pivot_table('rt', 'mouse_id', ['trial_type', 'context'])
print('variant, lick time minus response window start, reading (b):',
      {f'{tt} {"W+" if c else "W-"}': round(m[(tt, c)].mean()) for tt in ['auditory_trial', 'whisker_trial'] for c in (1, 0)})
reading (a)
   auditory_trial: W+ 472 (SD 111, SEM 16; 370 ± 9: False), W- 506 (SD 111, SEM 16; 400 ± 9: False); t -7.58, p x2 1.9e-09, mice 49
   whisker_trial: W+ 491 (SD 101, SEM 14; 392 ± 9: False), W- 525 (SD 85, SEM 12; 418 ± 9: False); t -5.98, p x2 5.4e-07, mice 49
reading (b)
   auditory_trial: W+ 470 (SD 89, SEM 14; 370 ± 9: False), W- 501 (SD 94, SEM 15; 400 ± 9: False); t -8.71, p x2 1.8e-10, mice 41
   whisker_trial: W+ 492 (SD 92, SEM 14; 392 ± 9: False), W- 518 (SD 72, SEM 11; 418 ± 9: False); t -3.95, p x2 6.2e-04, mice 41
response window start minus stimulus time (ms): {100.0: 38938}
variant, lick time minus response window start, reading (b): {'auditory_trial W+': 370, 'auditory_trial W-': 401, 'whisker_trial W+': 392, 'whisker_trial W-': 418}

Result: partially reproduced. W+ is faster for both trial types with corrected p below 0.05 and t-values equal to the paper's, but every mean is about 100 ms above the paper's value, outside the 9 ms tolerance. Measured from the opening of the response window, 100 ms after the stimulus in almost every trial, the means come close to the paper's (variant, printed above), which suggests the paper timed spout contact from that point; the criterion times it from the stimulus.

fig1e-context-off-no-discrimination¶

When the two context noises are replaced by constant white noise, keeping the block reward structure, mice no longer discriminate between the context blocks in their whisker responses.

In [15]:
off = LISTS['sessions_Context_sound_off_only']; on = sorted(set(LISTS['sessions_Context_sound_off']) - set(off))
print('Off sessions', len(off), 'On sessions', len(on))
print('noise on Off days:', T[T.session_id.isin(off)].context_background.value_counts().to_dict())
tr = bech.transition_table(T[T.session_id.isin(off)])
pm = tr.groupby(['mouse_id', 'session_id', 'direction', 'position']).lick.mean().groupby(['mouse_id', 'direction', 'position']).mean().unstack([1, 2]) * 100
for d in ['W-toW+', 'W+toW-']:
    r = stats.ttest_rel(pm[(d, 1)], pm[(d, -1)])
    print(f'Off, {d}: -1 {pm[(d, -1)].mean():.1f}, +1 {pm[(d, 1)].mean():.1f}, t {r.statistic:.2f}, p {r.pvalue:.3f}, mice {pm[(d, 1)].notna().sum()}')
for name, Sx in [('Off', off), ('On', on)]:
    m = lick_by_mouse(Sx)
    r = stats.ttest_rel(m[('whisker_trial', 1)], m[('whisker_trial', 0)])
    print(f'{name}: whisker W+ {m[("whisker_trial", 1)].mean():.1f}, W- {m[("whisker_trial", 0)].mean():.1f}, '
          f'difference {(m[("whisker_trial", 1)] - m[("whisker_trial", 0)]).mean():.1f}, t {r.statistic:.2f}, p {r.pvalue:.3g} (variant)')
Off sessions 7 On sessions 14
noise on Off days: {'brown': 1616, 'pink': 1607}
Off, W-toW+: -1 44.1, +1 49.5, t 1.20, p 0.275, mice 7
Off, W+toW-: -1 67.1, +1 71.8, t 0.64, p 0.545, mice 7
Off: whisker W+ 66.9, W- 61.3, difference 5.6, t 2.13, p 0.0769 (variant)
On: whisker W+ 81.5, W- 32.0, difference 49.4, t 13.53, p 1.01e-05 (variant)

Result: reproduced. On the Off days neither transition direction changes whisker licking (p 0.275 and 0.545); the W+ against W- variant gives p 0.077.

Optogenetic inactivation (Figure 2)¶

The opto-map rule of the claims file: per mouse, context, trial type and site, all the mouse's sessions pooled, ΔP(Lick) = P(lick | laser at the site) - P(lick | control, laser off the brain). Nulls: (i) the Methods (Figures 2C-E), block labels of whole blocks permuted within each session and ΔP recomputed; (ii) the Figure 2 legend and the code, lick outcomes permuted across the trials of that trial type and context within each session. 10,000 shuffles each (a count that is a standard choice). d' is |Cohen's d| between the null pooled over mice and the per-mouse ΔP. Thresholds (a) 0.5, (b) 0.8, (c) 2. A site has an effect of a sign when the mean ΔP over mice has that sign and d' passes the threshold. Early-lick trials are kept, as the code builds this table from the full trial table (figure2_analysis.py:20-40).

In [16]:
import warnings; warnings.filterwarnings('ignore')
OPTO_MICE = sorted({s.split('_')[0] for s in LISTS['sessions_Context_sessions_opto']})
CTRL_MICE = sorted({s.split('_')[0] for s in LISTS['sessions_Context_sessions_opto_control']})
O = T[T.session_id.isin(LISTS['sessions_Context_sessions_opto'])]
OC = T[T.session_id.isin(LISTS['sessions_Context_sessions_opto_control'])]
print('opto mice', OPTO_MICE, '| control mice', CTRL_MICE)
print('control trials (opto_stim 0) laser coordinates:', O[O.opto_stim == 0][['opto_grid_ap', 'opto_grid_ml']].value_counts().to_dict())
st = O[O.opto_stim == 1]
print('stimulated sites', st.groupby(['opto_grid_ap', 'opto_grid_ml']).ngroups, '| AP values', sorted(st.opto_grid_ap.unique()), '| ML values', sorted(st.opto_grid_ml.unique()))
print('trials per mouse, site, context and trial type: median', st.groupby(['mouse_id', 'opto_grid_ap', 'opto_grid_ml', 'context', 'trial_type']).size().median())
MAPS = {}
for null, seed in [('blocks', 11), ('trials', 12)]:
    obs, summ = bech.opto_map(O, OPTO_MICE, null=null, n_shuffle=10000, seed=seed)
    summ['name'] = summ.site.map({v: k for k, v in bech.SITES.items()})
    MAPS[null] = summ
OBS = obs
obsC, summC = bech.opto_map(OC, CTRL_MICE, null='trials', n_shuffle=10000, seed=13)
summC['name'] = summC.site.map({v: k for k, v in bech.SITES.items()})
print('sites per (context, trial type):', MAPS['trials'].groupby(['context', 'trial_type']).size().to_dict())
print('mice per site:', MAPS['trials'].n_mice.value_counts().to_dict())
for null, S in MAPS.items():
    print(f'null ({"i" if null == "blocks" else "ii"}) {null}: dP and d prime at the named sites')
    print(S[S.name.notna()].pivot_table(['dP_mean', 'dprime'], 'name', ['trial_type', 'context']).round(2).to_string())
    print('   null mean over sites, range', S.null_mean.min().round(3), S.null_mean.max().round(3), '| null SD range', S.null_sd.min().round(3), S.null_sd.max().round(3))
print('dP range over all sites', OBS.dP.min().round(2), OBS.dP.max().round(2))
THR = {'a': 0.5, 'b': 0.8, 'c': 2.0}
def effect(S, name, ctx, ttype, thr):
    r = S[(S.name == name) & (S.context == ctx) & (S.trial_type == ttype)]
    if len(r) == 0: return 0
    r = r.iloc[0]
    return int(np.sign(r.dP_mean)) if r.dprime >= thr else 0
def readings():
    for nl in ['blocks', 'trials']:
        for tk, tv in THR.items():
            yield f'null {"i" if nl == "blocks" else "ii"}, d>={tv}', MAPS[nl], tv
FIG4_OMIT = [(1.5, 5.5), (2.5, 4.5), (2.5, 5.5)]  # sites the Figure 4 code leaves out besides AP 3.5 (plot utils/figure4C_G.py)
print('stimulated sites after dropping AP 3.5:', MAPS['trials'].site.nunique(), '| of these, sites the Figure 4 code also leaves out:',
      sorted(set(MAPS['trials'].site) & set(FIG4_OMIT)))
# null (i) on synthetic data: 4 mice, 3 sessions of 20 blocks, the laser lowers licking by 0.2 at one site in both contexts
rs = np.random.default_rng(5); syn = []
for mo in range(4):
    for se in range(3):
        for b in range(20):
            for k in range(20):
                laser = rs.random() < 0.5
                p = 0.6 - (0.2 if laser else 0)
                syn.append((f'M{mo}', f'M{mo}_s{se}', b, b % 2, int(laser), 1.5 if laser else 0, 1.5 if laser else 0, 'whisker_trial', int(rs.random() < p), se * 1e4 + b * 100 + k))
syn = pd.DataFrame(syn, columns=['mouse_id', 'session_id', 'block', 'context', 'opto_stim', 'opto_grid_ap', 'opto_grid_ml', 'trial_type', 'lick_flag', 'start_time'])
for nl in ['blocks', 'trials']:
    _, sy = bech.opto_map(syn, [f'M{m}' for m in range(4)], null=nl, n_shuffle=1000, seed=4)
    print(f'synthetic, true dP -0.2 in both contexts, null ({"i" if nl == "blocks" else "ii"}):', sy[['context', 'dP_mean', 'null_mean', 'dprime']].round(3).to_dict('records'))
opto mice ['PB178', 'PB179', 'PB181', 'PB185', 'PB187', 'PB188', 'PB189'] | control mice ['PB177', 'PB195', 'PB197', 'PB198']
control trials (opto_stim 0) laser coordinates: {(-5.0, 5.0): 13978}
stimulated sites 45 | AP values [np.float64(-3.5), np.float64(-2.5), np.float64(-1.5), np.float64(-0.5), np.float64(0.5), np.float64(1.5), np.float64(2.5), np.float64(3.5)] | ML values [np.float64(0.5), np.float64(1.5), np.float64(2.5), np.float64(3.5), np.float64(4.5), np.float64(5.5)]
trials per mouse, site, context and trial type: median 6.0
sites per (context, trial type): {(0, 'auditory_trial'): 41, (0, 'no_stim_trial'): 41, (0, 'whisker_trial'): 41, (1, 'auditory_trial'): 41, (1, 'no_stim_trial'): 41, (1, 'whisker_trial'): 41}
mice per site: {7: 241, 6: 5}
null (i) blocks: dP and d prime at the named sites
                  dP_mean                                                       dprime                                              
trial_type auditory_trial       no_stim_trial       whisker_trial       auditory_trial       no_stim_trial       whisker_trial      
context                 0     1             0     1             0     1              0     1             0     1             0     1
name                                                                                                                                
A1                  -0.29 -0.35         -0.03 -0.03         -0.08 -0.09           0.09  0.07          0.00  0.01          0.05  0.10
ALM                 -0.22 -0.21         -0.02 -0.05         -0.29 -0.30           0.00  0.03          0.16  0.16          0.03  0.02
RSC                 -0.01  0.01          0.05  0.12          0.21  0.10           0.10  0.09          0.20  0.29          0.41  0.39
RSC_2               -0.01  0.02          0.03  0.09          0.22  0.14           0.05  0.15          0.24  0.22          0.28  0.25
tjM1                -0.11 -0.12          0.01  0.10          0.11 -0.03           0.04  0.01          0.27  0.27          0.28  0.27
tjS1                -0.12 -0.25          0.07 -0.00          0.23  0.02           0.26  0.23          0.24  0.28          0.57  0.56
wM1                 -0.16 -0.29          0.01 -0.00         -0.11 -0.20           0.14  0.22          0.05  0.05          0.29  0.18
wM2                 -0.17 -0.16         -0.04  0.04         -0.15 -0.18           0.00  0.03          0.35  0.35          0.06  0.08
wS1                  0.06  0.05          0.04 -0.05         -0.24 -0.46           0.10  0.03          0.25  0.29          0.53  0.53
wS2                 -0.30 -0.19         -0.00  0.01         -0.21 -0.29           0.22  0.25          0.06  0.09          0.33  0.23
   null mean over sites, range -0.352 0.179 | null SD range 0.068 0.373
null (ii) trials: dP and d prime at the named sites
                  dP_mean                                                       dprime                                              
trial_type auditory_trial       no_stim_trial       whisker_trial       auditory_trial       no_stim_trial       whisker_trial      
context                 0     1             0     1             0     1              0     1             0     1             0     1
name                                                                                                                                
A1                  -0.29 -0.35         -0.03 -0.03         -0.08 -0.09           1.77  2.03          0.34  0.33          0.61  0.75
ALM                 -0.22 -0.21         -0.02 -0.05         -0.29 -0.30           1.06  0.79          0.10  0.30          1.21  1.42
RSC                 -0.01  0.01          0.05  0.12          0.21  0.10           0.06  0.08          0.53  0.84          1.22  0.64
RSC_2               -0.01  0.02          0.03  0.09          0.22  0.14           0.06  0.07          0.39  0.74          1.10  0.58
tjM1                -0.11 -0.12          0.01  0.10          0.11 -0.03           0.36  0.85          0.07  0.73          0.69  0.00
tjS1                -0.12 -0.25          0.07 -0.00          0.23  0.02           0.62  1.26          0.60  0.01          1.14  0.06
wM1                 -0.16 -0.29          0.01 -0.00         -0.11 -0.20           0.44  1.08          0.08  0.04          0.34  0.97
wM2                 -0.17 -0.16         -0.04  0.04         -0.15 -0.18           1.11  0.94          0.47  0.26          1.04  1.40
wS1                  0.06  0.05          0.04 -0.05         -0.24 -0.46           0.29  0.11          0.42  0.29          0.94  2.25
wS2                 -0.30 -0.19         -0.00  0.01         -0.21 -0.29           2.24  1.34          0.03  0.08          1.72  2.57
   null mean over sites, range -0.05 0.032 | null SD range 0.07 0.294
dP range over all sites -0.95 0.7
stimulated sites after dropping AP 3.5: 41 | of these, sites the Figure 4 code also leaves out: [(1.5, 5.5), (2.5, 4.5)]
synthetic, true dP -0.2 in both contexts, null (i): [{'context': 0, 'dP_mean': -0.228, 'null_mean': -0.222, 'dprime': 0.191}, {'context': 1, 'dP_mean': -0.215, 'null_mean': -0.221, 'dprime': 0.183}]
synthetic, true dP -0.2 in both contexts, null (ii): [{'context': 0, 'dP_mean': -0.228, 'null_mean': -0.001, 'dprime': 5.586}, {'context': 1, 'dP_mean': -0.215, 'null_mean': 0.0, 'dprime': 5.282}]

fig2c-catch-little-effect¶

Optogenetic inactivation of cortical sites has little effect on licking in catch trials in either context.

In [17]:
res = {}
for lab, S, thr in readings():
    c = S[S.trial_type == 'no_stim_trial']
    n = {ctx: int((c[c.context == ctx].dprime >= thr).sum()) for ctx in (0, 1)}
    res[lab] = max(n.values()) <= 3
    c39 = c[~c.site.isin(FIG4_OMIT)]
    n39 = {ctx: int((c39[c39.context == ctx].dprime >= thr).sum()) for ctx in (0, 1)}
    print(f'{lab}: sites with an effect W- {n[0]}, W+ {n[1]} (of {c[c.context == 0].shape[0]}); at most 3: {res[lab]} | '
          f'on the {c39[c39.context == 0].shape[0]} sites of the Figure 4 code: W- {n39[0]}, W+ {n39[1]}')
print('largest mean |dP| over sites in catch trials:', MAPS['trials'][MAPS['trials'].trial_type == 'no_stim_trial'].dP_mean.abs().max().round(3))
print('all readings agree:', len(set(res.values())) == 1, set(res.values()))
null i, d>=0.5: sites with an effect W- 2, W+ 2 (of 41); at most 3: True | on the 39 sites of the Figure 4 code: W- 2, W+ 2
null i, d>=0.8: sites with an effect W- 0, W+ 0 (of 41); at most 3: True | on the 39 sites of the Figure 4 code: W- 0, W+ 0
null i, d>=2.0: sites with an effect W- 0, W+ 0 (of 41); at most 3: True | on the 39 sites of the Figure 4 code: W- 0, W+ 0
null ii, d>=0.5: sites with an effect W- 7, W+ 11 (of 41); at most 3: False | on the 39 sites of the Figure 4 code: W- 7, W+ 11
null ii, d>=0.8: sites with an effect W- 0, W+ 3 (of 41); at most 3: True | on the 39 sites of the Figure 4 code: W- 0, W+ 3
null ii, d>=2.0: sites with an effect W- 0, W+ 0 (of 41); at most 3: True | on the 39 sites of the Figure 4 code: W- 0, W+ 0
largest mean |dP| over sites in catch trials: 0.118
all readings agree: False {False, True}

Result: blocked (methods_underspecified). Five readings find at most 3 affected sites, but the trial-shuffle null at d' 0.5 finds 7 (W-) and 11 (W+), so the readings disagree.

fig2d-auditory-a1-frontal¶

In auditory trials, inactivating auditory cortex and frontal premotor regions reduces lick probability, similarly in both contexts.

In [18]:
res = {}
for lab, S, thr in readings():
    ok = {}
    for ctx in (0, 1):
        a1 = effect(S, 'A1', ctx, 'auditory_trial', thr) == -1
        fr = any(effect(S, n, ctx, 'auditory_trial', thr) == -1 for n in ['wM1', 'wM2', 'ALM'])
        ok[ctx] = a1 and fr
    res[lab] = 'reproduced' if all(ok.values()) else ('partially' if any(ok.values()) else 'not')
    print(f'{lab}: W- {ok[0]}, W+ {ok[1]} -> {res[lab]}')
S = MAPS['trials']
print(S[S.name.isin(['A1', 'wM1', 'wM2', 'ALM']) & (S.trial_type == 'auditory_trial')].pivot_table('dP_mean', 'name', 'context').round(3))
print('all readings agree:', len(set(res.values())) == 1, set(res.values()))
null i, d>=0.5: W- False, W+ False -> not
null i, d>=0.8: W- False, W+ False -> not
null i, d>=2.0: W- False, W+ False -> not
null ii, d>=0.5: W- True, W+ True -> reproduced
null ii, d>=0.8: W- True, W+ True -> reproduced
null ii, d>=2.0: W- False, W+ False -> not
context      0      1
name                 
A1      -0.286 -0.350
ALM     -0.216 -0.208
wM1     -0.155 -0.287
wM2     -0.169 -0.160
all readings agree: False {'reproduced', 'not'}

Result: blocked (methods_underspecified). The trial-shuffle null at d' 0.5 and 0.8 reproduces the claim; the same null at 2 and the block-label null at every threshold do not.

fig2e-whisker-sensory-premotor-reduction¶

In whisker trials, inactivating wS1, wS2 and anterior premotor regions (wM1/2, ALM) reduces lick probability in both contexts.

In [19]:
res = {}
for lab, S, thr in readings():
    ok = {}
    for ctx in (0, 1):
        ok[ctx] = (effect(S, 'wS1', ctx, 'whisker_trial', thr) == -1 and effect(S, 'wS2', ctx, 'whisker_trial', thr) == -1
                   and any(effect(S, n, ctx, 'whisker_trial', thr) == -1 for n in ['wM1', 'wM2', 'ALM']))
    res[lab] = 'reproduced' if all(ok.values()) else ('partially' if ok[1] else 'not')
    print(f'{lab}: W- {ok[0]}, W+ {ok[1]} -> {res[lab]}')
print('all readings agree:', len(set(res.values())) == 1, set(res.values()))
null i, d>=0.5: W- False, W+ False -> not
null i, d>=0.8: W- False, W+ False -> not
null i, d>=2.0: W- False, W+ False -> not
null ii, d>=0.5: W- True, W+ True -> reproduced
null ii, d>=0.8: W- True, W+ True -> reproduced
null ii, d>=2.0: W- False, W+ False -> not
all readings agree: False {'reproduced', 'not'}

Result: blocked (methods_underspecified). Reproduced under the trial-shuffle null at d' 0.5 and 0.8, not under it at 2 nor under the block-label null.

fig2e-rsc-tjs1-increase-wminus¶

Inactivating tongue-jaw somatosensory cortex (tjS1) or retrosplenial cortex (RSC) increases lick probability in whisker trials specifically in the W- context.

In [20]:
for rsc in ['RSC', 'RSC_2']:
    res = {}
    for lab, S, thr in readings():
        ok = {n: effect(S, n, 0, 'whisker_trial', thr) == 1 and effect(S, n, 1, 'whisker_trial', thr) != 1 for n in ['tjS1', rsc]}
        res[lab] = 'reproduced' if all(ok.values()) else ('partially' if any(ok.values()) else 'not')
        print(f'{rsc}, {lab}: {ok} -> {res[lab]}')
    print(rsc, 'all readings agree:', len(set(res.values())) == 1, set(res.values()))
for nl, S in MAPS.items():
    print(nl, S[S.name.isin(['tjS1', 'RSC', 'RSC_2']) & (S.trial_type == 'whisker_trial')].pivot_table(['dP_mean', 'dprime'], 'name', 'context').round(3).to_string())
print('per mouse dP, whisker W-:'); print(OBS[(OBS.trial_type == 'whisker_trial') & (OBS.context == 0) & OBS.site.isin([bech.SITES['RSC'], bech.SITES['tjS1']])].pivot_table('dP', 'mouse_id', 'site').round(2))
RSC, null i, d>=0.5: {'tjS1': False, 'RSC': False} -> not
RSC, null i, d>=0.8: {'tjS1': False, 'RSC': False} -> not
RSC, null i, d>=2.0: {'tjS1': False, 'RSC': False} -> not
RSC, null ii, d>=0.5: {'tjS1': True, 'RSC': False} -> partially
RSC, null ii, d>=0.8: {'tjS1': True, 'RSC': True} -> reproduced
RSC, null ii, d>=2.0: {'tjS1': False, 'RSC': False} -> not
RSC all readings agree: False {'reproduced', 'not', 'partially'}
RSC_2, null i, d>=0.5: {'tjS1': False, 'RSC_2': False} -> not
RSC_2, null i, d>=0.8: {'tjS1': False, 'RSC_2': False} -> not
RSC_2, null i, d>=2.0: {'tjS1': False, 'RSC_2': False} -> not
RSC_2, null ii, d>=0.5: {'tjS1': True, 'RSC_2': False} -> partially
RSC_2, null ii, d>=0.8: {'tjS1': True, 'RSC_2': True} -> reproduced
RSC_2, null ii, d>=2.0: {'tjS1': False, 'RSC_2': False} -> not
RSC_2 all readings agree: False {'reproduced', 'not', 'partially'}
blocks         dP_mean        dprime       
context       0      1      0      1
name                                
RSC       0.213  0.098  0.405  0.391
RSC_2     0.225  0.138  0.278  0.248
tjS1      0.227  0.017  0.566  0.555
trials         dP_mean        dprime       
context       0      1      0      1
name                                
RSC       0.213  0.098  1.218  0.639
RSC_2     0.225  0.138  1.105  0.576
tjS1      0.227  0.017  1.139  0.063
per mouse dP, whisker W-:
site      (-1.5, 0.5)  (0.5, 4.5)
mouse_id                         
PB178            0.24        0.17
PB179            0.45        0.70
PB181            0.16        0.16
PB185           -0.09        0.08
PB187            0.26        0.16
PB188            0.18        0.14
PB189            0.29        0.19

Result: blocked (methods_underspecified). The readings give reproduced (trial shuffle, d' 0.8), partially reproduced (0.5) and not reproduced (2, and every block-label reading).

fig2cd-rsc-no-effect-catch-auditory¶

Inhibiting RSC does not change performance in catch or auditory trials, so the effect of RSC inactivation needs the context-sensitive whisker stimulus.

In [21]:
for rsc in ['RSC', 'RSC_2']:
    res = {}
    for lab, S, thr in readings():
        eff = {(tt, c): effect(S, rsc, c, tt, thr) for tt in ['no_stim_trial', 'auditory_trial'] for c in (0, 1)}
        res[lab] = all(v == 0 for v in eff.values())
        print(f'{rsc}, {lab}: no effect in any group: {res[lab]}  {eff}')
    print(rsc, 'all readings agree:', len(set(res.values())) == 1, set(res.values()))
for nl, S in MAPS.items():
    print(nl); print(S[S.name.isin(['RSC', 'RSC_2']) & S.trial_type.isin(['no_stim_trial', 'auditory_trial'])].pivot_table(['dP_mean', 'dprime'], 'name', ['trial_type', 'context']).round(3).to_string())
RSC, null i, d>=0.5: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC, null i, d>=0.8: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC, null i, d>=2.0: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC, null ii, d>=0.5: no effect in any group: False  {('no_stim_trial', 0): 1, ('no_stim_trial', 1): 1, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC, null ii, d>=0.8: no effect in any group: False  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 1, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC, null ii, d>=2.0: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC all readings agree: False {False, True}
RSC_2, null i, d>=0.5: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC_2, null i, d>=0.8: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC_2, null i, d>=2.0: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC_2, null ii, d>=0.5: no effect in any group: False  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 1, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC_2, null ii, d>=0.8: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC_2, null ii, d>=2.0: no effect in any group: True  {('no_stim_trial', 0): 0, ('no_stim_trial', 1): 0, ('auditory_trial', 0): 0, ('auditory_trial', 1): 0}
RSC_2 all readings agree: False {False, True}
blocks
                  dP_mean                                     dprime                            
trial_type auditory_trial        no_stim_trial        auditory_trial        no_stim_trial       
context                 0      1             0      1              0      1             0      1
name                                                                                            
RSC                -0.005  0.014         0.051  0.117          0.103  0.092         0.203  0.291
RSC_2              -0.010  0.021         0.034  0.089          0.046  0.152         0.235  0.223
trials
                  dP_mean                                     dprime                            
trial_type auditory_trial        no_stim_trial        auditory_trial        no_stim_trial       
context                 0      1             0      1              0      1             0      1
name                                                                                            
RSC                -0.005  0.014         0.051  0.117          0.061  0.076         0.531  0.842
RSC_2              -0.010  0.021         0.034  0.089          0.058  0.074         0.385  0.739

Result: blocked (methods_underspecified). The trial-shuffle null finds a catch-trial effect at RSC at d' 0.5 and 0.8 and none at 2; the block-label null finds none.

fig2-no-effect-control-mice¶

In control mice without ChR2, light at the grid sites causes no significant change in lick probability at any site.

In [22]:
print('control mice', CTRL_MICE, 'sites', summC.site.nunique(), 'mice per site', summC.n_mice.value_counts().to_dict())
for tk, tv in THR.items():
    n = int((summC.dprime >= tv).sum())
    print(f'd >= {tv}: site, trial type and context groups passing: {n} of {len(summC)}')
print('largest d prime', summC.dprime.max().round(2), 'at', summC.loc[summC.dprime.idxmax(), ['site', 'trial_type', 'context']].tolist(),
      '| largest |dP|', summC.dP_mean.abs().max().round(3))
print(summC.sort_values('dprime', ascending=False).head(8)[['context', 'trial_type', 'site', 'dP_mean', 'dprime']].round(3).to_string())
control mice ['PB177', 'PB195', 'PB197', 'PB198'] sites 41 mice per site {4: 246}
d >= 0.5: site, trial type and context groups passing: 61 of 246
d >= 0.8: site, trial type and context groups passing: 20 of 246
d >= 2.0: site, trial type and context groups passing: 0 of 246
largest d prime 1.8 at [(-2.5, 2.5), 'no_stim_trial', np.int64(0)] | largest |dP| 0.225
     context      trial_type         site  dP_mean  dprime
49         0   no_stim_trial  (-2.5, 2.5)    0.122   1.799
166        1   no_stim_trial  (-3.5, 2.5)    0.142   1.433
66         0   no_stim_trial   (0.5, 1.5)    0.145   1.379
135        1  auditory_trial  (-1.5, 0.5)   -0.089   1.201
187        1   no_stim_trial  (-0.5, 5.5)    0.099   1.065
202        1   no_stim_trial   (2.5, 2.5)   -0.108   1.042
169        1   no_stim_trial  (-3.5, 5.5)   -0.108   1.038
40         0  auditory_trial   (2.5, 4.5)   -0.225   0.998

Result: blocked (methods_underspecified). In the control mice 61 and 20 groups pass d' 0.5 and 0.8 and none passes 2 (largest 1.80), so the thresholds disagree.

fig2f-latency-frontal-not-rsc¶

Lick latency increases during inactivation of frontal areas but does not change during inactivation of RSC or tjS1.

In [23]:
D = O[(O.early_lick == 0) & (O.lick_flag == 1) & (((O.trial_type == 'auditory_trial')) | ((O.trial_type == 'whisker_trial') & (O.context == 1)))].copy()
D['rt'] = (D.lick_time - D.stim_time) * 1000
D['site'] = list(zip(D.opto_grid_ap.round(2), D.opto_grid_ml.round(2)))
D.loc[D.opto_stim == 0, 'site'] = 'control'
rows = []
for tt, G in D.groupby('trial_type'):
    pm = G.groupby(['mouse_id', 'site']).rt.mean().unstack()
    for name in ['wM1', 'wM2', 'ALM', 'RSC', 'RSC_2', 'tjS1', 'wS1', 'A1']:
        s = bech.SITES[name]
        x = pm[s].dropna(); c = pm.loc[x.index, 'control']
        rows.append((tt, name, (x - c).mean(), abs(bech.dprime(x.values, c.values)), len(x)))
LAT = pd.DataFrame(rows, columns=['trial_type', 'name', 'dRT_ms', 'dprime', 'n_mice'])
print(LAT.round(2).to_string())
for tk, tv in THR.items():
    fr = any(((LAT.name == n) & (LAT.dRT_ms > 0) & (LAT.dprime >= tv)).any() for n in ['wM1', 'wM2', 'ALM'])
    nochange = not ((LAT.name.isin(['RSC', 'tjS1'])) & (LAT.dprime >= tv)).any()
    print(f'd >= {tv}: frontal increase {fr}; RSC and tjS1 unchanged {nochange} ->', 'reproduced' if fr and nochange else ('partially' if fr or nochange else 'not'))
        trial_type   name  dRT_ms  dprime  n_mice
0   auditory_trial    wM1  157.30    1.01       6
1   auditory_trial    wM2   77.77    0.75       7
2   auditory_trial    ALM   95.90    0.62       7
3   auditory_trial    RSC  -27.68    0.39       7
4   auditory_trial  RSC_2   -0.96    0.01       7
5   auditory_trial   tjS1   13.35    0.17       7
6   auditory_trial    wS1  -25.06    0.30       7
7   auditory_trial     A1   -9.87    0.15       5
8    whisker_trial    wM1  119.86    1.10       7
9    whisker_trial    wM2  128.15    1.09       6
10   whisker_trial    ALM  198.27    1.49       6
11   whisker_trial    RSC  -33.51    0.43       7
12   whisker_trial  RSC_2    0.47    0.01       7
13   whisker_trial   tjS1    9.16    0.11       7
14   whisker_trial    wS1   38.01    0.24       5
15   whisker_trial     A1   -4.79    0.06       7
d >= 0.5: frontal increase True; RSC and tjS1 unchanged True -> reproduced
d >= 0.8: frontal increase True; RSC and tjS1 unchanged True -> reproduced
d >= 2.0: frontal increase False; RSC and tjS1 unchanged True -> partially

Result: blocked (methods_underspecified). Reproduced at d' 0.5 and 0.8; at 2 no frontal site passes, which gives partially reproduced.

supp2-muscimol-ws1-rsc¶

Muscimol in wS1 significantly reduces whisker-trial lick probability in W- and W+, while muscimol in RSC gives a non-significant positive trend in whisker-trial licking in W-; pharmacological inactivation is consistent with the optogenetic results.

As process main_analysis/figure2_supp_stats.py: early licks dropped, session number by date within mouse and condition (third sessions dropped), statistic (muscimol day 2 - day 1) - (Ringer day 2 - day 1), two-level bootstrap (mice, then trials), 100,000 iterations, seed 42, p = twice the tail beyond 0 on the side opposite the observed sign. Whisker trials.

In [24]:
def pharma(cond):
    D = T[T.session_id.isin(LISTS[f'sessions_Context_{cond}']) & (T.early_lick == 0)].copy()
    D['date'] = pd.to_datetime(D.session_id.str.split('_').str[1])
    D['sn'] = D.groupby('mouse_id').date.rank(method='dense')
    return D[D.sn != 3]
rng_seed = 42
for area in ['wS1', 'fpS1', 'RSC']:
    Mu, Ri = pharma(f'muscimol_{area}'), pharma(f'ringer_{area}')
    print(f'{area}: muscimol mice {Mu.mouse_id.nunique()} sessions {Mu.session_id.nunique()}, Ringer mice {Ri.mouse_id.nunique()} sessions {Ri.session_id.nunique()}')
    for ctx in (0, 1):
        g = {}
        for k, D in [('m', Mu), ('r', Ri)]:
            for sn in (1, 2):
                x = D[(D.trial_type == 'whisker_trial') & (D.context == ctx) & (D.sn == sn)]
                g[(k, sn)] = [v.lick_flag.values.astype(float) for _, v in x.groupby('mouse_id')]
        o, bs, _ = bech.hier_boot(g, n_iter=100000, seed=rng_seed)
        p = 2 * ((bs >= 0).mean() if o < 0 else (bs <= 0).mean()); p = min(p, 1.0)
        dm = np.concatenate(g[('m', 2)]).mean() - np.concatenate(g[('m', 1)]).mean()
        dr = np.concatenate(g[('r', 2)]).mean() - np.concatenate(g[('r', 1)]).mean()
        print(f'   {"W+" if ctx else "W-"} whisker: muscimol change {dm:+.3f}, Ringer change {dr:+.3f}, statistic {o:+.3f}, '
              f'95% CI [{np.percentile(bs, 2.5):+.3f}, {np.percentile(bs, 97.5):+.3f}], p {p:.5f} (resolution 2e-5)')
# the injection day is the second date of each mouse in the list (the code's ranking); the files type some sessions pharma_session
STYPE = M.set_index('session_id').session_type
for area in ['wS1', 'fpS1', 'RSC']:
    for cond in ['muscimol', 'ringer']:
        d = pd.DataFrame({'session_id': LISTS[f'sessions_Context_{cond}_{area}']}); d['mouse'] = d.session_id.str.split('_').str[0]
        d['rank'] = d.groupby('mouse').session_id.transform(lambda s: pd.to_datetime(s.str.split('_').str[1]).rank(method='dense')).astype(int)
        d['type'] = d.session_id.map(STYPE)
        print(f'{area} {cond}: sessions by date rank and session_type', d.groupby(['rank', 'type']).size().to_dict())
wS1: muscimol mice 5 sessions 10, Ringer mice 4 sessions 8
   W- whisker: muscimol change -0.352, Ringer change +0.053, statistic -0.405, 95% CI [-0.659, -0.180], p 0.00032 (resolution 2e-5)
   W+ whisker: muscimol change -0.620, Ringer change +0.033, statistic -0.653, 95% CI [-0.909, -0.396], p 0.00000 (resolution 2e-5)
fpS1: muscimol mice 5 sessions 10, Ringer mice 4 sessions 8
   W- whisker: muscimol change -0.031, Ringer change -0.009, statistic -0.022, 95% CI [-0.237, +0.179], p 0.82734 (resolution 2e-5)
   W+ whisker: muscimol change -0.138, Ringer change +0.061, statistic -0.199, 95% CI [-0.349, -0.052], p 0.00772 (resolution 2e-5)
RSC: muscimol mice 8 sessions 16, Ringer mice 4 sessions 8
   W- whisker: muscimol change +0.168, Ringer change -0.038, statistic +0.206, 95% CI [-0.009, +0.422], p 0.06010 (resolution 2e-5)
   W+ whisker: muscimol change -0.089, Ringer change -0.023, statistic -0.066, 95% CI [-0.227, +0.071], p 0.36638 (resolution 2e-5)
wS1 muscimol: sessions by date rank and session_type {(1, 'behaviour_only_session'): 5, (2, 'behaviour_only_session'): 3, (2, 'pharma_session'): 2, (3, 'behaviour_only_session'): 4}
wS1 ringer: sessions by date rank and session_type {(1, 'behaviour_only_session'): 4, (2, 'pharma_session'): 4, (3, 'behaviour_only_session'): 4}
fpS1 muscimol: sessions by date rank and session_type {(1, 'behaviour_only_session'): 5, (2, 'behaviour_only_session'): 1, (2, 'pharma_session'): 4, (3, 'behaviour_only_session'): 3}
fpS1 ringer: sessions by date rank and session_type {(1, 'behaviour_only_session'): 4, (2, 'pharma_session'): 4, (3, 'behaviour_only_session'): 4}
RSC muscimol: sessions by date rank and session_type {(1, 'behaviour_only_session'): 8, (2, 'pharma_session'): 8, (3, 'behaviour_only_session'): 5}
RSC ringer: sessions by date rank and session_type {(1, 'behaviour_only_session'): 4, (2, 'pharma_session'): 4, (3, 'behaviour_only_session'): 4}

Result: reproduced. wS1 muscimol lowers whisker licking in both contexts (p 0.00032 in W-, below 2e-5 in W+), and RSC muscimol gives a positive W- change with p 0.060, inside 0.05 to 0.1.

Widefield imaging (Figure 3, Figure 4C, supplement 4D)¶

Grid ROI ΔF/F0 traces (brain_grid_fluorescence/dff0_grid_traces, 42 circles at the grid sites, named by (AP, ML)), aligned on the stimulus time of each trial. The claims file's conventions: correct trials only, averages over trials per session, then sessions per mouse, then mice; d' across mice, signed, ddof 0. Baseline readings: (a) 50 ms and (b) 250 ms before the stimulus (Methods), and the code's 100 ms as a variant. Mouse lines come from the code's lists (session-list-link).

In [25]:
WF_LISTS = ['sessions_Context_sessions_expert_WF_jrGECO', 'sessions_Context_sessions_expert_WF_gcamp',
            'sessions_Context_sessions_expert_WF_tomato', 'sessions_Context_sessions_expert_WF_GFP',
            'sessions_Context_sessions_wf_opto', 'sessions_Context_sessions_wf_opto_photoactivation']
wf_ids = sorted(set().union(*[LISTS[n] for n in WF_LISTS]))
G = bech.load_grid(A[A.session_id.isin(wf_ids)], pre=0.3, post=0.3, n=8)
print('sessions loaded', len(G), 'failed', [k for k, v in G.items() if v[0] is None])
rates = pd.Series({k: round(1 / np.median(np.diff(v[1]))) for k, v in G.items()})
print('frame rate (Hz) per session:', rates.value_counts().to_dict())
for n in WF_LISTS:
    print(n, 'rates', rates.reindex(LISTS[n]).value_counts().to_dict())
lags = np.concatenate([v[3][np.isfinite(v[2][:, 0, 0])] for v in G.values()])
print('trials inside the imaging: ', len(lags), 'of', sum(len(v[3]) for v in G.values()), '| lag of the first frame after the stimulus (ms): median', round(np.nanmedian(lags) * 1000, 1), 'max', round(np.nanmax(lags) * 1000, 1))
# trials whose first frame after the stimulus comes more than one frame late (a gap in the imaging)
LATE = {k: (v[3] > np.median(np.diff(v[1])) + 1e-6) & np.isfinite(v[2][:, 0, 0]) for k, v in G.items()}
lt = pd.Series({k: int(v.sum()) for k, v in LATE.items()})
print('trials with a lag above one frame:', lt.sum(), 'of', len(lags), 'in', (lt > 0).sum(), 'of', len(lt), 'sessions; per list:',
      {n.replace('sessions_Context_sessions_', ''): int(lt.reindex(LISTS[n]).sum()) for n in WF_LISTS})
allv = np.concatenate([np.nanpercentile(v[2], [1, 99]) for v in G.values()])
print('dF/F0 1st to 99th percentile over sessions:', np.round(allv.min(), 4), np.round(allv.max(), 4))
names0 = G[wf_ids[0]][0]; print('grid ROI names', len(names0), names0[:3], '...')
print('all sessions have the same ROI order:', all(v[0] == names0 for v in G.values()))
ROI = ['wS1', 'wS2', 'wM1', 'wM2', 'ALM', 'tjS1', 'tjM1', 'A1', 'RSC']
SIDX = bech.site_index(names0)
COL = {n: SIDX[bech.SITES[n]] for n in ROI + ['RSC_2']}
TT = T.set_index(['session_id', T.groupby('session_id').cumcount()])

def trial_table(sid):
    return T[T.session_id == sid].sort_values('start_time').reset_index(drop=True)

def mouse_traces(sids, select, baseline_ms, subtract=True, drop_late=False):
    # per mouse mean trace (time x site): trials -> session -> mouse. select(trials) -> boolean mask
    per = {}
    for sid in sids:
        names, t, W, lag = G[sid]
        tr = trial_table(sid)
        assert len(tr) == W.shape[0], sid
        m = select(tr).values
        if drop_late: m = m & ~LATE[sid]
        if m.sum() == 0: continue
        X = W[m]
        if subtract:
            b = (t < 0) & (t >= -baseline_ms / 1000 - 1e-9)
            X = X - np.nanmean(X[:, b, :], axis=1, keepdims=True)
        per.setdefault(sid.split('_')[0], []).append((t, np.nanmean(X, 0)))
    out = {}
    for mouse, lst in per.items():
        t = lst[0][0]
        out[mouse] = (t, np.mean([x for _, x in lst], 0), len(lst))
    return out

def stack(mt):
    mice = sorted(mt); t = mt[mice[0]][0]
    return t, np.stack([mt[m][1] for m in mice]), mice

wplus_hit = lambda tr: (tr.trial_type == 'whisker_trial') & (tr.context == 1) & (tr.lick_flag == 1)
wminus_miss = lambda tr: (tr.trial_type == 'whisker_trial') & (tr.context == 0) & (tr.lick_flag == 0)
aud_hit = lambda c: (lambda tr: (tr.trial_type == 'auditory_trial') & (tr.context == c) & (tr.lick_flag == 1))
BASES = [50, 250, 100]
JR = LISTS['sessions_Context_sessions_expert_WF_jrGECO']
sessions loaded 143 failed []
frame rate (Hz) per session: {100: 97, 50: 46}
sessions_Context_sessions_expert_WF_jrGECO rates {100: 25}
sessions_Context_sessions_expert_WF_gcamp rates {100: 33}
sessions_Context_sessions_expert_WF_tomato rates {100: 15}
sessions_Context_sessions_expert_WF_GFP rates {100: 24}
sessions_Context_sessions_wf_opto rates {50: 40}
sessions_Context_sessions_wf_opto_photoactivation rates {50: 6}
trials inside the imaging:  71866 of 71867 | lag of the first frame after the stimulus (ms): median 4.6 max 81030.4
trials with a lag above one frame: 910 of 71866 in 46 of 143 sessions; per list: {'expert_WF_jrGECO': 0, 'expert_WF_gcamp': 0, 'expert_WF_tomato': 0, 'expert_WF_GFP': 0, 'wf_opto': 833, 'wf_opto_photoactivation': 77}
dF/F0 1st to 99th percentile over sessions: -0.0471 0.4053
grid ROI names 42 ['(2.5, 5.5)', '(1.5, 5.5)', '(0.5, 5.5)'] ...
all sessions have the same ROI order: True

fig3e-auditory-similar-across-contexts¶

Auditory-evoked cortical activity is similar in W+ and W-, beginning in A1, then RSC, then medial secondary motor regions (wM1/2), then orofacial motor cortices (tjS1, ALM).

In [26]:
res = {}
for base in BASES:
    t, Xp, mice = stack(mouse_traces(JR, aud_hit(1), base)); _, Xm, _ = stack(mouse_traces(JR, aud_hit(0), base))
    d = bech.dprime(Xp, Xm)
    w = (t >= 0.02 - 1e-9) & (t <= 0.12 + 1e-9)
    maxd = {n: np.nanmax(np.abs(d[w, COL[n]])) for n in ROI}
    similar = all(v <= 2 for v in maxd.values())
    print(f'baseline {base} ms, {len(mice)} mice; max |d prime| W+ vs W- from 20 to 120 ms:', {k: round(v, 2) for k, v in maxd.items()}, '-> similar', similar)
    for ctx, X in [('W+', Xp), ('W-', Xm)]:
        mtr = X.mean(0); w0 = (t >= -1e-9) & (t <= 0.12 + 1e-9)
        for rd in ['peak', 'half']:
            tim = {}
            for n in ROI:
                y = mtr[w0, COL[n]]; tt = t[w0]
                tim[n] = tt[np.argmax(y)] if rd == 'peak' else tt[np.argmax(y >= y.max() / 2)]
            twm = min(tim['wM1'], tim['wM2'])
            order = tim['A1'] < tim['RSC'] < twm < min(tim['tjS1'], tim['ALM'])
            a1first = tim['A1'] <= min(tim[n] for n in ROI)
            oc = 'reproduced' if similar and order else ('partially' if similar and a1first else 'not')
            res[(base, ctx, rd)] = oc
            print(f'   {ctx} {rd}: times (ms)', {k: int(round(v * 1000)) for k, v in tim.items()}, f'order holds {order}, A1 first {a1first} -> {oc}')
print('outcomes per reading:', res)
print('baselines (a) and (b) agree:', len({v for k, v in res.items() if k[0] in (50, 250)}) == 1)
baseline 50 ms, 6 mice; max |d prime| W+ vs W- from 20 to 120 ms: {'wS1': np.float32(0.23), 'wS2': np.float32(0.19), 'wM1': np.float32(0.25), 'wM2': np.float32(0.31), 'ALM': np.float32(0.42), 'tjS1': np.float32(0.39), 'tjM1': np.float32(0.42), 'A1': np.float32(0.06), 'RSC': np.float32(0.16)} -> similar True
   W+ peak: times (ms) {'wS1': 120, 'wS2': 120, 'wM1': 120, 'wM2': 120, 'ALM': 120, 'tjS1': 120, 'tjM1': 120, 'A1': 120, 'RSC': 120} order holds False, A1 first True -> partially
   W+ half: times (ms) {'wS1': 90, 'wS2': 80, 'wM1': 80, 'wM2': 80, 'ALM': 80, 'tjS1': 90, 'tjM1': 90, 'A1': 40, 'RSC': 80} order holds False, A1 first True -> partially
   W- peak: times (ms) {'wS1': 120, 'wS2': 120, 'wM1': 120, 'wM2': 120, 'ALM': 120, 'tjS1': 120, 'tjM1': 120, 'A1': 120, 'RSC': 120} order holds False, A1 first True -> partially
   W- half: times (ms) {'wS1': 90, 'wS2': 80, 'wM1': 90, 'wM2': 90, 'ALM': 90, 'tjS1': 90, 'tjM1': 90, 'A1': 40, 'RSC': 80} order holds False, A1 first True -> partially
baseline 250 ms, 6 mice; max |d prime| W+ vs W- from 20 to 120 ms: {'wS1': np.float32(0.29), 'wS2': np.float32(0.23), 'wM1': np.float32(0.25), 'wM2': np.float32(0.26), 'ALM': np.float32(0.43), 'tjS1': np.float32(0.59), 'tjM1': np.float32(0.75), 'A1': np.float32(0.09), 'RSC': np.float32(0.15)} -> similar True
   W+ peak: times (ms) {'wS1': 120, 'wS2': 120, 'wM1': 120, 'wM2': 120, 'ALM': 120, 'tjS1': 120, 'tjM1': 120, 'A1': 120, 'RSC': 120} order holds False, A1 first True -> partially
   W+ half: times (ms) {'wS1': 90, 'wS2': 80, 'wM1': 80, 'wM2': 80, 'ALM': 80, 'tjS1': 80, 'tjM1': 90, 'A1': 40, 'RSC': 80} order holds False, A1 first True -> partially
   W- peak: times (ms) {'wS1': 120, 'wS2': 120, 'wM1': 120, 'wM2': 120, 'ALM': 120, 'tjS1': 120, 'tjM1': 120, 'A1': 120, 'RSC': 120} order holds False, A1 first True -> partially
   W- half: times (ms) {'wS1': 90, 'wS2': 80, 'wM1': 90, 'wM2': 90, 'ALM': 90, 'tjS1': 90, 'tjM1': 90, 'A1': 40, 'RSC': 80} order holds False, A1 first True -> partially
baseline 100 ms, 6 mice; max |d prime| W+ vs W- from 20 to 120 ms: {'wS1': np.float32(0.37), 'wS2': np.float32(0.19), 'wM1': np.float32(0.25), 'wM2': np.float32(0.29), 'ALM': np.float32(0.4), 'tjS1': np.float32(0.41), 'tjM1': np.float32(0.42), 'A1': np.float32(0.06), 'RSC': np.float32(0.1)} -> similar True
   W+ peak: times (ms) {'wS1': 120, 'wS2': 120, 'wM1': 120, 'wM2': 120, 'ALM': 120, 'tjS1': 120, 'tjM1': 120, 'A1': 120, 'RSC': 120} order holds False, A1 first True -> partially
   W+ half: times (ms) {'wS1': 90, 'wS2': 80, 'wM1': 80, 'wM2': 80, 'ALM': 80, 'tjS1': 80, 'tjM1': 90, 'A1': 40, 'RSC': 80} order holds False, A1 first True -> partially
   W- peak: times (ms) {'wS1': 120, 'wS2': 120, 'wM1': 120, 'wM2': 120, 'ALM': 120, 'tjS1': 120, 'tjM1': 120, 'A1': 120, 'RSC': 120} order holds False, A1 first True -> partially
   W- half: times (ms) {'wS1': 90, 'wS2': 80, 'wM1': 90, 'wM2': 90, 'ALM': 90, 'tjS1': 90, 'tjM1': 90, 'A1': 40, 'RSC': 80} order holds False, A1 first True -> partially
outcomes per reading: {(50, 'W+', 'peak'): 'partially', (50, 'W+', 'half'): 'partially', (50, 'W-', 'peak'): 'partially', (50, 'W-', 'half'): 'partially', (250, 'W+', 'peak'): 'partially', (250, 'W+', 'half'): 'partially', (250, 'W-', 'peak'): 'partially', (250, 'W-', 'half'): 'partially', (100, 'W+', 'peak'): 'partially', (100, 'W+', 'half'): 'partially', (100, 'W-', 'peak'): 'partially', (100, 'W-', 'half'): 'partially'}
baselines (a) and (b) agree: True

Result: partially reproduced. No ROI reaches |d'| 2 between contexts and A1 is first under every reading, but the order RSC, wM1/2, tjS1 and ALM is not found.

fig3f-whisker-divergence-after-50ms¶

In whisker trials, wS1 and wS2 activate similarly in both contexts early after the stimulus, and from about 50 ms activity diverges, with more activity in RSC and wM1/2 in W+ than in W-.

In [27]:
D3 = {}
for base in BASES:
    t, Xp, mice = stack(mouse_traces(JR, wplus_hit, base)); _, Xm, _ = stack(mouse_traces(JR, wminus_miss, base))
    d = bech.dprime(Xp, Xm); D3[base] = (t, d, Xp, Xm)
    e = (t >= 0.02 - 1e-9) & (t <= 0.05 + 1e-9); l = (t >= 0.05 - 1e-9) & (t <= 0.12 + 1e-9)
    early = {n: np.nanmax(np.abs(d[e, COL[n]])) for n in ['wS1', 'wS2']}
    late = {n: np.nanmax(d[l, COL[n]]) for n in ['RSC', 'wM1', 'wM2']}
    ok_early = all(v <= 2 for v in early.values()); rsc = late['RSC'] > 2; wm = max(late['wM1'], late['wM2']) > 2
    oc = 'reproduced' if ok_early and rsc and wm else ('partially' if ok_early and (rsc or wm) else 'not')
    print(f'baseline {base} ms, {len(mice)} mice: early max |d| {dict((k, round(v, 2)) for k, v in early.items())}; '
          f'late max d {dict((k, round(v, 2)) for k, v in late.items())} -> {oc}')
    print('   d prime by time (ms) for RSC, wM1, wM2, wS1, wS2:')
    sel = (t >= -1e-9) & (t <= 0.15)
    print(pd.DataFrame({n: d[sel, COL[n]] for n in ['RSC', 'wM1', 'wM2', 'wS1', 'wS2']}, index=np.round(t[sel] * 1000).astype(int)).round(2).T.to_string())
baseline 50 ms, 6 mice: early max |d| {'wS1': np.float32(0.91), 'wS2': np.float32(0.94)}; late max d {'RSC': np.float32(3.7), 'wM1': np.float32(3.14), 'wM2': np.float32(2.77)} -> reproduced
   d prime by time (ms) for RSC, wM1, wM2, wS1, wS2:
      0     10    20    30    40    50    60    70    80    90    100   110   120   130   140   150
RSC  0.20  0.26  0.57  1.16  1.98  2.43  2.66  2.73  2.82  2.98  3.25  3.48  3.70  3.86  4.05  4.22
wM1  0.58  0.17  0.01  0.34  0.65  1.01  1.39  1.79  2.09  2.37  2.67  2.90  3.14  3.37  3.61  3.86
wM2  0.68  0.23  0.13  0.30  0.63  0.81  1.04  1.35  1.63  1.94  2.25  2.52  2.77  3.00  3.26  3.54
wS1 -0.11 -0.29  0.08  0.43  0.67  0.91  1.21  1.53  1.75  1.92  2.12  2.29  2.44  2.61  2.79  2.97
wS2 -0.12 -0.16  0.14  0.55  0.75  0.94  1.19  1.38  1.57  1.75  1.92  2.05  2.18  2.30  2.43  2.57
baseline 250 ms, 6 mice: early max |d| {'wS1': np.float32(0.97), 'wS2': np.float32(1.08)}; late max d {'RSC': np.float32(3.49), 'wM1': np.float32(3.23), 'wM2': np.float32(2.84)} -> reproduced
   d prime by time (ms) for RSC, wM1, wM2, wS1, wS2:
      0     10    20    30    40    50    60    70    80    90    100   110   120   130   140   150
RSC -0.32 -0.24  0.05  0.52  1.18  1.73  2.13  2.34  2.52  2.72  3.00  3.26  3.49  3.66  3.86  4.04
wM1  0.55  0.35  0.29  0.50  0.83  1.21  1.57  1.95  2.23  2.49  2.77  3.00  3.23  3.44  3.68  3.92
wM2  0.42  0.27  0.23  0.35  0.80  0.95  1.15  1.44  1.71  2.02  2.32  2.59  2.84  3.06  3.32  3.59
wS1  0.45  0.09  0.25  0.53  0.74  0.97  1.28  1.61  1.85  2.02  2.22  2.38  2.54  2.70  2.88  3.07
wS2  0.42  0.31  0.41  0.73  0.89  1.08  1.32  1.52  1.70  1.87  2.03  2.15  2.28  2.40  2.52  2.67
baseline 100 ms, 6 mice: early max |d| {'wS1': np.float32(0.95), 'wS2': np.float32(1.05)}; late max d {'RSC': np.float32(3.65), 'wM1': np.float32(3.19), 'wM2': np.float32(2.8)} -> reproduced
   d prime by time (ms) for RSC, wM1, wM2, wS1, wS2:
      0     10    20    30    40    50    60    70    80    90    100   110   120   130   140   150
RSC -0.25 -0.14  0.24  0.85  1.67  2.20  2.51  2.63  2.75  2.92  3.19  3.43  3.65  3.82  4.01  4.18
wM1  0.91  0.64  0.54  0.66  0.88  1.17  1.50  1.88  2.16  2.43  2.72  2.95  3.19  3.40  3.64  3.88
wM2  0.83  0.60  0.58  0.63  0.86  0.94  1.12  1.40  1.67  1.98  2.28  2.55  2.80  3.02  3.27  3.55
wS1  0.28 -0.04  0.20  0.50  0.72  0.95  1.24  1.56  1.78  1.95  2.15  2.32  2.47  2.64  2.82  3.00
wS2  0.39  0.25  0.37  0.71  0.88  1.05  1.27  1.45  1.63  1.80  1.97  2.09  2.21  2.33  2.46  2.60

Result: reproduced. wS1 and wS2 stay below |d'| 2 from 20 to 50 ms, and RSC, wM1 and wM2 pass d' 2 between 50 and 120 ms under every baseline.

fig3h-rsc-first-context-discrimination¶

RSC is the first cortical area to discriminate the contexts in whisker trials, both in the pixel-wise maps and in the ROI averages, the time of the first d' above 2 between W+ and W-.

ROI part on the grid ROI traces. Pixel part on the ΔF/F0 image stack (processing/ophys/dff0): only the frames of the selected trials are read (250 ms before to 120 ms after the stimulus, 38 frames per trial), baseline-subtracted per trial, averaged per session, then per mouse; d' per pixel across the 6 mice; for each ROI the earliest crossing among the pixels of its 1 mm circle (the file's grid masks, grid_areas/brain_grid_area_segmentation), with the code's Gaussian smoothing of sigma 1 pixel on the mouse-average images and without it as a variant. The Methods for Figure 3H define d' as that "shown in Figure 3F bottom row", whose Methods (Figures 3E&F) subtract the 50 ms baseline, while the Methods' Computation of ΔF/F0 give 250 ms for Figures 3 and 4.

In [28]:
def first_cross(t, dfun, start):
    first = {}
    for n in ['wS1', 'wS2', 'wM1', 'RSC', 'ALM', 'tjS1']:
        w = [k for k in range(len(t)) if t[k] >= start - 1e-9 and dfun(k, n) > 2]
        first[n] = int(round(t[w[0]] * 1000)) if w else None
    valid = {k: v for k, v in first.items() if v is not None}
    best = min(valid.values()) if valid else None
    rsc = first['RSC'] is not None and first['RSC'] == best
    tie = sum(v == best for v in valid.values()) > 1 if valid else None
    return first, rsc, tie
H = {}
print('ROI part')
for base in BASES:
    t, d, _, _ = D3[base]
    for start in [0.02, 0.03]:
        first, rsc, tie = first_cross(t, lambda k, n: d[k, COL[n]], start)
        H[('roi', base, start)] = 'reproduced' if rsc and not tie else ('tie' if rsc else 'not')
        print(f'   baseline {base} ms, from {int(start * 1000)} ms: first d>2 (ms) {first}; RSC earliest {rsc}, tie {tie}')
print('   trials whose first frame after the stimulus is more than one frame late, jRGECO1a sessions:', int(sum(LATE[k].sum() for k in JR)))
# pixel part
pgroups = {sid: {'W+ hit': np.where(wplus_hit(trial_table(sid)))[0], 'W- miss': np.where(wminus_miss(trial_table(sid)))[0]} for sid in JR}
import time
t_pix = time.time()
PIX = bech.load_pixels(A[A.session_id.isin(JR)], pgroups, n=12)
t_pix = time.time() - t_pix
GB_PIX = sum(v['n']['W+ hit'] + v['n']['W- miss'] for v in PIX.values() if 'n' in v) * (bech.PIX_PRE + bech.PIX_POST) * 125 * 160 * 8 / 1e9
print(f'pixel reads: {GB_PIX:.1f} GB in {t_pix / 60:.1f} min, {GB_PIX / t_pix * 1000:.0f} MB/s with 12 parallel reads')
print('pixel part: sessions failed', [k for k, v in PIX.items() if 'error' in v])
P0 = next(iter(PIX.values()))
print('stack', P0['info'], '| trials read per session, W+ hits', pd.Series({k: v['n']['W+ hit'] for k, v in PIX.items()}).describe().round(0).to_dict(),
      '| W- misses', pd.Series({k: v['n']['W- miss'] for k, v in PIX.items()}).describe().round(0).to_dict())
print('pixels without data (NaN, outside the brain) per frame:', int(np.isnan(P0['means']['W+ hit'][50][0]).sum()), 'of', P0['means']['W+ hit'][50][0].size,
      '| grid masks identical in every session:', all((v['masks'] == P0['masks']).all() for v in PIX.values()),
      '| pixels per ROI circle', int(P0['masks'][SIDX[bech.SITES['RSC']]].sum()))
from scipy.ndimage import gaussian_filter
JR_MICE = sorted({s.split('_')[0] for s in JR})
tp = np.arange(bech.PIX_POST) / 100
for base in BASES:
    for smooth in (True, False):
        X = {}
        for g in ('W+ hit', 'W- miss'):
            per = []
            for mo in JR_MICE:
                x = np.mean([v['means'][g][base] for k, v in PIX.items() if k.startswith(mo + '_') and v['n'][g] > 0], 0)
                if smooth: x = np.stack([gaussian_filter(np.nan_to_num(f), 1) for f in x])
                per.append(x)
            X[g] = np.stack(per)
        dp = bech.dprime(X['W+ hit'], X['W- miss'])
        masks = {n: P0['masks'][SIDX[bech.SITES[n]]].astype(bool) for n in ROI}
        for start in [0.02, 0.03]:
            first, rsc, tie = first_cross(tp, lambda k, n: np.nanmax(dp[k][masks[n]]), start)
            H[('pixel', smooth, base, start)] = 'reproduced' if rsc and not tie else ('tie' if rsc else 'not')
            print(f'   pixels, {"smoothed" if smooth else "unsmoothed (variant)"}, baseline {base} ms, from {int(start * 1000)} ms: first d>2 (ms) {first}; RSC earliest {rsc}, tie {tie}')
for base in [50, 250]:
    v = {H[('roi', base, s)] for s in (0.02, 0.03)} | {H[('pixel', True, base, s)] for s in (0.02, 0.03)}
    print(f'baseline {base} ms, ROI and smoothed pixel versions, both exclusion readings:', v)
ROI part
   baseline 50 ms, from 20 ms: first d>2 (ms) {'wS1': 100, 'wS2': 110, 'wM1': 80, 'RSC': 50, 'ALM': 110, 'tjS1': 110}; RSC earliest True, tie False
   baseline 50 ms, from 30 ms: first d>2 (ms) {'wS1': 100, 'wS2': 110, 'wM1': 80, 'RSC': 50, 'ALM': 110, 'tjS1': 110}; RSC earliest True, tie False
   baseline 250 ms, from 20 ms: first d>2 (ms) {'wS1': 90, 'wS2': 100, 'wM1': 80, 'RSC': 60, 'ALM': 100, 'tjS1': 100}; RSC earliest True, tie False
   baseline 250 ms, from 30 ms: first d>2 (ms) {'wS1': 90, 'wS2': 100, 'wM1': 80, 'RSC': 60, 'ALM': 100, 'tjS1': 100}; RSC earliest True, tie False
   baseline 100 ms, from 20 ms: first d>2 (ms) {'wS1': 100, 'wS2': 110, 'wM1': 80, 'RSC': 50, 'ALM': 110, 'tjS1': 110}; RSC earliest True, tie False
   baseline 100 ms, from 30 ms: first d>2 (ms) {'wS1': 100, 'wS2': 110, 'wM1': 80, 'RSC': 50, 'ALM': 110, 'tjS1': 110}; RSC earliest True, tie False
   trials whose first frame after the stimulus is more than one frame late, jRGECO1a sessions: 0
pixel reads: 22.1 GB in 2.8 min, 132 MB/s with 12 parallel reads
pixel part: sessions failed []
stack {'shape': (377564, 125, 160), 'dtype': 'float64', 'chunks': None, 'rate': np.float64(100.00000000009095)} | trials read per session, W+ hits {'count': 25.0, 'mean': 78.0, 'std': 19.0, 'min': 31.0, '25%': 67.0, '50%': 80.0, '75%': 91.0, 'max': 109.0} | W- misses {'count': 25.0, 'mean': 67.0, 'std': 20.0, 'min': 32.0, '25%': 55.0, '50%': 67.0, '75%': 77.0, 'max': 112.0}
pixels without data (NaN, outside the brain) per frame: 566 of 20000 | grid masks identical in every session: True | pixels per ROI circle 249
   pixels, smoothed, baseline 50 ms, from 20 ms: first d>2 (ms) {'wS1': 90, 'wS2': 80, 'wM1': 50, 'RSC': 40, 'ALM': 110, 'tjS1': 110}; RSC earliest True, tie False
   pixels, smoothed, baseline 50 ms, from 30 ms: first d>2 (ms) {'wS1': 90, 'wS2': 80, 'wM1': 50, 'RSC': 40, 'ALM': 110, 'tjS1': 110}; RSC earliest True, tie False
   pixels, unsmoothed (variant), baseline 50 ms, from 20 ms: first d>2 (ms) {'wS1': 80, 'wS2': 80, 'wM1': 40, 'RSC': 30, 'ALM': 100, 'tjS1': 100}; RSC earliest True, tie False
   pixels, unsmoothed (variant), baseline 50 ms, from 30 ms: first d>2 (ms) {'wS1': 80, 'wS2': 80, 'wM1': 40, 'RSC': 30, 'ALM': 100, 'tjS1': 100}; RSC earliest True, tie False
   pixels, smoothed, baseline 250 ms, from 20 ms: first d>2 (ms) {'wS1': 80, 'wS2': 70, 'wM1': 50, 'RSC': 50, 'ALM': 100, 'tjS1': 100}; RSC earliest True, tie True
   pixels, smoothed, baseline 250 ms, from 30 ms: first d>2 (ms) {'wS1': 80, 'wS2': 70, 'wM1': 50, 'RSC': 50, 'ALM': 100, 'tjS1': 100}; RSC earliest True, tie True
   pixels, unsmoothed (variant), baseline 250 ms, from 20 ms: first d>2 (ms) {'wS1': 80, 'wS2': 60, 'wM1': 30, 'RSC': 50, 'ALM': 90, 'tjS1': 30}; RSC earliest False, tie True
   pixels, unsmoothed (variant), baseline 250 ms, from 30 ms: first d>2 (ms) {'wS1': 80, 'wS2': 60, 'wM1': 30, 'RSC': 50, 'ALM': 90, 'tjS1': 30}; RSC earliest False, tie True
   pixels, smoothed, baseline 100 ms, from 20 ms: first d>2 (ms) {'wS1': 90, 'wS2': 80, 'wM1': 50, 'RSC': 40, 'ALM': 100, 'tjS1': 100}; RSC earliest True, tie False
   pixels, smoothed, baseline 100 ms, from 30 ms: first d>2 (ms) {'wS1': 90, 'wS2': 80, 'wM1': 50, 'RSC': 40, 'ALM': 100, 'tjS1': 100}; RSC earliest True, tie False
   pixels, unsmoothed (variant), baseline 100 ms, from 20 ms: first d>2 (ms) {'wS1': 80, 'wS2': 60, 'wM1': 40, 'RSC': 30, 'ALM': 30, 'tjS1': 100}; RSC earliest True, tie True
   pixels, unsmoothed (variant), baseline 100 ms, from 30 ms: first d>2 (ms) {'wS1': 80, 'wS2': 60, 'wM1': 40, 'RSC': 30, 'ALM': 30, 'tjS1': 100}; RSC earliest True, tie True
baseline 50 ms, ROI and smoothed pixel versions, both exclusion readings: {'reproduced'}
baseline 250 ms, ROI and smoothed pixel versions, both exclusion readings: {'reproduced', 'tie'}

Result: blocked (methods_underspecified). With the 50 ms baseline, which the Methods for Figure 3H take from Figure 3F, RSC is the earliest area in both the ROI ranking and the smoothed pixel version, under both exclusion readings, with no tie. With the 250 ms baseline RSC is first in the ROI ranking but ties with wM1 in the pixel version (50 ms), which counts as partially reproduced; the unsmoothed pixel variant at 250 ms puts wM1 and tjS1 first. The criterion asks for the outcome every baseline gives, otherwise methods_underspecified, and the claims file names both the 50 and 250 ms baselines; since they disagree, the criterion gives blocked (methods_underspecified). The paper states both baselines, so which one Figure 3H uses is a question for the authors.

fig3-gcamp-consistent-controls-flat¶

GCaMP6f mice show whisker-evoked dynamics consistent with jRGECO1a mice, and calcium-insensitive tdTomato and GFP control mice show none of these dynamics.

Evoked response at an ROI: d' >= 1 across mice between the (not baseline-subtracted) value at some time from 20 to 120 ms and the mean of the baseline window, W+ hits, the Methods' rule for Figure 3C applied to ΔF/F0.

In [29]:
def evoked(sids, base):
    t, X, mice = stack(mouse_traces(sids, wplus_hit, base, subtract=False))
    b = (t < 0) & (t >= -base / 1000 - 1e-9)
    B = np.nanmean(X[:, b, :], 1)
    w = (t >= 0.02 - 1e-9) & (t <= 0.12 + 1e-9)
    dd = np.array([bech.dprime(X[:, i, :], B) for i in np.where(w)[0]])
    return dd, mice
res = {}
for base in BASES:
    for line, n in [('GCaMP6f', 'sessions_Context_sessions_expert_WF_gcamp'), ('tdTomato', 'sessions_Context_sessions_expert_WF_tomato'), ('GFP', 'sessions_Context_sessions_expert_WF_GFP')]:
        sids = LISTS[n]
        dd, mice = evoked(sids, base)
        ev = np.nanmax(dd[:, COL['wS1']])
        t, Xp, _ = stack(mouse_traces(sids, wplus_hit, base)); _, Xm, _ = stack(mouse_traces(sids, wminus_miss, base))
        d = bech.dprime(Xp, Xm)
        l = (t >= 0.05 - 1e-9) & (t <= 0.12 + 1e-9); w = (t >= 0.02 - 1e-9) & (t <= 0.12 + 1e-9)
        ctxd = max(np.nanmax(d[l, COL[k]]) for k in ['RSC', 'wM1', 'wM2'])
        anyd = max(np.nanmax(np.abs(d[w, COL[k]])) for k in ROI)
        peak = np.nanmax(Xp.mean(0)[w, COL['wS1']])
        res[(base, line)] = (ev, ctxd, anyd)
        print(f'baseline {base} ms, {line} ({len(mice)} mice): wS1 evoked d max {ev:.2f}, wS1 mean peak dF/F0 {peak:.4f}; '
              f'max W+ > W- d in RSC/wM1/wM2 (50-120 ms) {ctxd:.2f}; max |d| W+ vs W- over ROIs (20-120 ms) {anyd:.2f}')
    g = res[(base, 'GCaMP6f')]; gc = g[0] >= 1 and g[1] > 2
    ctrl = all(res[(base, l)][0] < 1 and res[(base, l)][2] <= 2 for l in ['tdTomato', 'GFP'])
    print(f'   GCaMP6f part {gc}; controls part {ctrl} ->', 'reproduced' if gc and ctrl else ('partially' if gc or ctrl else 'not'))
baseline 50 ms, GCaMP6f (8 mice): wS1 evoked d max 3.48, wS1 mean peak dF/F0 0.0101; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 3.36; max |d| W+ vs W- over ROIs (20-120 ms) 3.36
baseline 50 ms, tdTomato (4 mice): wS1 evoked d max 0.37, wS1 mean peak dF/F0 0.0024; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 2.77; max |d| W+ vs W- over ROIs (20-120 ms) 2.91
baseline 50 ms, GFP (6 mice): wS1 evoked d max 0.23, wS1 mean peak dF/F0 0.0014; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 3.43; max |d| W+ vs W- over ROIs (20-120 ms) 3.43
   GCaMP6f part True; controls part False -> partially
baseline 250 ms, GCaMP6f (8 mice): wS1 evoked d max 3.55, wS1 mean peak dF/F0 0.0102; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 3.36; max |d| W+ vs W- over ROIs (20-120 ms) 3.36
baseline 250 ms, tdTomato (4 mice): wS1 evoked d max 0.39, wS1 mean peak dF/F0 0.0025; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 3.59; max |d| W+ vs W- over ROIs (20-120 ms) 4.67
baseline 250 ms, GFP (6 mice): wS1 evoked d max 0.23, wS1 mean peak dF/F0 0.0015; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 3.58; max |d| W+ vs W- over ROIs (20-120 ms) 3.58
   GCaMP6f part True; controls part False -> partially
baseline 100 ms, GCaMP6f (8 mice): wS1 evoked d max 3.52, wS1 mean peak dF/F0 0.0101; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 3.34; max |d| W+ vs W- over ROIs (20-120 ms) 3.34
baseline 100 ms, tdTomato (4 mice): wS1 evoked d max 0.37, wS1 mean peak dF/F0 0.0024; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 2.80; max |d| W+ vs W- over ROIs (20-120 ms) 3.10
baseline 100 ms, GFP (6 mice): wS1 evoked d max 0.23, wS1 mean peak dF/F0 0.0014; max W+ > W- d in RSC/wM1/wM2 (50-120 ms) 3.51; max |d| W+ vs W- over ROIs (20-120 ms) 3.51
   GCaMP6f part True; controls part False -> partially

Result: partially reproduced. The GCaMP6f part holds under every baseline; tdTomato and GFP mice have no evoked wS1 response but do show W+ against W- differences above d' 2.

fig4c-inhibition-propagates-forward¶

Inhibiting wS1 decreases activity widely across cortex, inhibiting wM1/2 decreases activity among motor areas while leaving whisker sensory responses intact, and inhibiting RSC does not increase activity in wM1/2 or tongue-jaw motor regions.

Whisker trials in W+, the 4 widefield-with-optogenetics mice (50 Hz imaging), by laser site; control is laser off the brain (opto_stim 0). Peak ΔF/F0 from 50 to 120 ms per ROI.

In [30]:
WO = LISTS['sessions_Context_sessions_wf_opto']
def site_sel(site):
    def f(tr):
        base = (tr.trial_type == 'whisker_trial') & (tr.context == 1)
        if site == 'control': return base & (tr.opto_stim == 0)
        ap, ml = bech.SITES[site]
        return base & (tr.opto_stim == 1) & np.isclose(tr.opto_grid_ap, ap) & np.isclose(tr.opto_grid_ml, ml)
    return f
wo_trials = T[T.session_id.isin(WO)]
print('wf-opto sites stimulated:', wo_trials[wo_trials.opto_stim == 1].groupby(['opto_grid_ap', 'opto_grid_ml']).size().shape[0],
      '| control laser coordinates', wo_trials[wo_trials.opto_stim == 0][['opto_grid_ap', 'opto_grid_ml']].value_counts().to_dict())
DROP_LATE = False
def peaks(sids, site, base):
    mt = mouse_traces(sids, site_sel(site), base, drop_late=DROP_LATE)
    t, X, mice = stack(mt)
    w = (t >= 0.05 - 1e-9) & (t <= 0.12 + 1e-9)
    return pd.DataFrame(np.nanmax(X[:, w, :], 1)[:, [COL[n] for n in ROI]], index=mice, columns=ROI)
def fig4c(sids, base, sites):
    C = peaks(sids, 'control', base)
    out = {}
    for s in sites:
        P = peaks(sids, s, base)
        diff = P.mean() - C.loc[P.index].mean(); sd = C.loc[P.index].std(ddof=1)
        out[s] = (diff, sd, P.mean(), len(P))
    return C, out
print('late-frame trials in the wf-opto sessions:', int(sum(LATE[k].sum() for k in WO)), 'of', int(sum(len(LATE[k]) for k in WO)))
for base, DROP_LATE in [(50, False), (250, False), (50, True)]:
    if DROP_LATE: print('variant: trials whose first frame after the stimulus is more than one frame late left out')
    C, out = fig4c(WO, base, ['wS1', 'wM1', 'wM2', 'RSC'])
    print(f'baseline {base} ms; control peak (mean over {len(C)} mice):', C.mean().round(4).to_dict())
    dec = {s: (o[0] < -o[1]) for s, o in out.items()}
    for s, o in out.items():
        print(f'   laser at {s} ({o[3]} mice): peak minus control', o[0].round(4).to_dict(), '| decreased:', [k for k, v in dec[s].items() if v])
    p1 = dec['wS1'].sum() > len(ROI) / 2
    p2 = any(dec[s][['wM1', 'wM2', 'ALM', 'tjM1']].any() and not dec[s][['wS1', 'wS2']].any() for s in ['wM1', 'wM2'])
    up = out['RSC'][0] > out['RSC'][1]
    p3 = not up[['wM1', 'wM2', 'ALM', 'tjM1', 'tjS1']].any()
    p1, p2, p3 = bool(p1), bool(p2), bool(p3)
    n = int(p1) + int(p2) + int(p3)
    print(f'   parts: wS1 widespread {p1} ({dec["wS1"].sum()} of {len(ROI)}), wM1/2 motor only {p2}, RSC no increase {p3} ->',
          'reproduced' if n == 3 else ('partially' if n == 2 else 'not'))
DROP_LATE = False
wf-opto sites stimulated: 45 | control laser coordinates {(-5.0, 5.0): 10754}
late-frame trials in the wf-opto sessions: 833 of 21425
baseline 50 ms; control peak (mean over 4 mice): {'wS1': 0.020899999886751175, 'wS2': 0.012799999676644802, 'wM1': 0.018699999898672104, 'wM2': 0.016499999910593033, 'ALM': 0.012400000356137753, 'tjS1': 0.007300000172108412, 'tjM1': 0.010099999606609344, 'A1': 0.0015999999595806003, 'RSC': 0.022600000724196434}
   laser at wS1 (4 mice): peak minus control {'wS1': 0.017100000753998756, 'wS2': 0.008299999870359898, 'wM1': -0.028300000354647636, 'wM2': -0.01979999989271164, 'ALM': -0.020899999886751175, 'tjS1': -0.02239999920129776, 'tjM1': -0.025800000876188278, 'A1': -0.011699999682605267, 'RSC': -0.029600000008940697} | decreased: ['wM1', 'wM2', 'ALM', 'tjS1', 'tjM1', 'A1', 'RSC']
   laser at wM1 (4 mice): peak minus control {'wS1': -0.004000000189989805, 'wS2': -0.0006000000284984708, 'wM1': 0.0019000000320374966, 'wM2': -0.013000000268220901, 'ALM': -0.016899999231100082, 'tjS1': -0.01600000075995922, 'tjM1': -0.019300000742077827, 'A1': 0.009999999776482582, 'RSC': -0.006000000052154064} | decreased: ['wM2', 'ALM', 'tjS1', 'tjM1']
   laser at wM2 (4 mice): peak minus control {'wS1': 0.005100000184029341, 'wS2': 0.0035000001080334187, 'wM1': -0.019300000742077827, 'wM2': 0.006399999838322401, 'ALM': -0.012000000104308128, 'tjS1': -0.010400000028312206, 'tjM1': -0.018300000578165054, 'A1': 0.012299999594688416, 'RSC': 0.006399999838322401} | decreased: ['wM1', 'ALM', 'tjS1', 'tjM1']
   laser at RSC (4 mice): peak minus control {'wS1': -0.012500000186264515, 'wS2': -0.00279999990016222, 'wM1': -0.010700000450015068, 'wM2': -0.004600000102072954, 'ALM': -0.002899999963119626, 'tjS1': -0.0017999999690800905, 'tjM1': -0.00419999985024333, 'A1': 0.00860000029206276, 'RSC': -0.004100000020116568} | decreased: ['wS1', 'wM1', 'wM2', 'ALM', 'tjM1']
   parts: wS1 widespread True (7 of 9), wM1/2 motor only True, RSC no increase True -> reproduced
baseline 250 ms; control peak (mean over 4 mice): {'wS1': 0.020899999886751175, 'wS2': 0.012799999676644802, 'wM1': 0.018699999898672104, 'wM2': 0.016599999740719795, 'ALM': 0.012600000016391277, 'tjS1': 0.007699999958276749, 'tjM1': 0.010300000198185444, 'A1': 0.0015999999595806003, 'RSC': 0.022600000724196434}
   laser at wS1 (4 mice): peak minus control {'wS1': 0.01730000041425228, 'wS2': 0.009200000204145908, 'wM1': -0.027300000190734863, 'wM2': -0.019200000911951065, 'ALM': -0.020500000566244125, 'tjS1': -0.023000000044703484, 'tjM1': -0.026399999856948853, 'A1': -0.012500000186264515, 'RSC': -0.02590000070631504} | decreased: ['wM1', 'wM2', 'ALM', 'tjS1', 'tjM1', 'A1', 'RSC']
   laser at wM1 (4 mice): peak minus control {'wS1': -0.003100000089034438, 'wS2': 0.001500000013038516, 'wM1': 0.0038999998942017555, 'wM2': -0.010999999940395355, 'ALM': -0.015399999916553497, 'tjS1': -0.014600000344216824, 'tjM1': -0.01850000023841858, 'A1': 0.009999999776482582, 'RSC': -0.0071000000461936} | decreased: ['wM2', 'ALM', 'tjS1', 'tjM1', 'RSC']
   laser at wM2 (4 mice): peak minus control {'wS1': 0.005200000014156103, 'wS2': 0.004000000189989805, 'wM1': -0.018799999728798866, 'wM2': 0.006599999964237213, 'ALM': -0.011900000274181366, 'tjS1': -0.00989999994635582, 'tjM1': -0.018200000748038292, 'A1': 0.012600000016391277, 'RSC': 0.006599999964237213} | decreased: ['wM1', 'ALM', 'tjS1', 'tjM1']
   laser at RSC (4 mice): peak minus control {'wS1': -0.011500000022351742, 'wS2': -0.002300000051036477, 'wM1': -0.009700000286102295, 'wM2': -0.003700000001117587, 'ALM': -0.0027000000700354576, 'tjS1': -0.002199999988079071, 'tjM1': -0.00430000014603138, 'A1': 0.009800000116229057, 'RSC': -0.00279999990016222} | decreased: ['wS1', 'wM1', 'tjM1']
   parts: wS1 widespread True (7 of 9), wM1/2 motor only True, RSC no increase True -> reproduced
variant: trials whose first frame after the stimulus is more than one frame late left out
baseline 50 ms; control peak (mean over 4 mice): {'wS1': 0.023000000044703484, 'wS2': 0.014100000262260437, 'wM1': 0.020899999886751175, 'wM2': 0.01860000006854534, 'ALM': 0.014399999752640724, 'tjS1': 0.009399999864399433, 'tjM1': 0.012299999594688416, 'A1': 0.002099999925121665, 'RSC': 0.025200000032782555}
   laser at wS1 (4 mice): peak minus control {'wS1': 0.015399999916553497, 'wS2': 0.007400000002235174, 'wM1': -0.03099999949336052, 'wM2': -0.022099999710917473, 'ALM': -0.023000000044703484, 'tjS1': -0.02500000037252903, 'tjM1': -0.0284000001847744, 'A1': -0.01269999984651804, 'RSC': -0.03269999846816063} | decreased: ['wM1', 'wM2', 'ALM', 'tjS1', 'tjM1', 'A1', 'RSC']
   laser at wM1 (4 mice): peak minus control {'wS1': -0.004999999888241291, 'wS2': -0.00139999995008111, 'wM1': 0.00139999995008111, 'wM2': -0.014100000262260437, 'ALM': -0.01810000091791153, 'tjS1': -0.01769999973475933, 'tjM1': -0.0210999995470047, 'A1': 0.010099999606609344, 'RSC': -0.007199999876320362} | decreased: ['wM2', 'ALM', 'tjS1', 'tjM1', 'RSC']
   laser at wM2 (4 mice): peak minus control {'wS1': 0.003000000026077032, 'wS2': 0.002099999925121665, 'wM1': -0.0215000007301569, 'wM2': 0.004399999976158142, 'ALM': -0.013899999670684338, 'tjS1': -0.012500000186264515, 'tjM1': -0.020500000566244125, 'A1': 0.011800000444054604, 'RSC': 0.0038999998942017555} | decreased: ['wM1', 'ALM', 'tjS1', 'tjM1']
   laser at RSC (4 mice): peak minus control {'wS1': -0.013399999588727951, 'wS2': -0.003100000089034438, 'wM1': -0.011800000444054604, 'wM2': -0.005499999970197678, 'ALM': -0.004000000189989805, 'tjS1': -0.0031999999191612005, 'tjM1': -0.005499999970197678, 'A1': 0.00860000029206276, 'RSC': -0.005200000014156103} | decreased: ['wS1', 'wM1', 'wM2', 'ALM', 'tjM1']
   parts: wS1 widespread True (7 of 9), wM1/2 motor only True, RSC no increase True -> reproduced

Result: reproduced. All three parts hold under both baselines; wS1 inhibition lowers 7 of 9 ROIs, wM1 inhibition lowers motor ROIs and not wS1 or wS2, and RSC inhibition raises no motor ROI.

supp4d-photoactivation-control¶

In mice expressing jRGECO1a without ChR2, the laser gives only a local photoactivation effect and none of the widespread inhibition seen in ChR2 mice.

In [31]:
PA = LISTS['sessions_Context_sessions_wf_opto_photoactivation']
pa_tr = T[T.session_id.isin(PA)]
print('photoactivation sessions', len(PA), 'mice', pa_tr.mouse_id.nunique(), '| sites', pa_tr[pa_tr.opto_stim == 1].groupby(['opto_grid_ap', 'opto_grid_ml']).size().to_dict())
print('frame rates', rates.reindex(PA).to_dict())
for base in [50, 250]:
    C = peaks(PA, 'control', base)
    for s in ['wS1', 'wM1', 'wM2']:
        try:
            P = peaks(PA, s, base)
        except Exception as e:
            print(f'baseline {base}: no trials at {s}'); continue
        diff = P.mean() - C.loc[P.index].mean(); sd = C.loc[P.index].std(ddof=1)
        others = [r for r in ROI if r != s]
        fall = int((diff[others] < -sd[others]).sum())
        print(f'baseline {base} ms, laser at {s} ({len(P)} mice): stimulated ROI minus control {diff[s]:+.4f}; '
              f'other ROIs below control by more than SD: {fall} of {len(others)} -> holds {diff[s] > 0 and fall < len(others) / 2}')
        print('    differences', diff.round(4).to_dict())
photoactivation sessions 6 mice 2 | sites {(-3.5, 0.5): 80, (-3.5, 1.5): 76, (-3.5, 2.5): 76, (-3.5, 3.5): 81, (-3.5, 4.5): 80, (-3.5, 5.5): 79, (-2.5, 0.5): 77, (-2.5, 1.5): 79, (-2.5, 2.5): 73, (-2.5, 3.5): 78, (-2.5, 4.5): 79, (-2.5, 5.5): 77, (-1.5, 0.5): 81, (-1.5, 1.5): 76, (-1.5, 2.5): 73, (-1.5, 3.5): 77, (-1.5, 4.5): 80, (-1.5, 5.5): 79, (-0.5, 0.5): 87, (-0.5, 1.5): 80, (-0.5, 2.5): 83, (-0.5, 3.5): 79, (-0.5, 4.5): 79, (-0.5, 5.5): 77, (0.5, 0.5): 74, (0.5, 1.5): 77, (0.5, 2.5): 77, (0.5, 3.5): 77, (0.5, 4.5): 87, (0.5, 5.5): 76, (1.5, 0.5): 80, (1.5, 1.5): 81, (1.5, 2.5): 78, (1.5, 3.5): 82, (1.5, 4.5): 78, (1.5, 5.5): 78, (2.5, 0.5): 76, (2.5, 1.5): 84, (2.5, 2.5): 81, (2.5, 3.5): 77, (2.5, 4.5): 75, (3.5, 0.5): 77, (3.5, 1.5): 76, (3.5, 2.5): 78, (3.5, 3.5): 75}
frame rates {'PB205_20250714_155405': 50, 'PB205_20250715_151308': 50, 'PB205_20250716_101640': 50, 'PB206_20250714_173130': 50, 'PB206_20250716_134222': 50, 'PB206_20250717_104356': 50}
baseline 50 ms, laser at wS1 (2 mice): stimulated ROI minus control +0.0491; other ROIs below control by more than SD: 0 of 8 -> holds True
    differences {'wS1': 0.04910000041127205, 'wS2': 0.03700000047683716, 'wM1': 0.0034000000450760126, 'wM2': 0.002400000113993883, 'ALM': 0.005799999926239252, 'tjS1': 0.010599999688565731, 'tjM1': 0.010300000198185444, 'A1': 0.007499999832361937, 'RSC': 0.003800000064074993}
baseline 50 ms, laser at wM1 (2 mice): stimulated ROI minus control +0.0411; other ROIs below control by more than SD: 1 of 8 -> holds True
    differences {'wS1': 0.006200000178068876, 'wS2': 0.006200000178068876, 'wM1': 0.041099999099969864, 'wM2': 0.02419999986886978, 'ALM': 0.015300000086426735, 'tjS1': 0.004100000020116568, 'tjM1': 0.006800000090152025, 'A1': -0.0008999999845400453, 'RSC': 0.003599999938160181}
baseline 50 ms, laser at wM2 (2 mice): stimulated ROI minus control +0.0389; other ROIs below control by more than SD: 1 of 8 -> holds True
    differences {'wS1': 0.00570000009611249, 'wS2': 0.003800000064074993, 'wM1': 0.013899999670684338, 'wM2': 0.03889999911189079, 'ALM': 0.01759999990463257, 'tjS1': -0.003000000026077032, 'tjM1': 0.002099999925121665, 'A1': -0.0010000000474974513, 'RSC': 0.0027000000700354576}
baseline 250 ms, laser at wS1 (2 mice): stimulated ROI minus control +0.0469; other ROIs below control by more than SD: 0 of 8 -> holds True
    differences {'wS1': 0.04690000042319298, 'wS2': 0.035599999129772186, 'wM1': 0.003000000026077032, 'wM2': 0.002400000113993883, 'ALM': 0.005499999970197678, 'tjS1': 0.010499999858438969, 'tjM1': 0.010300000198185444, 'A1': 0.009100000374019146, 'RSC': 0.002099999925121665}
baseline 250 ms, laser at wM1 (2 mice): stimulated ROI minus control +0.0405; other ROIs below control by more than SD: 1 of 8 -> holds True
    differences {'wS1': 0.003700000001117587, 'wS2': 0.004000000189989805, 'wM1': 0.04050000011920929, 'wM2': 0.024700000882148743, 'ALM': 0.015399999916553497, 'tjS1': 0.003000000026077032, 'tjM1': 0.006800000090152025, 'A1': -0.000699999975040555, 'RSC': 0.00139999995008111}
baseline 250 ms, laser at wM2 (2 mice): stimulated ROI minus control +0.0398; other ROIs below control by more than SD: 1 of 8 -> holds True
    differences {'wS1': 0.004800000227987766, 'wS2': 0.005799999926239252, 'wM1': 0.013100000098347664, 'wM2': 0.039799999445676804, 'ALM': 0.020099999383091927, 'tjS1': 0.0, 'tjM1': 0.0038999998942017555, 'A1': -0.0006000000284984708, 'RSC': 0.00039999998989515007}

Result: reproduced. At wS1, wM1 and wM2 the stimulated ROI rises above control and at most 1 of 8 other ROIs falls by more than the control SD.

Orofacial tracking (Figure 1I-J, Figure 3B-C)¶

Sessions: the four widefield expert groups (claims file, 24 mice, 97 sessions). The DLC series are stored in pixels (with a conversion of 1/28 or 1/24 and the unit "seconds"); the measures are computed from the tracked points as the Methods define them (Behavioral kinematics; Figures 1I-J), with the side camera's 28 pixels/mm (Methods, Behavior videography). Whisker trials only, early-lick trials dropped, mean over the 2 s before the stimulus per trial, then per session, then per mouse.

In [32]:
FACE = sorted(set().union(*[LISTS[n] for n in WF_LISTS[:4]]))
DLC = bech.load_dlc(A[A.session_id.isin(FACE)], n=8)
bad = {k: v['error'] for k, v in DLC.items() if 'error' in v}
print('sessions', len(DLC), 'mice', len({k.split('_')[0] for k in DLC}), '| failed to load:', bad)
ok = {k: v for k, v in DLC.items() if 'error' not in v}
LEN = pd.DataFrame({k: v['lengths'] for k, v in ok.items()}).T
LEN_BAD = LEN[(LEN.jaw_timestamps != LEN.jaw_data) | (LEN.whisker_timestamps != LEN.whisker_data)]
print('sessions whose DLC timestamps and data differ in length (both cut to the shorter):', len(LEN_BAD), 'of', len(LEN))
print(LEN_BAD.to_string())
print('video rate (Hz):', pd.Series({k: round(v['rate']) for k, v in ok.items()}).value_counts().to_dict())
frac = pd.DataFrame({k: v['frac'] for k, v in ok.items()}).T
print('fraction of points passing the likelihood filter, by body part:'); print(frac.describe().round(3).to_string())
print('sessions kept (>= 70% of points):', (frac >= bech.KEEP_FRACTION).sum().to_dict())
pre = []
for k, v in ok.items():
    p = v['pre'].copy(); tr = trial_table(k) if k in G else T[T.session_id == k].sort_values('start_time').reset_index(drop=True)
    assert len(tr) == len(p)
    p = pd.concat([tr[['trial_type', 'context', 'lick_flag', 'early_lick']].reset_index(drop=True), p], axis=1)
    p['session_id'] = k; p['mouse_id'] = k.split('_')[0]
    for part, cols in [('pupil', ['pupil', 'stored_pupil_area']), ('jaw', ['jaw', 'jaw_speed', 'jaw_speed_x200']), ('whisker', ['whisker_angle', 'whisker_speed', 'stored_whisker_angle', 'stored_whisker_speed'])]:
        if frac.loc[k, part] < bech.KEEP_FRACTION: p[cols] = np.nan
    pre.append(p)
PRE = pd.concat(pre, ignore_index=True)
PW = PRE[(PRE.trial_type == 'whisker_trial') & (PRE.early_lick == 0)]
print('whisker trials', len(PW), '| value ranges (1st, 99th percentile):')
for c in ['pupil', 'jaw', 'whisker_angle', 'jaw_speed', 'whisker_speed', 'stored_pupil_area', 'stored_whisker_angle', 'stored_whisker_speed']:
    print('  ', c, np.nanpercentile(PW[c], [1, 99]).round(3), 'missing', PW[c].isna().mean().round(3))
def mouse_means(col, by):
    s = PW.dropna(subset=[col]).groupby(['mouse_id', 'session_id', by])[col].mean()
    return s.groupby(['mouse_id', by]).mean().unstack()
def paired(col, by, a, b):
    m = mouse_means(col, by).dropna()
    r = stats.ttest_rel(m[a], m[b])
    return m, r
sessions 97 mice 24 | failed to load: {}
sessions whose DLC timestamps and data differ in length (both cut to the shorter): 76 of 97
                       jaw_timestamps  jaw_data  whisker_timestamps  whisker_data
PB177_20240528_093711          526784    526780              526784        526780
PB177_20240527_135745          728838    728839              728838        728839
PB177_20240530_113408          851934    851930              851934        851850
PB177_20240529_121819          955705    953445              955705        948779
PB177_20240606_104234          795762    795760              795762        795760
PB177_20240607_161204          716821    716790              716821        716790
PB178_20240529_101445          421918    421920              421918        421920
PB178_20240607_115237          488556    488560              488556        488560
PB185_20240831_123411          819216    819220              819216        819220
PB185_20240830_105945         1214276   1214280             1214276       1214280
PB187_20240806_132010         1062915   1062915             1062915       1062520
PB187_20240809_111335          883234    883230              883234        883150
PB187_20240807_091702         1320036   1320040             1320036       1320040
PB178_20240608_132641          734894    734890              734894        734890
PB188_20240821_170100          873662    873660              873662        873660
PB188_20240824_130819         1005301   1005300             1005301       1005300
PB188_20240822_153551         1278787   1278789             1278788       1278789
PB189_20240820_155808          835936    835940              835936        835940
PB189_20240821_142007          826688    826690              826688        826690
PB191_20241202_102608          881341    881340              881341        881340
PB191_20241121_094747          970391    970390              970391        970390
PB191_20241128_104818         1012611   1012610             1012611       1012610
PB192_20241121_122848         1116888    311339             1116888       1116890
PB192_20241126_113401         1111592   1111590             1111592       1111590
PB192_20241122_115247         1349076   1349080             1349076       1349080
PB192_20241127_121115         1039023   1039020             1039023       1039020
PB192_20241128_164232         1240416   1240420             1240416       1240420
PB193_20241119_112050         1298211   1298210             1298211       1298210
PB193_20241122_135140         1041268   1041270             1041268       1041260
PB193_20241127_134816         1114862   1114860             1114862       1114860
PB194_20241210_175040          671881    671880              671881        671880
PB195_20241118_105242          918663    918660              918663        918660
PB195_20241120_112711         1202882   1202880             1202882       1202880
PB195_20241122_100713         1088638   1088640             1088638       1088640
PB195_20241127_103029         1023713   1023710             1023713       1023710
PB196_20241122_122220          619721    619720              619721        618569
PB197_20241121_112305          648341    648340              648340        648340
PB197_20241122_132228         1094579   1094570             1094579       1094575
PB197_20241126_151654          891278    891280              891278        891280
PB198_20241121_123544          986042    986040              986042        986040
PB198_20241120_131355         1230099   1230099             1230099       1229910
PB198_20241122_150719         1297333   1297330             1297333       1297330
PB198_20241119_111415         1656081   1656080             1656081       1656080
PB200_20241210_162223          550291    550290              550291        550290
PB201_20241120_182145          904616    904620              904616        904620
PB200_20241211_115117          940801    940770              940801        940770
PB201_20241129_142056          908462    908460              908462        908460
PB201_20241203_145200         1237531   1237530             1237531       1237530
RD039_20240222_145509          503156    503160              503156        503100
RD039_20240228_182245          465568    465570              465568        465570
RD043_20240229_145751          236138    236140              236138        236140
RD043_20240301_104556          354747    354749              354747        354749
RD045_20240227_183215          359887    359889              360344        360340
RD045_20240228_171641          287532    287530              287532        287530
RD045_20240229_172110          297835    297829              297835        297829
RD045_20240301_141157          454428    454430              454428        454430
RD049_20240601_125108          635914    635910              635914        635910
RD049_20240605_115240          626653    626650              626653        626650
RD049_20240610_112214          695677    695679              695677        695679
RD049_20240611_134805          626692    626690              626692        626690
RD049_20240613_124245          948572    948570              948572        948570
RD054_20240816_085656          725116    725120              725116        725120
RD054_20240813_100047         1533881   1533880             1533881       1533880
RD054_20240823_080514          924177    924179              924177        924179
RD054_20240822_092158         1202001   1202000             1202001       1202000
RD055_20240809_105347          886272    886270              886272        886270
RD055_20240814_104525          701578    701580              701578        701580
RD055_20240816_100734          946117    946119              946117        946119
RD055_20240819_105516          836292    836290              836292        836290
RD055_20240821_094632         1210573   1210570             1210573       1210570
RD055_20240823_093660          864777    864779              864777        864779
RD056_20240809_122313          941972    941970              941972        941970
RD056_20240827_084507          872474    872470              872474        872470
RD056_20240829_083808          757181    757180              757181        757180
RD056_20240830_081606          854058    854060              854058        854060
RD057_20240824_091953          967838    967840              967838        967840
video rate (Hz): {200: 89, 100: 8}
fraction of points passing the likelihood filter, by body part:
          jaw   pupil  whisker
count  97.000  97.000   97.000
mean    0.764   0.987    0.958
std     0.181   0.092    0.101
min     0.248   0.092    0.431
25%     0.663   0.998    0.974
50%     0.799   0.999    0.990
75%     0.920   0.999    0.997
max     0.986   1.000    1.000
sessions kept (>= 70% of points): {'jaw': 65, 'pupil': 96, 'whisker': 92}
whisker trials 18570 | value ranges (1st, 99th percentile):
   pupil [0.218 1.023] missing 0.024
   jaw [-0.057  0.714] missing 0.293
   whisker_angle [ 69.882 108.363] missing 0.054
   jaw_speed [ 0.461 10.809] missing 0.293
   whisker_speed [ 17.614 870.604] missing 0.055
   stored_pupil_area [170.933 813.162] missing 0.024
   stored_whisker_angle [ 71.868 125.121] missing 0.054
   stored_whisker_speed [  10.895 1149.453] missing 0.055

fig1i-pupil-larger-wplus¶

Before the whisker stimulus, pupil area is larger in W+ than in W- (0.52 ± 0.13 against 0.50 ± 0.12 mm2), while whisker angle and jaw opening show no general effect of context.

In [33]:
for col in ['pupil', 'whisker_angle', 'jaw', 'stored_whisker_angle']:
    m, r = paired(col, 'context', 1, 0)
    print(f'{col}: W+ {m[1].mean():.3f} ± {m[1].std():.3f}, W- {m[0].mean():.3f} ± {m[0].std():.3f}, mice {len(m)}, '
          f't {r.statistic:.2f}, p {r.pvalue:.4f}, Bonferroni x20 {min(1, 20 * r.pvalue):.4f}')
m, r = paired('pupil', 'context', 1, 0)
print('pupil within tolerance:', abs(m[1].mean() - 0.52) <= 0.13, abs(m[0].mean() - 0.50) <= 0.12, '| W+ larger with corrected p < 0.05:', m[1].mean() > m[0].mean() and 20 * r.pvalue < 0.05)
print('per mouse W+ minus W- pupil (mm2):', (m[1] - m[0]).round(4).to_dict())
pupil: W+ 0.534 ± 0.134, W- 0.513 ± 0.127, mice 24, t 3.82, p 0.0009, Bonferroni x20 0.0174
whisker_angle: W+ 87.124 ± 4.645, W- 88.047 ± 5.416, mice 24, t -2.34, p 0.0282, Bonferroni x20 0.5635
jaw: W+ 0.276 ± 0.049, W- 0.261 ± 0.049, mice 21, t 1.60, p 0.1245, Bonferroni x20 1.0000
stored_whisker_angle: W+ 97.329 ± 13.008, W- 98.321 ± 12.570, mice 24, t -2.56, p 0.0176, Bonferroni x20 0.3516
pupil within tolerance: True True | W+ larger with corrected p < 0.05: True
per mouse W+ minus W- pupil (mm2): {'PB177': 0.0423, 'PB178': 0.012, 'PB185': 0.0262, 'PB187': 0.0174, 'PB188': -0.0035, 'PB189': 0.0424, 'PB191': 0.0374, 'PB192': 0.0608, 'PB193': 0.0317, 'PB194': 0.0752, 'PB195': -0.0118, 'PB196': 0.0065, 'PB197': 0.0063, 'PB198': 0.013, 'PB200': 0.0867, 'PB201': -0.0192, 'RD039': 0.0278, 'RD043': -0.0122, 'RD045': 0.0038, 'RD049': 0.0209, 'RD054': 0.0222, 'RD055': 0.0171, 'RD056': 0.0041, 'RD057': -0.0057}

Result: reproduced. Pupil area 0.53 and 0.51 mm2, W+ larger with corrected p below 0.05, and no corrected context effect on whisker angle or jaw opening.

fig1i-posture-before-lick¶

Independently of context, before trials in which the mouse then licks to the whisker stimulus the jaw rests more open (0.27 ± 0.05 against 0.23 ± 0.04 mm) and the whisker is more posterior (97.3 ± 13 against 98.6 ± 12 degrees).

In [34]:
for col, (el, en, tl, tn) in [('jaw', (0.27, 0.23, 0.05, 0.04)), ('whisker_angle', (97.3, 98.6, 13, 12)), ('stored_whisker_angle', (97.3, 98.6, 13, 12))]:
    m, r = paired(col, 'lick_flag', 1, 0)
    print(f'{col}: lick {m[1].mean():.3f} ± {m[1].std():.3f} ({el} ± {tl}: {abs(m[1].mean() - el) <= tl}), no lick {m[0].mean():.3f} ± {m[0].std():.3f} '
          f'({en} ± {tn}: {abs(m[0].mean() - en) <= tn}), mice {len(m)}, t {r.statistic:.2f}, p x20 {min(1, 20 * r.pvalue):.4f}')
jaw: lick 0.282 ± 0.052 (0.27 ± 0.05: True), no lick 0.247 ± 0.041 (0.23 ± 0.04: True), mice 21, t 4.56, p x20 0.0038
whisker_angle: lick 87.040 ± 4.812 (97.3 ± 13: True), no lick 88.361 ± 5.360 (98.6 ± 12: True), mice 24, t -3.96, p x20 0.0123
stored_whisker_angle: lick 97.274 ± 12.901 (97.3 ± 13: True), no lick 98.607 ± 12.434 (98.6 ± 12: True), mice 24, t -4.04, p x20 0.0102

Result: reproduced. The jaw is more open and the whisker angle smaller before lick trials, all four means within tolerance and both corrected p below 0.05. whisker_angle is the Methods' angle computed from the tracked points; stored_whisker_angle, the file's series, is a variant and gives the paper's values.

fig1j-jaw-speed-context¶

Pre-stimulus jaw speed is higher in the rewarded context (3.0 ± 1.0 against 2.5 ± 0.8 mm/s), and also before lick than before no-lick trials, while whisking speed shows no effect of context or lick.

In [35]:
for col in ['jaw_speed', 'jaw_speed_x200', 'whisker_speed', 'stored_whisker_speed']:
    for by in ['context', 'lick_flag']:
        m, r = paired(col, by, 1, 0)
        print(f'{col} by {by}: 1 {m[1].mean():.3f} ± {m[1].std():.3f}, 0 {m[0].mean():.3f} ± {m[0].std():.3f}, mice {len(m)}, t {r.statistic:.2f}, p x20 {min(1, 20 * r.pvalue):.4f}')
m, r = paired('jaw_speed', 'context', 1, 0); m2, r2 = paired('jaw_speed', 'lick_flag', 1, 0)
print('within tolerance: W+', abs(m[1].mean() - 3.0) <= 1.0, 'W-', abs(m[0].mean() - 2.5) <= 0.8, 'lick', abs(m2[1].mean() - 2.8) <= 0.28, 'no lick', abs(m2[0].mean() - 2.6) <= 0.7)
jaw_speed by context: 1 2.963 ± 0.983, 0 2.499 ± 0.809, mice 21, t 4.96, p x20 0.0015
jaw_speed by lick_flag: 1 2.832 ± 0.960, 0 2.578 ± 0.777, mice 21, t 4.15, p x20 0.0099
jaw_speed_x200 by context: 1 2.997 ± 0.941, 0 2.525 ± 0.776, mice 21, t 5.09, p x20 0.0011
jaw_speed_x200 by lick_flag: 1 2.859 ± 0.923, 0 2.614 ± 0.742, mice 21, t 3.73, p x20 0.0263
whisker_speed by context: 1 189.644 ± 86.079, 0 155.823 ± 59.389, mice 24, t 3.81, p x20 0.0182
whisker_speed by lick_flag: 1 175.290 ± 81.726, 0 167.498 ± 58.389, mice 24, t 0.82, p x20 1.0000
stored_whisker_speed by context: 1 219.932 ± 110.647, 0 179.316 ± 85.567, mice 24, t 3.98, p x20 0.0119
stored_whisker_speed by lick_flag: 1 201.192 ± 105.426, 0 196.012 ± 88.618, mice 24, t 0.43, p x20 1.0000
within tolerance: W+ True W- True lick True no lick True

Result: partially reproduced. Jaw speed is higher in W+ and before lick with corrected p below 0.05 and all four means within tolerance, but whisker speed is also higher in W+ (corrected p 0.018), where the claim states no effect.

Gradient-boosted model of the whisker-trial choice (Figure 1K-L)¶

As the claims file gives it (process main_analysis/model_context_behaviour.py; configs/analysis_params/ whisker_classification.yaml; explain_behaviour v1.0.1 preprocessing/trial_features.py and models/behavioural_analysis_GBM.py, read at the commits the claims file cites): the code's 60 sessions of 21 mice; early licks dropped; the five DLC features of the code (bech._model_one); the trial features of explain_behaviour (bech.model_features); whisker trials only; one session held out (numpy default_rng(20), choice over the sessions in list order); categorical columns coded by sorted value; a stratified 67/33 split (random_state 123); Optuna TPE (seed 123, 1000 trials, 80/20 inner split, random_state 123, binary log loss, early stopping 100 rounds on the inner validation split); the final model fitted with early stopping on the test split, as the code does, and on the inner validation split as a variant; balanced accuracy on the test split. XGBoost runs on 4 threads (the code sets 20 for the search), which can change the fitted trees slightly.

In [36]:
import xgboost as xgb, optuna
from sklearn.model_selection import train_test_split
from sklearn.metrics import balanced_accuracy_score, log_loss
MODEL_S = LISTS['session_context_expert_behaviour_model']
MF = bech.load_model_features(A[A.session_id.isin(MODEL_S)], n=8)
print('sessions', len(MF), '| kept or skipped by the 30% rule of the code:', pd.Series({k: v[1] for k, v in MF.items()}).value_counts().to_dict())
MDF = pd.concat([MF[s][0] for s in MODEL_S if MF[s][0] is not None], ignore_index=True)
MFE = bech.model_features(MDF)
FEAT = ['context', 'subject', 'cum_water', 'prev_trial_correct', 'whisker_trial_in_block', 'prev_trial_water', 'last_stimulus_type',
        'prev_whisker_rewarded', 'time_since_last_stimulus', 'lick_flag', 'pupil_area_nanmean', 'jaw_y_nanmean', 'whisker_velocity_mean_abs',
        'whisker_angle_mean', 'jaw_y_mean_abs_diff']
LABELS = ['Context', 'Mouse ID', 'Cumulative water', 'Previous trial correct', 'Whisker trial in block', 'Previous trial water', 'Last stimulus type',
          'Previous whisker rewarded', 'Time since last stimulus', 'Lick flag', 'Pupil Area', 'Jaw y', 'Whisker Speed', 'Whisker Angle', 'Jaw Speed']
MW = MFE[MFE.trial_type == 'whisker_trial']
test_session = np.random.default_rng(20).choice(MW['session'].unique())
MWt, MW = MW[MW.session == test_session], MW[MW.session != test_session]
def code_cats(Xd, maps=None):
    Xd = Xd.copy(); maps = maps or {}
    for col in ['Context', 'Mouse ID', 'Previous trial correct', 'Previous whisker rewarded', 'Last stimulus type']:
        if col not in maps:
            u = Xd[col].unique()
            try: u = np.sort(u)
            except TypeError: pass
            maps[col] = {v: i for i, v in enumerate(u)}
        Xd[col] = Xd[col].map(maps[col])
    return Xd, maps
MX, CMAP = code_cats(MW[FEAT].rename(columns=dict(zip(FEAT, LABELS))))
My = MX.pop('Lick flag').astype(int)
print('whisker trials', len(MX), 'in', MW.session.nunique(), 'sessions of', MW.subject.nunique(), 'mice; held-out session', test_session, len(MWt), 'trials')
print('lick rate', round(My.mean(), 3), '| missing values per feature:', MX.isna().mean().round(3)[MX.isna().mean() > 0].to_dict())
print('feature ranges:', {c: (round(float(MX[c].min()), 2), round(float(MX[c].max()), 2)) for c in MX.columns})
Xtr, Xte, ytr, yte = train_test_split(MX, My, test_size=0.33, random_state=123, stratify=My)
Xo, Xv, yo, yv = train_test_split(Xtr, ytr, test_size=0.2, random_state=123)
def objective(trial):
    p = dict(subsample=trial.suggest_float('subsample', 0.1, 1), learning_rate=trial.suggest_float('learning_rate', 0.0001, 0.5, log=True),
             max_depth=trial.suggest_int('max_depth', 7, 20), min_child_weight=trial.suggest_int('min_child_weight', 1, 200),
             reg_alpha=trial.suggest_float('reg_alpha', 0.001, 10, log=True), reg_lambda=trial.suggest_float('reg_lambda', 0.001, 10, log=True),
             gamma=trial.suggest_float('gamma', 0, 20), colsample_bytree=trial.suggest_float('colsample_bytree', 0.5, 1),
             colsample_bylevel=trial.suggest_float('colsample_bylevel', 0.5, 1), colsample_bynode=trial.suggest_float('colsample_bynode', 0.5, 1),
             n_estimators=trial.suggest_int('n_estimators', 100, 1000), scale_pos_weight=trial.suggest_float('scale_pos_weight', 1, 10))
    m = xgb.XGBClassifier(**p, eval_metric='logloss', early_stopping_rounds=100, random_state=123, verbosity=0, n_jobs=4)
    m.fit(Xo, yo, eval_set=[(Xv, yv)], verbose=False)
    return log_loss(yv, m.predict_proba(Xv)[:, 1])
optuna.logging.set_verbosity(optuna.logging.WARNING)
study = optuna.create_study(direction='minimize', sampler=optuna.samplers.TPESampler(seed=123))
study.optimize(objective, n_trials=1000)
print('Optuna trials', len(study.trials), '| best inner log loss', round(study.best_value, 4), '| best parameters', {k: round(v, 4) for k, v in study.best_params.items()})
def fit_final(Xe, ye):
    m = xgb.XGBClassifier(**study.best_params, objective='binary:logistic', eval_metric='logloss', early_stopping_rounds=100, random_state=123, verbosity=0, n_jobs=4)
    return m.fit(Xtr, ytr, eval_set=[(Xe, ye)], verbose=False)
GBM = fit_final(Xte, yte)
sessions 60 | kept or skipped by the 30% rule of the code: {'ok': 60}
whisker trials 12220 in 59 sessions of 21 mice; held-out session RD055_20240816_100734 187 trials
lick rate 0.577 | missing values per feature: {'Time since last stimulus': 0.004, 'Pupil Area': 0.109, 'Jaw y': 0.025, 'Whisker Speed': 0.002, 'Whisker Angle': 0.002, 'Jaw Speed': 0.025}
feature ranges: {'Context': (0.0, 1.0), 'Mouse ID': (0.0, 20.0), 'Cumulative water': (0.0, 1390.0), 'Previous trial correct': (0.0, 1.0), 'Whisker trial in block': (1.0, 8.0), 'Previous trial water': (0.0, 1.0), 'Last stimulus type': (0.0, 2.0), 'Previous whisker rewarded': (0.0, 1.0), 'Time since last stimulus': (6.21, 140.38), 'Pupil Area': (0.0, 1.0), 'Jaw y': (0.0, 1.0), 'Whisker Speed': (0.0, 1.0), 'Whisker Angle': (0.0, 1.0), 'Jaw Speed': (0.0, 1.0)}
Optuna trials 1000 | best inner log loss 0.4699 | best parameters {'subsample': 0.9808, 'learning_rate': 0.0302, 'max_depth': 11, 'min_child_weight': 13, 'reg_alpha': 0.5327, 'reg_lambda': 0.0025, 'gamma': 0.4716, 'colsample_bytree': 0.9561, 'colsample_bylevel': 0.552, 'colsample_bynode': 0.9714, 'n_estimators': 424, 'scale_pos_weight': 1.0282}

fig1k-model-accuracy¶

A gradient-boosted tree model of the whisker-trial lick choice, from task, history and orofacial features, reaches a cross-validated accuracy of 0.78 on held-out test trials.

Chance for balanced accuracy is 0.5; the accuracy of a model fitted with the lick labels permuted is shown as a reference.

In [37]:
ba = balanced_accuracy_score(yte, GBM.predict(Xte))
print(f'balanced accuracy, test split: {ba:.3f} (0.78 ± 0.078: {abs(ba - 0.78) <= 0.078}) | train {balanced_accuracy_score(ytr, GBM.predict(Xtr)):.3f} | trees {GBM.best_iteration + 1}')
GBMv = fit_final(Xv, yv)
print(f'variant, early stopping on the inner validation split: {balanced_accuracy_score(yte, GBMv.predict(Xte)):.3f}')
Xh, _ = code_cats(MWt[FEAT].rename(columns=dict(zip(FEAT, LABELS))), CMAP); yh = Xh.pop('Lick flag').astype(int)
print(f'held-out session {test_session}: balanced accuracy {balanced_accuracy_score(yh, GBM.predict(Xh)):.3f} on {len(yh)} trials')
yperm = pd.Series(np.random.default_rng(31).permutation(ytr.values), index=ytr.index)
mp = xgb.XGBClassifier(**study.best_params, objective='binary:logistic', eval_metric='logloss', early_stopping_rounds=100, random_state=123, verbosity=0, n_jobs=4)
mp.fit(Xtr, yperm, eval_set=[(Xte, yte)], verbose=False)
print(f'reference, labels of the training split permuted: {balanced_accuracy_score(yte, mp.predict(Xte)):.3f} (chance 0.5)')
balanced accuracy, test split: 0.783 (0.78 ± 0.078: True) | train 0.850 | trees 178
variant, early stopping on the inner validation split: 0.780
held-out session RD055_20240816_100734: balanced accuracy 0.812 on 187 trials
reference, labels of the training split permuted: 0.500 (chance 0.5)

Result: reproduced. The balanced accuracy on the test split is within 0.78 ± 0.078, against 0.50 for the model fitted on permuted labels (printed above).

fig1k-context-strongest-feature¶

Among the model's features, context gives the largest drop in accuracy when permuted, followed by whether the previous whisker trial was rewarded, the cumulative number of rewards and the index of the whisker trial in the block.

Each feature permuted 10,000 times on the test split, the drop in balanced accuracy recorded (claims file).

In [38]:
rng_pi = np.random.default_rng(32)
BOOST, ITR = GBM.get_booster(), (0, GBM.best_iteration + 1)
Xn, yn = Xte.values.astype(np.float32), yte.values
def bacc(p):  # balanced accuracy of the 0.5-threshold prediction, as GBM.predict gives it
    return 0.5 * ((p[yn == 1] > 0.5).mean() + (p[yn == 0] <= 0.5).mean())
base_ba = bacc(BOOST.inplace_predict(Xn, iteration_range=ITR))
print('balanced accuracy of the fast predictor equals that of the model:', np.isclose(base_ba, balanced_accuracy_score(yte, GBM.predict(Xte))))
drops = {}
for j, col in enumerate(Xte.columns):
    Xp_ = Xn.copy(); d = np.empty(10000)
    for i in range(10000):
        Xp_[:, j] = rng_pi.permutation(Xn[:, j])
        d[i] = base_ba - bacc(BOOST.inplace_predict(Xp_, iteration_range=ITR))
    drops[col] = (d.mean(), d.std(), np.percentile(d, 2.5), np.percentile(d, 97.5))
PI = pd.DataFrame(drops, index=['mean drop', 'SD', '2.5%', '97.5%']).T.sort_values('mean drop', ascending=False)
print(PI.round(4).to_string())
top = list(PI.index)
print('order:', top[:5], '| context first:', top[0] == 'Context', '| next three as stated:', top[1:4] == ['Previous whisker rewarded', 'Cumulative water', 'Whisker trial in block'],
      '| the three in the top five:', set(['Previous whisker rewarded', 'Cumulative water', 'Whisker trial in block']) <= set(top[:5]))
balanced accuracy of the fast predictor equals that of the model: True
                           mean drop      SD    2.5%   97.5%
Context                       0.2088  0.0068  0.1954  0.2223
Previous whisker rewarded     0.0355  0.0037  0.0281  0.0428
Cumulative water              0.0214  0.0029  0.0157  0.0271
Whisker trial in block        0.0180  0.0032  0.0117  0.0244
Jaw y                         0.0066  0.0022  0.0023  0.0109
Mouse ID                      0.0050  0.0017  0.0016  0.0084
Whisker Speed                 0.0046  0.0021  0.0005  0.0088
Previous trial water          0.0041  0.0018  0.0007  0.0075
Whisker Angle                 0.0031  0.0017 -0.0001  0.0064
Time since last stimulus      0.0029  0.0022 -0.0015  0.0073
Previous trial correct        0.0012  0.0014 -0.0016  0.0041
Pupil Area                    0.0003  0.0020 -0.0035  0.0041
Jaw Speed                     0.0002  0.0019 -0.0036  0.0040
Last stimulus type           -0.0009  0.0011 -0.0031  0.0014
order: ['Context', 'Previous whisker rewarded', 'Cumulative water', 'Whisker trial in block', 'Jaw y'] | context first: True | next three as stated: True | the three in the top five: True

Result: reproduced. Context gives the largest mean drop in balanced accuracy, followed in order by previous whisker rewarded, cumulative water and whisker trial in block (printed above).

fig1l-shap-whisker-trial-in-block¶

The SHAP values of the whisker-trial-in-block feature follow the behaviour, with a single-trial change after a context transition and a slower further component.

Interventional TreeExplainer, 100 background trials from the training split (random_state 123), over the training and test trials; whisker trials 5 to 8 of a block relabelled -4 to -1 (claims file).

In [39]:
import shap
Xall = pd.concat([Xtr, Xte]).astype(float)
bg = Xtr.sample(min(100, len(Xtr)), random_state=123).astype(float)
expl = shap.TreeExplainer(GBM, data=bg, feature_perturbation='interventional', model_output='raw')
SV = expl.shap_values(Xall)
sv = pd.DataFrame({'pos': Xall['Whisker trial in block'].values, 'ctx': Xall['Context'].values,
                   'shap': SV[:, list(Xall.columns).index('Whisker trial in block')]})
sv['rel'] = np.where(sv.pos >= 5, sv.pos - 9, sv.pos)
ctx_code = {v: k for k, v in CMAP['Context'].items()}
sv['context'] = sv.ctx.map(ctx_code)
print('positions in block:', sv.pos.value_counts().sort_index().to_dict())
tab = sv.groupby(['context', 'rel']).shap.agg(['mean', 'count']).unstack(0)
print(tab.round(4).to_string())
m = sv.groupby(['context', 'rel']).shap.mean()
res = {}
for newc, oldc, sgn, name in [(1, 0, 1, 'W- to W+'), (0, 1, -1, 'W+ to W-')]:
    s1, s2, sm1 = m[(newc, 1)], m[(newc, 2)], m[(oldc, -1)]
    flip = sgn * s1 > 0 and sgn * sm1 < 0
    further = sgn * s2 > sgn * s1
    res[name] = (flip, further)
    print(f'{name}: trial -1 (old block) {sm1:+.4f}, trial 1 {s1:+.4f}, trial 2 {s2:+.4f} -> sign change toward the new context {flip}, trial 2 further {further}')
print('base value', np.round(expl.expected_value, 4), '| SHAP range of the feature', sv.shap.min().round(3), sv.shap.max().round(3))
# variant: the SHAP values of context and whisker trial in block summed, the model's account of both features together
sv['both'] = sv.shap + SV[:, list(Xall.columns).index('Context')]
mb = sv.groupby(['context', 'rel']).both.mean()
print('variant, context + whisker trial in block:', mb.unstack(0).round(3).to_dict())
for newc, oldc, sgn, name in [(1, 0, 1, 'W- to W+'), (0, 1, -1, 'W+ to W-')]:
    print(f'   {name}: trial -1 {mb[(oldc, -1)]:+.3f}, trial 1 {mb[(newc, 1)]:+.3f}, trial 2 {mb[(newc, 2)]:+.3f}, trial 4 {mb[(newc, 4)]:+.3f}')
  8%|==                  | 1010/12220 [00:11<02:02]       
  9%|==                  | 1111/12220 [00:12<01:59]       
 10%|==                  | 1213/12220 [00:13<01:57]       
 11%|==                  | 1315/12220 [00:14<01:56]       
 12%|==                  | 1415/12220 [00:15<01:54]       
 12%|==                  | 1515/12220 [00:16<01:53]       
 13%|===                 | 1615/12220 [00:17<01:51]       
 14%|===                 | 1716/12220 [00:18<01:50]       
 15%|===                 | 1817/12220 [00:19<01:48]       
 16%|===                 | 1919/12220 [00:20<01:47]       
 17%|===                 | 2019/12220 [00:21<01:46]       
 17%|===                 | 2120/12220 [00:22<01:44]       
 18%|====                | 2221/12220 [00:23<01:43]       
 19%|====                | 2320/12220 [00:24<01:42]       
 20%|====                | 2420/12220 [00:25<01:41]       
 21%|====                | 2522/12220 [00:26<01:39]       
 21%|====                | 2624/12220 [00:27<01:38]       
 22%|====                | 2724/12220 [00:28<01:37]       
 23%|=====               | 2827/12220 [00:29<01:36]       
 24%|=====               | 2930/12220 [00:30<01:35]       
 25%|=====               | 3031/12220 [00:31<01:33]       
 26%|=====               | 3134/12220 [00:32<01:32]       
 26%|=====               | 3236/12220 [00:33<01:31]       
 27%|=====               | 3338/12220 [00:34<01:30]       
 28%|======              | 3439/12220 [00:35<01:29]       
 29%|======              | 3541/12220 [00:36<01:28]       
 30%|======              | 3642/12220 [00:37<01:27]       
 31%|======              | 3744/12220 [00:38<01:26]       
 31%|======              | 3844/12220 [00:39<01:24]       
 32%|======              | 3946/12220 [00:40<01:23]       
 33%|=======             | 4046/12220 [00:41<01:22]       
 34%|=======             | 4144/12220 [00:42<01:21]       
 35%|=======             | 4244/12220 [00:43<01:20]       
 36%|=======             | 4346/12220 [00:44<01:19]       
 36%|=======             | 4446/12220 [00:45<01:18]       
 37%|=======             | 4545/12220 [00:46<01:17]       
 38%|========            | 4647/12220 [00:47<01:16]       
 39%|========            | 4748/12220 [00:48<01:15]       
 40%|========            | 4849/12220 [00:49<01:14]       
 40%|========            | 4949/12220 [00:50<01:13]       
 41%|========            | 5047/12220 [00:51<01:12]       
 42%|========            | 5148/12220 [00:52<01:11]       
 43%|=========           | 5248/12220 [00:53<01:10]       
 44%|=========           | 5348/12220 [00:54<01:09]       
 45%|=========           | 5449/12220 [00:55<01:08]       
 45%|=========           | 5548/12220 [00:56<01:07]       
 46%|=========           | 5647/12220 [00:57<01:06]       
 47%|=========           | 5747/12220 [00:58<01:05]       
 48%|==========          | 5850/12220 [00:59<01:04]       
 49%|==========          | 5951/12220 [01:00<01:03]       
 50%|==========          | 6052/12220 [01:01<01:02]       
 50%|==========          | 6154/12220 [01:02<01:01]       
 51%|==========          | 6256/12220 [01:03<01:00]       
 52%|==========          | 6357/12220 [01:04<00:59]       
 53%|===========         | 6459/12220 [01:05<00:57]       
 54%|===========         | 6560/12220 [01:06<00:56]       
 55%|===========         | 6660/12220 [01:07<00:55]       
 55%|===========         | 6763/12220 [01:08<00:54]       
 56%|===========         | 6864/12220 [01:09<00:53]       
 57%|===========         | 6966/12220 [01:10<00:52]       
 58%|============        | 7068/12220 [01:11<00:51]       
 59%|============        | 7167/12220 [01:12<00:50]       
 59%|============        | 7269/12220 [01:13<00:49]       
 60%|============        | 7369/12220 [01:14<00:48]       
 61%|============        | 7471/12220 [01:15<00:47]       
 62%|============        | 7573/12220 [01:16<00:46]       
 63%|=============       | 7675/12220 [01:17<00:45]       
 64%|=============       | 7777/12220 [01:18<00:44]       
 64%|=============       | 7878/12220 [01:19<00:43]       
 65%|=============       | 7982/12220 [01:20<00:42]       
 66%|=============       | 8083/12220 [01:21<00:41]       
 67%|=============       | 8183/12220 [01:22<00:40]       
 68%|==============      | 8283/12220 [01:23<00:39]       
 69%|==============      | 8384/12220 [01:24<00:38]       
 69%|==============      | 8481/12220 [01:25<00:37]       
 70%|==============      | 8578/12220 [01:26<00:36]       
 71%|==============      | 8678/12220 [01:27<00:35]       
 72%|==============      | 8777/12220 [01:28<00:34]       
 73%|===============     | 8874/12220 [01:29<00:33]       
 73%|===============     | 8972/12220 [01:30<00:32]       
 74%|===============     | 9069/12220 [01:31<00:31]       
 75%|===============     | 9166/12220 [01:32<00:30]       
 76%|===============     | 9262/12220 [01:33<00:29]       
 77%|===============     | 9359/12220 [01:34<00:28]       
 77%|===============     | 9456/12220 [01:35<00:27]       
 78%|================    | 9552/12220 [01:36<00:26]       
 79%|================    | 9649/12220 [01:37<00:25]       
 80%|================    | 9748/12220 [01:38<00:24]       
 81%|================    | 9847/12220 [01:39<00:23]       
 81%|================    | 9943/12220 [01:40<00:22]       
 82%|================    | 10038/12220 [01:41<00:21]       
 83%|=================   | 10135/12220 [01:42<00:20]       
 84%|=================   | 10232/12220 [01:43<00:20]       
 85%|=================   | 10327/12220 [01:44<00:19]       
 85%|=================   | 10423/12220 [01:45<00:18]       
 86%|=================   | 10520/12220 [01:46<00:17]       
 87%|=================   | 10617/12220 [01:47<00:16]       
 88%|==================  | 10712/12220 [01:48<00:15]       
 88%|==================  | 10809/12220 [01:49<00:14]       
 89%|==================  | 10906/12220 [01:50<00:13]       
 90%|==================  | 11002/12220 [01:51<00:12]       
 91%|==================  | 11097/12220 [01:52<00:11]       
 92%|==================  | 11194/12220 [01:53<00:10]       
 92%|==================  | 11286/12220 [01:54<00:09]       
 93%|=================== | 11383/12220 [01:55<00:08]       
 94%|=================== | 11480/12220 [01:56<00:07]       
 95%|=================== | 11575/12220 [01:57<00:06]       
 96%|=================== | 11671/12220 [01:58<00:05]       
 96%|=================== | 11768/12220 [01:59<00:04]       
 97%|=================== | 11867/12220 [02:00<00:03]       
 98%|===================| 11963/12220 [02:01<00:02]       
 99%|===================| 12059/12220 [02:02<00:01]       
 99%|===================| 12154/12220 [02:03<00:00]       
positions in block: {1.0: 1552, 2.0: 1544, 3.0: 1539, 4.0: 1530, 5.0: 1523, 6.0: 1517, 7.0: 1512, 8.0: 1503}
           mean         count     
context       0       1     0    1
rel                               
-4.0    -0.1407 -0.0330   764  759
-3.0    -0.1373 -0.0320   760  757
-2.0    -0.1220  0.0120   759  753
-1.0    -0.1672 -0.0006   757  746
 1.0     0.6061 -0.2094   775  777
 2.0     0.3357  0.0853   772  772
 3.0    -0.1009 -0.0749   771  768
 4.0    -0.1358 -0.0374   768  762
W- to W+: trial -1 (old block) -0.1672, trial 1 -0.2094, trial 2 +0.0853 -> sign change toward the new context False, trial 2 further True
W+ to W-: trial -1 (old block) -0.0006, trial 1 +0.6061, trial 2 +0.3357 -> sign change toward the new context False, trial 2 further True
base value 0.5329 | SHAP range of the feature -0.665 1.184
variant, context + whisker trial in block: {0: {-4.0: -1.341, -3.0: -1.331, -2.0: -1.331, -1.0: -1.384, 1.0: -0.201, 2.0: -0.695, 3.0: -1.251, 4.0: -1.309}, 1: {-4.0: 1.311, -3.0: 1.307, -2.0: 1.372, -1.0: 1.367, 1.0: 0.687, 2.0: 1.248, 3.0: 1.224, 4.0: 1.291}}
   W- to W+: trial -1 -1.384, trial 1 +0.687, trial 2 +1.248, trial 4 +1.291
   W+ to W-: trial -1 +1.367, trial 1 -0.201, trial 2 -0.695, trial 4 -1.309

Result: not reproduced as the criterion reads it. In both directions the SHAP value of whisker trial in block at trial 1 of the new block does not take the sign of the new context: it moves against it (negative after W- to W+, positive after W+ to W-), and trial 2 then moves toward the new context. The feature carries the one-trial lag of the behaviour, while context carries the switch (variant with both features summed, printed above).

fig3c-jaw-onset¶

Jaw opening, the first movement, begins 108 ± 24 ms after the sensory stimulus, so the first 120 ms after the stimulus largely precede movement.

jRGECO1a mice. As the Methods (Figures 3B and 3C): jaw opening filtered at 60% likelihood (points below it set missing, not dropped trials), and, "as in Figures 1I&J", the jaw dropped for a session when under 70% of its points pass (the variant without this rule is shown); each trial centred on its mean over the 250 ms before the stimulus; traces averaged within session, then over sessions per mouse. Methods' onset rule: per mouse, the d' (ddof 0) at each time between the trial values of jaw opening (missing points left out) and the trials' pre-stimulus mean (0 after centring); onset is the first time after the stimulus with d' >= 1. The d' over session means is a variant. Trial sets: (a) the Methods' correct whisker trials, W+ hits and W- misses pooled (Figure 3B: "correct trials (i.e. licks to whisker in W+ and no licks in W-)"), (b) W+ whisker hits, (c) the code's auditory and whisker hits, and the Figure 3C legend's groups (auditory hits in W+ and W-, whisker hits in W-). The code's rule (per trial, the first time |jaw| over its pre-stimulus SD exceeds 3, averaged per session, then mouse) is a variant.

In [40]:
sets = {'(a) correct whisker, W+ hits and W- misses': lambda tr: (tr.trial_type == 'whisker_trial') & (tr.lick_flag == tr.context),
        '(b) W+ whisker hits': lambda tr: (tr.trial_type == 'whisker_trial') & (tr.context == 1) & (tr.lick_flag == 1),
        '(c) auditory and whisker hits (code)': lambda tr: tr.trial_type.isin(['whisker_trial', 'auditory_trial']) & (tr.lick_flag == 1),
        'auditory hits W+': lambda tr: (tr.trial_type == 'auditory_trial') & (tr.context == 1) & (tr.lick_flag == 1),
        'auditory hits W-': lambda tr: (tr.trial_type == 'auditory_trial') & (tr.context == 0) & (tr.lick_flag == 1),
        'whisker hits W-': lambda tr: (tr.trial_type == 'whisker_trial') & (tr.context == 0) & (tr.lick_flag == 1)}
def first_d1(t, J):
    # J: values x time, centred on the pre-stimulus mean; d' of each time against the zero baseline means
    d = np.array([bech.dprime(J[np.isfinite(J[:, i]), i], np.zeros(np.isfinite(J[:, i]).sum())) if np.isfinite(J[:, i]).sum() > 2 else np.nan
                  for i in range(J.shape[1])])
    post = np.where((t > 0) & (d >= 1))[0]
    return t[post[0]] * 1000 if len(post) else np.nan
print('jaw points passing 60% likelihood per jRGECO1a session:', frac.reindex(JR).jaw.round(2).to_dict())
F3C = {}
for keep70 in (True, False):
    print('70% session rule (Methods, Figures 1I-J)' if keep70 else 'variant, without the 70% session rule')
    for name, sel in sets.items():
        rows = []
        for mouse in sorted({s.split('_')[0] for s in JR}):
            sids = [s for s in JR if s.startswith(mouse + '_') and s in ok and (not keep70 or frac.loc[s, 'jaw'] >= bech.KEEP_FRACTION)]
            Js, Ss, codes = [], [], []
            for sid in sids:
                tr = trial_table(sid); t = ok[sid]['jaw_t']
                J = ok[sid]['jaw_traces'][(sel(tr) & (tr.early_lick == 0)).values]
                b = (t < 0) & (t >= -0.25 - 1e-9)
                with np.errstate(all='ignore'):
                    bm = np.nanmean(J[:, b], 1); bs = np.nanstd(J[:, b], 1)
                    keep = np.isfinite(bm)
                    J, bs = J[keep] - bm[keep, None], bs[keep]
                    if len(J) == 0: continue
                    Js.append(J); Ss.append(np.nanmean(J, 0))
                    z = np.abs(J) / bs[:, None]
                    f1 = [t[np.where((t > 0) & (zz > 3))[0][0]] * 1000 for zz in z if ((t > 0) & (zz > 3)).any()]
                    codes.append(np.mean(f1) if f1 else np.nan)
            if not Js:
                rows.append((mouse, len(sids), 0, 0, np.nan, np.nan, np.nan, np.nan)); continue
            J = np.concatenate(Js); S_ = np.array(Ss)
            post_ = (t > 0) & (t <= 0.15)
            rows.append((mouse, len(Ss), len(J), round(float(np.isnan(J[:, post_]).mean()), 3), first_d1(t, J),
                         first_d1(t, S_) if len(S_) > 2 else np.nan, np.nanmean(codes), np.nan))
        R = pd.DataFrame(rows, columns=['mouse', 'sessions', 'trials', 'missing_0_150ms', 'onset_ms', 'onset_session_dprime', 'code_rule_ms', '_']).drop(columns='_').set_index('mouse')
        v = R.onset_ms
        F3C[(keep70, name)] = v.mean()
        print(f'  {name}: Methods onset {v.mean():.1f} ± SD {v.std():.1f} ms over {v.notna().sum()} mice (108 ± 24: {abs(v.mean() - 108) <= 24}); '
              f'd prime over session means {R.onset_session_dprime.mean():.1f} ({R.onset_session_dprime.notna().sum()} mice with 3 or more sessions); code rule {R.code_rule_ms.mean():.1f}')
        print('    per mouse:', R.round(1).to_dict('index'))
jaw points passing 60% likelihood per jRGECO1a session: {'PB177_20240525_124055': 0.4, 'PB177_20240527_135745': 0.28, 'PB177_20240528_093711': 0.37, 'PB177_20240529_121819': 0.25, 'PB177_20240530_113408': 0.55, 'PB177_20240531_104515': 0.51, 'PB177_20240606_104234': 0.68, 'PB177_20240607_161204': 0.69, 'PB178_20240529_101445': 0.74, 'PB178_20240607_115237': 0.65, 'PB178_20240608_132641': 0.66, 'PB185_20240823_102701': 0.97, 'PB185_20240830_105945': 0.96, 'PB185_20240831_123411': 0.96, 'PB187_20240806_132010': 0.96, 'PB187_20240807_091702': 0.94, 'PB187_20240808_105328': 0.83, 'PB187_20240809_111335': 0.75, 'PB188_20240821_170100': 0.8, 'PB188_20240822_153551': 0.83, 'PB188_20240823_113645': 0.78, 'PB188_20240824_130819': 0.8, 'PB189_20240820_155808': 0.68, 'PB189_20240821_142007': 0.57, 'PB189_20240822_172840': 0.72}
70% session rule (Methods, Figures 1I-J)
  (a) correct whisker, W+ hits and W- misses: Methods onset 90.0 ± SD 12.2 ms over 5 mice (108 ± 24: True); d prime over session means 25.0 (3 mice with 3 or more sessions); code rule 68.8
    per mouse: {'PB177': {'sessions': 0, 'trials': 0, 'missing_0_150ms': 0.0, 'onset_ms': nan, 'onset_session_dprime': nan, 'code_rule_ms': nan}, 'PB178': {'sessions': 1, 'trials': 62, 'missing_0_150ms': 0.3, 'onset_ms': 95.0, 'onset_session_dprime': nan, 'code_rule_ms': 62.0}, 'PB185': {'sessions': 3, 'trials': 440, 'missing_0_150ms': 0.0, 'onset_ms': 95.0, 'onset_session_dprime': 55.0, 'code_rule_ms': 62.4}, 'PB187': {'sessions': 4, 'trials': 710, 'missing_0_150ms': 0.1, 'onset_ms': 105.0, 'onset_session_dprime': 15.0, 'code_rule_ms': 79.2}, 'PB188': {'sessions': 4, 'trials': 658, 'missing_0_150ms': 0.2, 'onset_ms': 80.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 66.3}, 'PB189': {'sessions': 1, 'trials': 139, 'missing_0_150ms': 0.2, 'onset_ms': 75.0, 'onset_session_dprime': nan, 'code_rule_ms': 73.9}}
  (b) W+ whisker hits: Methods onset 76.0 ± SD 6.5 ms over 5 mice (108 ± 24: False); d prime over session means 23.3 (3 mice with 3 or more sessions); code rule 65.0
    per mouse: {'PB177': {'sessions': 0, 'trials': 0, 'missing_0_150ms': 0.0, 'onset_ms': nan, 'onset_session_dprime': nan, 'code_rule_ms': nan}, 'PB178': {'sessions': 1, 'trials': 29, 'missing_0_150ms': 0.2, 'onset_ms': 75.0, 'onset_session_dprime': nan, 'code_rule_ms': 54.1}, 'PB185': {'sessions': 3, 'trials': 253, 'missing_0_150ms': 0.0, 'onset_ms': 80.0, 'onset_session_dprime': 55.0, 'code_rule_ms': 61.1}, 'PB187': {'sessions': 4, 'trials': 387, 'missing_0_150ms': 0.1, 'onset_ms': 85.0, 'onset_session_dprime': 10.0, 'code_rule_ms': 73.5}, 'PB188': {'sessions': 4, 'trials': 352, 'missing_0_150ms': 0.2, 'onset_ms': 70.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 68.1}, 'PB189': {'sessions': 1, 'trials': 90, 'missing_0_150ms': 0.2, 'onset_ms': 70.0, 'onset_session_dprime': nan, 'code_rule_ms': 68.4}}
  (c) auditory and whisker hits (code): Methods onset 77.0 ± SD 5.7 ms over 5 mice (108 ± 24: False); d prime over session means 20.0 (3 mice with 3 or more sessions); code rule 66.1
    per mouse: {'PB177': {'sessions': 0, 'trials': 0, 'missing_0_150ms': 0.0, 'onset_ms': nan, 'onset_session_dprime': nan, 'code_rule_ms': nan}, 'PB178': {'sessions': 1, 'trials': 70, 'missing_0_150ms': 0.3, 'onset_ms': 80.0, 'onset_session_dprime': nan, 'code_rule_ms': 56.9}, 'PB185': {'sessions': 3, 'trials': 626, 'missing_0_150ms': 0.0, 'onset_ms': 85.0, 'onset_session_dprime': 50.0, 'code_rule_ms': 68.0}, 'PB187': {'sessions': 4, 'trials': 951, 'missing_0_150ms': 0.1, 'onset_ms': 75.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 64.3}, 'PB188': {'sessions': 4, 'trials': 881, 'missing_0_150ms': 0.2, 'onset_ms': 70.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 63.9}, 'PB189': {'sessions': 1, 'trials': 207, 'missing_0_150ms': 0.2, 'onset_ms': 75.0, 'onset_session_dprime': nan, 'code_rule_ms': 77.7}}
  auditory hits W+: Methods onset 65.0 ± SD 12.2 ms over 5 mice (108 ± 24: False); d prime over session means 20.0 (3 mice with 3 or more sessions); code rule 64.4
    per mouse: {'PB177': {'sessions': 0, 'trials': 0, 'missing_0_150ms': 0.0, 'onset_ms': nan, 'onset_session_dprime': nan, 'code_rule_ms': nan}, 'PB178': {'sessions': 1, 'trials': 16, 'missing_0_150ms': 0.3, 'onset_ms': 50.0, 'onset_session_dprime': nan, 'code_rule_ms': 56.6}, 'PB185': {'sessions': 3, 'trials': 132, 'missing_0_150ms': 0.0, 'onset_ms': 80.0, 'onset_session_dprime': 40.0, 'code_rule_ms': 71.1}, 'PB187': {'sessions': 4, 'trials': 212, 'missing_0_150ms': 0.1, 'onset_ms': 55.0, 'onset_session_dprime': 15.0, 'code_rule_ms': 49.8}, 'PB188': {'sessions': 4, 'trials': 204, 'missing_0_150ms': 0.2, 'onset_ms': 70.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 62.0}, 'PB189': {'sessions': 1, 'trials': 42, 'missing_0_150ms': 0.2, 'onset_ms': 70.0, 'onset_session_dprime': nan, 'code_rule_ms': 82.4}}
  auditory hits W-: Methods onset 76.0 ± SD 15.6 ms over 5 mice (108 ± 24: False); d prime over session means 10.0 (3 mice with 3 or more sessions); code rule 69.5
    per mouse: {'PB177': {'sessions': 0, 'trials': 0, 'missing_0_150ms': 0.0, 'onset_ms': nan, 'onset_session_dprime': nan, 'code_rule_ms': nan}, 'PB178': {'sessions': 1, 'trials': 18, 'missing_0_150ms': 0.3, 'onset_ms': 65.0, 'onset_session_dprime': nan, 'code_rule_ms': 62.8}, 'PB185': {'sessions': 3, 'trials': 128, 'missing_0_150ms': 0.0, 'onset_ms': 80.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 78.1}, 'PB187': {'sessions': 4, 'trials': 223, 'missing_0_150ms': 0.1, 'onset_ms': 60.0, 'onset_session_dprime': 20.0, 'code_rule_ms': 55.1}, 'PB188': {'sessions': 4, 'trials': 201, 'missing_0_150ms': 0.2, 'onset_ms': 75.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 63.6}, 'PB189': {'sessions': 1, 'trials': 43, 'missing_0_150ms': 0.2, 'onset_ms': 100.0, 'onset_session_dprime': nan, 'code_rule_ms': 88.0}}
  whisker hits W-: Methods onset 106.0 ± SD 56.4 ms over 5 mice (108 ± 24: True); d prime over session means 41.7 (3 mice with 3 or more sessions); code rule 67.1
    per mouse: {'PB177': {'sessions': 0, 'trials': 0, 'missing_0_150ms': 0.0, 'onset_ms': nan, 'onset_session_dprime': nan, 'code_rule_ms': nan}, 'PB178': {'sessions': 1, 'trials': 7, 'missing_0_150ms': 0.1, 'onset_ms': 205.0, 'onset_session_dprime': nan, 'code_rule_ms': 52.0}, 'PB185': {'sessions': 3, 'trials': 113, 'missing_0_150ms': 0.0, 'onset_ms': 80.0, 'onset_session_dprime': 15.0, 'code_rule_ms': 68.1}, 'PB187': {'sessions': 4, 'trials': 129, 'missing_0_150ms': 0.1, 'onset_ms': 95.0, 'onset_session_dprime': 65.0, 'code_rule_ms': 75.6}, 'PB188': {'sessions': 4, 'trials': 124, 'missing_0_150ms': 0.2, 'onset_ms': 65.0, 'onset_session_dprime': 45.0, 'code_rule_ms': 56.3}, 'PB189': {'sessions': 1, 'trials': 32, 'missing_0_150ms': 0.2, 'onset_ms': 85.0, 'onset_session_dprime': nan, 'code_rule_ms': 83.4}}
variant, without the 70% session rule
  (a) correct whisker, W+ hits and W- misses: Methods onset 85.8 ± SD 13.9 ms over 6 mice (108 ± 24: True); d prime over session means 25.0 (6 mice with 3 or more sessions); code rule 69.3
    per mouse: {'PB177': {'sessions': 8, 'trials': 916, 'missing_0_150ms': 0.4, 'onset_ms': 65.0, 'onset_session_dprime': 40.0, 'code_rule_ms': 63.6}, 'PB178': {'sessions': 3, 'trials': 239, 'missing_0_150ms': 0.3, 'onset_ms': 80.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 63.4}, 'PB185': {'sessions': 3, 'trials': 440, 'missing_0_150ms': 0.0, 'onset_ms': 95.0, 'onset_session_dprime': 55.0, 'code_rule_ms': 62.4}, 'PB187': {'sessions': 4, 'trials': 710, 'missing_0_150ms': 0.1, 'onset_ms': 105.0, 'onset_session_dprime': 15.0, 'code_rule_ms': 79.2}, 'PB188': {'sessions': 4, 'trials': 658, 'missing_0_150ms': 0.2, 'onset_ms': 80.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 66.3}, 'PB189': {'sessions': 3, 'trials': 396, 'missing_0_150ms': 0.3, 'onset_ms': 90.0, 'onset_session_dprime': 30.0, 'code_rule_ms': 80.6}}
  (b) W+ whisker hits: Methods onset 73.3 ± SD 8.8 ms over 6 mice (108 ± 24: False); d prime over session means 21.7 (6 mice with 3 or more sessions); code rule 66.2
    per mouse: {'PB177': {'sessions': 8, 'trials': 500, 'missing_0_150ms': 0.4, 'onset_ms': 60.0, 'onset_session_dprime': 50.0, 'code_rule_ms': 62.0}, 'PB178': {'sessions': 3, 'trials': 138, 'missing_0_150ms': 0.3, 'onset_ms': 70.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 59.3}, 'PB185': {'sessions': 3, 'trials': 253, 'missing_0_150ms': 0.0, 'onset_ms': 80.0, 'onset_session_dprime': 55.0, 'code_rule_ms': 61.1}, 'PB187': {'sessions': 4, 'trials': 387, 'missing_0_150ms': 0.1, 'onset_ms': 85.0, 'onset_session_dprime': 10.0, 'code_rule_ms': 73.5}, 'PB188': {'sessions': 4, 'trials': 352, 'missing_0_150ms': 0.2, 'onset_ms': 70.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 68.1}, 'PB189': {'sessions': 3, 'trials': 234, 'missing_0_150ms': 0.3, 'onset_ms': 75.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 73.5}}
  (c) auditory and whisker hits (code): Methods onset 73.3 ± SD 10.3 ms over 6 mice (108 ± 24: False); d prime over session means 19.2 (6 mice with 3 or more sessions); code rule 66.3
    per mouse: {'PB177': {'sessions': 8, 'trials': 1083, 'missing_0_150ms': 0.4, 'onset_ms': 60.0, 'onset_session_dprime': 45.0, 'code_rule_ms': 62.9}, 'PB178': {'sessions': 3, 'trials': 336, 'missing_0_150ms': 0.3, 'onset_ms': 65.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 59.5}, 'PB185': {'sessions': 3, 'trials': 626, 'missing_0_150ms': 0.0, 'onset_ms': 85.0, 'onset_session_dprime': 50.0, 'code_rule_ms': 68.0}, 'PB187': {'sessions': 4, 'trials': 951, 'missing_0_150ms': 0.1, 'onset_ms': 75.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 64.3}, 'PB188': {'sessions': 4, 'trials': 881, 'missing_0_150ms': 0.2, 'onset_ms': 70.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 63.9}, 'PB189': {'sessions': 3, 'trials': 546, 'missing_0_150ms': 0.3, 'onset_ms': 85.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 79.2}}
  auditory hits W+: Methods onset 65.0 ± SD 11.8 ms over 6 mice (108 ± 24: False); d prime over session means 18.3 (6 mice with 3 or more sessions); code rule 62.8
    per mouse: {'PB177': {'sessions': 8, 'trials': 270, 'missing_0_150ms': 0.4, 'onset_ms': 60.0, 'onset_session_dprime': 40.0, 'code_rule_ms': 62.8}, 'PB178': {'sessions': 3, 'trials': 78, 'missing_0_150ms': 0.3, 'onset_ms': 50.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 51.5}, 'PB185': {'sessions': 3, 'trials': 132, 'missing_0_150ms': 0.0, 'onset_ms': 80.0, 'onset_session_dprime': 40.0, 'code_rule_ms': 71.1}, 'PB187': {'sessions': 4, 'trials': 212, 'missing_0_150ms': 0.1, 'onset_ms': 55.0, 'onset_session_dprime': 15.0, 'code_rule_ms': 49.8}, 'PB188': {'sessions': 4, 'trials': 204, 'missing_0_150ms': 0.2, 'onset_ms': 70.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 62.0}, 'PB189': {'sessions': 3, 'trials': 122, 'missing_0_150ms': 0.3, 'onset_ms': 75.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 79.5}}
  auditory hits W-: Methods onset 73.3 ± SD 15.4 ms over 6 mice (108 ± 24: False); d prime over session means 22.5 (6 mice with 3 or more sessions); code rule 68.8
    per mouse: {'PB177': {'sessions': 8, 'trials': 216, 'missing_0_150ms': 0.5, 'onset_ms': 65.0, 'onset_session_dprime': 55.0, 'code_rule_ms': 67.7}, 'PB178': {'sessions': 3, 'trials': 67, 'missing_0_150ms': 0.3, 'onset_ms': 60.0, 'onset_session_dprime': 15.0, 'code_rule_ms': 56.3}, 'PB185': {'sessions': 3, 'trials': 128, 'missing_0_150ms': 0.0, 'onset_ms': 80.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 78.1}, 'PB187': {'sessions': 4, 'trials': 223, 'missing_0_150ms': 0.1, 'onset_ms': 60.0, 'onset_session_dprime': 20.0, 'code_rule_ms': 55.1}, 'PB188': {'sessions': 4, 'trials': 201, 'missing_0_150ms': 0.2, 'onset_ms': 75.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 63.6}, 'PB189': {'sessions': 3, 'trials': 117, 'missing_0_150ms': 0.3, 'onset_ms': 100.0, 'onset_session_dprime': 35.0, 'code_rule_ms': 91.9}}
  whisker hits W-: Methods onset 85.0 ± SD 18.2 ms over 6 mice (108 ± 24: True); d prime over session means 36.7 (6 mice with 3 or more sessions); code rule 68.1
    per mouse: {'PB177': {'sessions': 8, 'trials': 97, 'missing_0_150ms': 0.5, 'onset_ms': 65.0, 'onset_session_dprime': 25.0, 'code_rule_ms': 58.9}, 'PB178': {'sessions': 3, 'trials': 53, 'missing_0_150ms': 0.3, 'onset_ms': 110.0, 'onset_session_dprime': 65.0, 'code_rule_ms': 73.7}, 'PB185': {'sessions': 3, 'trials': 113, 'missing_0_150ms': 0.0, 'onset_ms': 80.0, 'onset_session_dprime': 15.0, 'code_rule_ms': 68.1}, 'PB187': {'sessions': 4, 'trials': 129, 'missing_0_150ms': 0.1, 'onset_ms': 95.0, 'onset_session_dprime': 65.0, 'code_rule_ms': 75.6}, 'PB188': {'sessions': 4, 'trials': 124, 'missing_0_150ms': 0.2, 'onset_ms': 65.0, 'onset_session_dprime': 45.0, 'code_rule_ms': 56.3}, 'PB189': {'sessions': 3, 'trials': 73, 'missing_0_150ms': 0.3, 'onset_ms': 95.0, 'onset_session_dprime': 5.0, 'code_rule_ms': 76.0}}

Result: reproduced, resting on an assumption. With the Methods' correct whisker trials (a) and the 70% session rule the mean onset is within 108 ± 24 ms, and so it is without the rule. With W+ whisker hits only (b), with the code's auditory and whisker hits (c), and for auditory hits it is below the tolerance. The assumption is the Methods' trial set (a).

Low-dimensional trajectories under inhibition (Figure 4D-G)¶

As the Methods (Principal component analysis; Figure 4D; Figures 4E-G) and plot utils/figure4C_G.py:434-535: the 4 widefield-with-optogenetics mice; grid ROI ΔF/F0 without baseline subtraction, from -150 to 150 ms around trial onset (the whisker or catch stimulus); the 39 grid sites the code keeps (AP 3.5 and (1.5, 5.5), (2.5, 4.5), (2.5, 5.5) left out). Control trials (laser off the brain), whisker and catch, averaged per mouse over all its trials (the pseudosession), then over mice by context, trial type, lick and time; StandardScaler and PCA with 15 components fitted on that matrix; each component's sign set so that its wS1 loading is positive (the code's enforce_sign_consistency on the wS1 column). Trials at each stimulated site, all trials pooled, are projected per mouse.

In [41]:
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
KEEP = sorted([s for s in SIDX if s[0] != 3.5 and s not in [(1.5, 5.5), (2.5, 4.5), (2.5, 5.5)]], key=lambda s: str(s))
KC = [SIDX[s] for s in KEEP]
print('sites used', len(KEEP))
def pseudo(sids, select):
    # per mouse mean over all selected trials pooled across sessions: dict mouse -> (t, time x site)
    acc = {}
    for sid in sids:
        names, t, W, lag = G[sid]; tr = trial_table(sid); m = select(tr).values
        if m.sum() == 0: continue
        acc.setdefault(sid.split('_')[0], []).append(W[m][:, :, KC])
    out = {}
    for mouse, lst in acc.items():
        X = np.concatenate(lst); out[mouse] = (t, np.nanmean(X, 0), len(X))
    return out
def sel(tt, ctx, lick=None, site='control'):
    def f(tr):
        m = (tr.trial_type == tt) & (tr.context == ctx)
        if lick is not None: m &= tr.lick_flag == lick
        if site == 'control': return m & (tr.opto_stim == 0)
        return m & (tr.opto_stim == 1) & np.isclose(tr.opto_grid_ap, site[0]) & np.isclose(tr.opto_grid_ml, site[1])
    return f
rows, ctrl_mouse = [], {}
for ctx in (0, 1):
    for tt in ['whisker_trial', 'no_stim_trial']:
        for lick in (0, 1):
            pm = pseudo(WO, sel(tt, ctx, lick))
            t = next(iter(pm.values()))[0]; w = (t >= -0.15 - 1e-9) & (t <= 0.15 + 1e-9)
            X = np.stack([v[1][w] for v in pm.values()])
            ctrl_mouse[(ctx, tt, lick)] = {m: v[1][w] for m, v in pm.items()}
            rows.append(((ctx, tt, lick), np.nanmean(X, 0)))
tw = t[w]
Mtx = np.concatenate([r[1] for r in rows])
scaler = StandardScaler().fit(Mtx)
pca = PCA(n_components=15).fit(np.nan_to_num(scaler.transform(Mtx)))
wS1col = KEEP.index(bech.SITES['wS1'])
sgn = np.sign(pca.components_[:, wS1col]); sgn[sgn == 0] = 1
proj = lambda X: (pca.transform(np.nan_to_num(scaler.transform(X))) * sgn)
print('time samples', len(tw), tw.round(2), '| variance explained by PC1-5', pca.explained_variance_ratio_[:5].round(3), 'cumulative 15', pca.explained_variance_ratio_.sum().round(3))
print('sign flips applied (wS1 loading made positive), PC1-3:', sgn[:3])
print('loadings after the sign convention, PC1-3, named sites:')
print(pd.DataFrame((pca.components_[:3] * sgn[:3, None]).T, index=[str(s) for s in KEEP], columns=['PC1', 'PC2', 'PC3'])
      .loc[[str(bech.SITES[n]) for n in ['wS1', 'wS2', 'wM1', 'wM2', 'ALM', 'tjS1', 'tjM1', 'A1', 'RSC', 'RSC_2']]]
      .set_axis(['wS1', 'wS2', 'wM1', 'wM2', 'ALM', 'tjS1', 'tjM1', 'A1', 'RSC', 'RSC_2']).round(3).T.to_string())
ctrl_pc3 = {k: proj(v)[:, 2] for k, v in rows}
STIM = {}
for site_name in ['wS1', 'wS2', 'wM1', 'wM2', 'ALM', 'RSC', 'RSC_2', 'tjS1', 'tjM1', 'A1']:
    for ctx in (0, 1):
        pm = pseudo(WO, sel('whisker_trial', ctx, None, bech.SITES[site_name]))
        STIM[(site_name, ctx)] = {m: proj(v[1][w])[:, 2] for m, v in pm.items()}
ALLSITE = {}
for s in KEEP:
    for ctx in (0, 1):
        pm = pseudo(WO, sel('whisker_trial', ctx, None, s))
        ALLSITE[(s, ctx)] = {m: proj(v[1][w])[:, 2] for m, v in pm.items()}
post = tw >= -1e-9
sites used 39
time samples 15 [-0.14 -0.12 -0.1  -0.08 -0.06 -0.04 -0.02  0.    0.02  0.04  0.06  0.08
  0.1   0.12  0.14] | variance explained by PC1-5 [0.748 0.154 0.044 0.033 0.015] cumulative 15 1.0
sign flips applied (wS1 loading made positive), PC1-3: [ 1. -1.  1.]
loadings after the sign convention, PC1-3, named sites:
       wS1    wS2    wM1    wM2    ALM   tjS1   tjM1     A1    RSC  RSC_2
PC1  0.143  0.155  0.166  0.166  0.173  0.163  0.171  0.132  0.170  0.164
PC2  0.049 -0.007  0.171  0.171  0.121 -0.056  0.028 -0.270  0.121  0.150
PC3  0.410  0.372  0.098  0.027 -0.126 -0.296 -0.265  0.125  0.093  0.031

fig4d-trajectories-follow-lick¶

Projected onto PC3, inactivation of wS1, wS2, wM1/2 and ALM drives the trajectory away from the control-lick trajectory toward no-lick, while inhibition of RSC and tjS1 gives trajectories that follow the control-lick trajectory in both contexts.

In [42]:
close = {}
for ctx in (0, 1):
    L1, L0 = ctrl_pc3[(ctx, 'whisker_trial', 1)][post], ctrl_pc3[(ctx, 'whisker_trial', 0)][post]
    print(f'{"W+" if ctx else "W-"}: control lick PC3 {L1.round(2)}; no lick {L0.round(2)}')
    for s in ['wS1', 'wS2', 'wM1', 'wM2', 'ALM', 'RSC', 'RSC_2', 'tjS1']:
        tr_ = np.mean(list(STIM[(s, ctx)].values()), 0)[post]
        dl, dn = np.mean((tr_ - L1) ** 2), np.mean((tr_ - L0) ** 2)
        close[(s, ctx)] = 'lick' if dl < dn else 'no lick'
        print(f'   {s}: MSD to lick {dl:.3f}, to no lick {dn:.3f} -> closer to {close[(s, ctx)]} (mice {len(STIM[(s, ctx)])})')
for rsc in ['RSC', 'RSC_2']:
    rt = all(close[(s, c)] == 'lick' for s in [rsc, 'tjS1'] for c in (0, 1))
    others = {c: [close[(s, c)] == 'no lick' for s in ['wS1', 'wS2', 'ALM']] + [close[('wM1', c)] == 'no lick' or close[('wM2', c)] == 'no lick'] for c in (0, 1)}
    full = rt and all(all(v) for v in others.values())
    part = rt and all(sum(v) >= 2 for v in others.values())
    print(rsc, '-> reproduced' if full else ('-> partially' if part else '-> not'), '| RSC and tjS1 closer to lick in both:', rt, '| others closer to no lick:', others)
# variant, not deciding (asked of a reader): where each trajectory lies along the control lick to no-lick
# direction, the least-squares coefficient of (site - lick) on (no lick - lick) over 0 to 140 ms (0 at the
# lick trajectory, 1 at no-lick), and its distance from the lick trajectory as a multiple of the control
# lick to no-lick distance (root mean square)
for ctx in (0, 1):
    L1, L0 = ctrl_pc3[(ctx, 'whisker_trial', 1)][post], ctrl_pc3[(ctx, 'whisker_trial', 0)][post]
    ax = L0 - L1; sep = np.sqrt(np.mean(ax ** 2))
    out = {}
    for s in ['wS1', 'wS2', 'wM1', 'wM2', 'ALM', 'RSC', 'RSC_2', 'tjS1']:
        tr_ = np.mean(list(STIM[(s, ctx)].values()), 0)[post]
        out[s] = (round(float(np.sum((tr_ - L1) * ax) / np.sum(ax ** 2)), 2), round(float(np.sqrt(np.mean((tr_ - L1) ** 2)) / sep), 1))
    print(f'variant, {"W+" if ctx else "W-"}: control lick to no-lick RMS distance {sep:.2f}; per site (coefficient toward no-lick, distance from lick in units of it):', out)
W-: control lick PC3 [0.39 1.39 2.66 3.42 3.43 2.5  1.3  0.19]; no lick [-0.64  0.16  1.19  1.92  2.19  1.86  1.25  0.66]
   wS1: MSD to lick 30.340, to no lick 33.438 -> closer to lick (mice 4)
   wS2: MSD to lick 16.622, to no lick 18.659 -> closer to lick (mice 4)
   wM1: MSD to lick 25.191, to no lick 29.545 -> closer to lick (mice 4)
   wM2: MSD to lick 46.045, to no lick 54.270 -> closer to lick (mice 4)
   ALM: MSD to lick 30.827, to no lick 37.481 -> closer to lick (mice 4)
   RSC: MSD to lick 1.405, to no lick 0.858 -> closer to no lick (mice 4)
   RSC_2: MSD to lick 1.522, to no lick 3.573 -> closer to lick (mice 4)
   tjS1: MSD to lick 7.557, to no lick 12.106 -> closer to lick (mice 4)
W+: control lick PC3 [ 0.64  1.44  2.54  3.18  2.75  1.58  0.28 -0.95]; no lick [-0.4   0.25  1.11  1.72  1.97  1.7   1.03  0.41]
   wS1: MSD to lick 37.628, to no lick 36.005 -> closer to no lick (mice 4)
   wS2: MSD to lick 18.763, to no lick 18.540 -> closer to no lick (mice 4)
   wM1: MSD to lick 57.937, to no lick 61.380 -> closer to lick (mice 4)
   wM2: MSD to lick 50.330, to no lick 52.662 -> closer to lick (mice 4)
   ALM: MSD to lick 29.607, to no lick 31.056 -> closer to lick (mice 4)
   RSC: MSD to lick 0.165, to no lick 0.967 -> closer to lick (mice 4)
   RSC_2: MSD to lick 0.759, to no lick 1.762 -> closer to lick (mice 4)
   tjS1: MSD to lick 10.415, to no lick 13.036 -> closer to lick (mice 4)
RSC -> not | RSC and tjS1 closer to lick in both: False | others closer to no lick: {0: [False, False, False, False], 1: [True, True, False, False]}
RSC_2 -> not | RSC and tjS1 closer to lick in both: True | others closer to no lick: {0: [False, False, False, False], 1: [True, True, False, False]}
variant, W-: control lick to no-lick RMS distance 1.07; per site (coefficient toward no-lick, distance from lick in units of it): {'wS1': (-0.85, 5.1), 'wS2': (-0.39, 3.8), 'wM1': (-1.4, 4.7), 'wM2': (-3.09, 6.3), 'ALM': (-2.4, 5.2), 'RSC': (0.74, 1.1), 'RSC_2': (-0.39, 1.2), 'tjS1': (-1.48, 2.6)}
variant, W+: control lick to no-lick RMS distance 1.10; per site (coefficient toward no-lick, distance from lick in units of it): {'wS1': (1.17, 5.6), 'wS2': (0.59, 3.9), 'wM1': (-0.93, 6.9), 'wM2': (-0.47, 6.5), 'ALM': (-0.1, 5.0), 'RSC': (0.17, 0.4), 'RSC_2': (0.08, 0.8), 'tjS1': (-0.58, 2.9)}

Result: not reproduced. RSC (-1.5, 0.5) is closer to no-lick in W-, and wS1, wS2, wM1/2 and ALM are not closer to no-lick in W-. In the variant along the lick to no-lick direction (not deciding), the trajectories of wS1, wS2, wM1, wM2 and ALM lie 3.8 to 6.9 times the control lick to no-lick distance from the lick trajectory, against 0.4 and 1.1 for RSC, but on the side away from no-lick in W- (coefficients -3.09 to -0.39) and for wM1, wM2 and ALM in W+; only wS1 and wS2 in W+ lie toward no-lick (1.17 and 0.59). So they move away from control-lick, but not toward no-lick, by either measure.

fig4e-rsc-tjs1-smaller-angle¶

The PC3 trajectories under RSC and tjS1 inhibition make smaller angles with the control-lick trajectory than those under inhibition of the other regions, which decreased lick probability.

In [43]:
def angle(v1, v2):
    return np.degrees(np.arccos(np.clip(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)), -1, 1)))
def site_angles(store, ctx, code_variant=False):
    L1 = np.mean([v for v in ctrl_mouse_pc3(ctx).values()], 0)
    out = {}
    for key, per in store.items():
        if key[1] != ctx: continue
        vals = []
        for m, tr_ in per.items():
            a, b = tr_[post], L1[post]
            if code_variant:
                mn = min(tr_[post].min(), 0) if False else tr_[post].min()
                a, b = a + mn, b + mn
            vals.append(angle(a, b))
        out[key[0]] = np.mean(vals)
    return out
def ctrl_mouse_pc3(ctx):
    return {m: proj(x)[:, 2] for m, x in ctrl_mouse[(ctx, 'whisker_trial', 1)].items()}
for variant in [False, True]:
    print('code variant (minimum added)' if variant else 'Methods angle')
    res = {}
    for ctx in (0, 1):
        ang = site_angles(STIM, ctx, variant)
        print(f'   {"W+" if ctx else "W-"}:', {k: round(v, 1) for k, v in ang.items()})
        for rsc in ['RSC', 'RSC_2']:
            small = max(ang[rsc], ang['tjS1']) < min(ang['wS1'], ang['wS2'], ang['ALM']) and max(ang[rsc], ang['tjS1']) < max(ang['wM1'], ang['wM2'])
            res[(rsc, ctx)] = small
    for rsc in ['RSC', 'RSC_2']:
        n = int(bool(res[(rsc, 0)])) + int(bool(res[(rsc, 1)]))
        print('  ', rsc, {('W+' if c else 'W-'): res[(rsc, c)] for c in (0, 1)}, '->', 'reproduced' if n == 2 else ('partially' if n == 1 else 'not'))
Methods angle
   W-: {'wS1': np.float32(42.7), 'wS2': np.float32(41.0), 'wM1': np.float32(34.3), 'wM2': np.float32(30.4), 'ALM': np.float32(30.3), 'RSC': np.float32(37.5), 'RSC_2': np.float32(21.2), 'tjS1': np.float32(23.9), 'tjM1': np.float32(19.5), 'A1': np.float32(46.5)}
   W+: {'wS1': np.float32(54.0), 'wS2': np.float32(46.3), 'wM1': np.float32(41.2), 'wM2': np.float32(43.5), 'ALM': np.float32(43.7), 'RSC': np.float32(33.1), 'RSC_2': np.float32(23.7), 'tjS1': np.float32(26.9), 'tjM1': np.float32(34.9), 'A1': np.float32(22.3)}
   RSC {'W-': np.False_, 'W+': np.True_} -> partially
   RSC_2 {'W-': np.True_, 'W+': np.True_} -> reproduced
code variant (minimum added)
   W-: {'wS1': np.float32(56.9), 'wS2': np.float32(46.7), 'wM1': np.float32(47.7), 'wM2': np.float32(30.7), 'ALM': np.float32(28.9), 'RSC': np.float32(30.4), 'RSC_2': np.float32(23.2), 'tjS1': np.float32(21.6), 'tjM1': np.float32(9.8), 'A1': np.float32(15.0)}
   W+: {'wS1': np.float32(68.2), 'wS2': np.float32(37.8), 'wM1': np.float32(20.9), 'wM2': np.float32(37.3), 'ALM': np.float32(42.2), 'RSC': np.float32(14.2), 'RSC_2': np.float32(21.2), 'tjS1': np.float32(31.2), 'tjM1': np.float32(45.2), 'A1': np.float32(21.8)}
   RSC {'W-': np.False_, 'W+': np.True_} -> partially
   RSC_2 {'W-': np.True_, 'W+': np.True_} -> reproduced

Result: partially reproduced. In W+ the angles of RSC and tjS1 are below those of wS1, wS2, wM1, wM2 and ALM, the sites the criterion compares them with (A1 and RSC (-0.5, 0.5), which it does not compare, are lower still); in W- the RSC (-1.5, 0.5) angle is above those of wM1, wM2 and ALM.

fig4fg-angle-predicts-lick-change¶

Across all inactivated sites, in W+ and in W-, the angle between the inhibition and control-lick trajectories relates to the change in lick probability the inhibition evokes.

In [44]:
WO_MICE = sorted({s.split('_')[0] for s in WO})
obs_wo, _ = bech.opto_map(T[T.session_id.isin(WO)], WO_MICE, null='trials', n_shuffle=10, seed=21)
dpw = obs_wo[obs_wo.trial_type == 'whisker_trial'].groupby(['context', 'site']).dP.mean()
for variant in [False, True]:
    for ctx in (0, 1):
        ang = site_angles(ALLSITE, ctx, variant)
        sites = [s for s in ang if (ctx, s) in dpw.index]
        x = np.array([ang[s] for s in sites]); y = np.array([dpw[(ctx, s)] for s in sites])
        r = stats.linregress(x, y)
        print(f'{"code angle" if variant else "Methods angle"}, {"W+" if ctx else "W-"}: {len(sites)} sites, r {r.rvalue:.2f}, p {r.pvalue:.2g}, slope {r.slope:.4f} dP per degree; angle range {x.min():.1f} to {x.max():.1f}, dP range {y.min():.2f} to {y.max():.2f}')
Methods angle, W-: 39 sites, r -0.41, p 0.0088, slope -0.0022 dP per degree; angle range 11.1 to 133.2, dP range -0.34 to 0.22
Methods angle, W+: 39 sites, r -0.33, p 0.043, slope -0.0020 dP per degree; angle range 11.0 to 100.1, dP range -0.33 to 0.07
code angle, W-: 39 sites, r -0.51, p 0.00089, slope -0.0046 dP per degree; angle range 9.3 to 71.7, dP range -0.34 to 0.22
code angle, W+: 39 sites, r -0.46, p 0.0036, slope -0.0047 dP per degree; angle range 13.3 to 68.2, dP range -0.33 to 0.07

Result: reproduced. The correlation of angle with dP over 39 sites is negative with p below 0.05 in both contexts, for both angle definitions.

Pre-stimulus correlations (Figure 4A-B), a variant on the grid ROI traces¶

The three fig4b claims are blocked: the criterion uses seed-to-pixel correlation maps of the ΔF/F0 stack in the 2 s before every trial, masked by a block-shuffle null. That analysis was not run in this attempt. The reads alone are estimated below from the rate measured for the pixel part of fig3h, with the time this notebook has taken up to that cell; together they do not fit the notebook limit of 60 minutes. In a separate notebook the reads alone would fit within that limit (the share is printed below; the read rate varies between runs), before the block shuffles; such a notebook was not built in this attempt. As a variant that does not decide the outcome, the zero-lag Pearson correlations between the grid ROI traces of the seven seeds (1 mm circles at the seed sites) in the 2 s before each trial start are computed, whisker trials, correct (W+ hits, W- misses) and incorrect (W+ misses, W- hits), averaged per session, then per mouse; the paired d' (mean of the W- minus W+ differences over their SD, ddof 1) and the related t-test with Bonferroni x7 are given for the code's seven pairs. No null, so the connectivity claim is not addressed.

In [45]:
SEEDS = ['wS1', 'wS2', 'wM1', 'RSC', 'ALM', 'tjM1', 'tjS1']
PAIRS = [('ALM', 'tjM1'), ('ALM', 'tjS1'), ('tjM1', 'tjS1'), ('wM1', 'ALM'), ('wM1', 'tjM1'), ('wS1', 'wS2'), ('wS2', 'wM1')]
PC = bech.load_precorr(A[A.session_id.isin(JR)], [bech.SITES[s] for s in SEEDS], n=8)
n_all = int(T[T.session_id.isin(JR)].shape[0]); gb = n_all * 200 * 125 * 160 * 8 / 1e9
t_read = gb / (GB_PIX / t_pix) / 60
print(f'seed-to-pixel maps would need 200 frames for each of the {n_all} trials of the jRGECO1a sessions, {gb:.0f} GB; '
      f'at the rate of the fig3h pixel reads, {t_read:.0f} min of reading')
t_nb = (time.time() - T0_NB) / 60
print(f'this notebook has run {t_nb:.0f} min up to here; with the reads, {t_nb + t_read:.0f} min, against the 60 min notebook limit; '
      f'the reads alone take {t_read / 60 * 100:.0f}% of the limit of a separate notebook, before the 1,000 block shuffles per seed and pixel')
print('sessions failed', [k for k, v in PC.items() if isinstance(v, str)])
rows = []
for sid, C in PC.items():
    tr = trial_table(sid); assert len(tr) == len(C)
    w = (tr.trial_type == 'whisker_trial').values; corr = (tr.lick_flag == tr.context).values
    for ctx in (0, 1):
        for oc, m in [('correct', corr), ('incorrect', ~corr)]:
            s_ = w & (tr.context.values == ctx) & m & np.isfinite(C[:, 0, 1])
            if s_.sum() == 0: continue
            mc = C[s_].mean(0)
            for a, b in PAIRS:
                rows.append((sid.split('_')[0], sid, ctx, oc, f'{a}-{b}', mc[SEEDS.index(a), SEEDS.index(b)], s_.sum()))
R4 = pd.DataFrame(rows, columns=['mouse', 'session', 'context', 'outcome', 'pair', 'r', 'n'])
print('whisker trials with a full 2 s window per session and group, median:', R4.groupby(['session', 'context', 'outcome']).n.first().groupby(['context', 'outcome']).median().to_dict())
Mm = R4.groupby(['mouse', 'context', 'outcome', 'pair']).r.mean().unstack(['outcome', 'context'])
for oc in ['correct', 'incorrect']:
    print(oc, 'trials, mice', Mm.index.get_level_values(0).nunique())
    for a, b in PAIRS:
        x = Mm.xs(f'{a}-{b}', level='pair'); wm, wp = x[(oc, 0)].values, x[(oc, 1)].values
        dd = wm - wp; tt = stats.ttest_rel(wm, wp)
        print(f'   {a}-{b}: W- {wm.mean():.3f}, W+ {wp.mean():.3f}, W- minus W+ {dd.mean():+.3f}, paired d {dd.mean() / dd.std(ddof=1):+.2f}, t {tt.statistic:.2f}, p x7 {min(1, 7 * tt.pvalue):.3f}')
print('W+ incorrect minus W+ correct:', {f'{a}-{b}': round(float((Mm.xs(f'{a}-{b}', level='pair')[('incorrect', 1)] - Mm.xs(f'{a}-{b}', level='pair')[('correct', 1)]).mean()), 3) for a, b in PAIRS})
seed-to-pixel maps would need 200 frames for each of the 11476 trials of the jRGECO1a sessions, 367 GB; at the rate of the fig3h pixel reads, 47 min of reading
this notebook has run 46 min up to here; with the reads, 92 min, against the 60 min notebook limit; the reads alone take 78% of the limit of a separate notebook, before the 1,000 block shuffles per seed and pixel
sessions failed []
whisker trials with a full 2 s window per session and group, median: {(0, 'correct'): 67.0, (0, 'incorrect'): 25.0, (1, 'correct'): 80.0, (1, 'incorrect'): 13.0}
correct trials, mice 6
   ALM-tjM1: W- 0.881, W+ 0.865, W- minus W+ +0.016, paired d +0.88, t 2.17, p x7 0.578
   ALM-tjS1: W- 0.791, W+ 0.767, W- minus W+ +0.024, paired d +1.00, t 2.45, p x7 0.407
   tjM1-tjS1: W- 0.901, W+ 0.887, W- minus W+ +0.014, paired d +0.90, t 2.21, p x7 0.545
   wM1-ALM: W- 0.751, W+ 0.790, W- minus W+ -0.039, paired d -1.29, t -3.16, p x7 0.175
   wM1-tjM1: W- 0.580, W+ 0.611, W- minus W+ -0.030, paired d -0.64, t -1.56, p x7 1.000
   wS1-wS2: W- 0.824, W+ 0.805, W- minus W+ +0.019, paired d +1.17, t 2.86, p x7 0.249
   wS2-wM1: W- 0.642, W+ 0.631, W- minus W+ +0.011, paired d +0.28, t 0.68, p x7 1.000
incorrect trials, mice 6
   ALM-tjM1: W- 0.877, W+ 0.884, W- minus W+ -0.007, paired d -0.34, t -0.82, p x7 1.000
   ALM-tjS1: W- 0.788, W+ 0.797, W- minus W+ -0.009, paired d -0.31, t -0.76, p x7 1.000
   tjM1-tjS1: W- 0.891, W+ 0.899, W- minus W+ -0.007, paired d -0.36, t -0.88, p x7 1.000
   wM1-ALM: W- 0.768, W+ 0.737, W- minus W+ +0.032, paired d +0.59, t 1.44, p x7 1.000
   wM1-tjM1: W- 0.600, W+ 0.554, W- minus W+ +0.046, paired d +0.63, t 1.55, p x7 1.000
   wS1-wS2: W- 0.818, W+ 0.831, W- minus W+ -0.013, paired d -0.52, t -1.28, p x7 1.000
   wS2-wM1: W- 0.644, W+ 0.656, W- minus W+ -0.012, paired d -0.24, t -0.59, p x7 1.000
W+ incorrect minus W+ correct: {'ALM-tjM1': 0.019, 'ALM-tjS1': 0.03, 'tjM1-tjS1': 0.012, 'wM1-ALM': -0.053, 'wM1-tjM1': -0.057, 'wS1-wS2': 0.027, 'wS2-wM1': 0.025}

Result: blocked (other). The seed-to-pixel analysis the criterion needs was not run in this attempt. Its reads, estimated above, do not fit this notebook with the rest of the notebook, but in a separate notebook they would fit within the limit, so the data are not shown to be too large; that notebook was not built. In the ROI-trace variant, before correct trials W- is higher than W+ for 5 of the 7 pairs (paired d' at or above 0.8 for 4 of them) and lower for wM1-ALM and wM1-tjM1, and no pair passes the corrected t-test; before incorrect trials no pair has a W- minus W+ d' of 0.8 or more.

Summary¶

A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.

claim outcome
session-list-link partially reproduced (every list a claim uses matches; the pool list does not in full)
expert-sessions not reproduced (the Methods' rule selects more sessions and mice; the code's list matches)
fig1c-auditory-hit-both-contexts, fig1c-whisker-context-modulation, fig1d, fig1c-catch-higher-wplus, fig1e, fig1g, fig1f, fig1h, supp1c reproduced
supp1d-faster-response-wplus partially reproduced (tests match, means about 100 ms longer)
fig1i-pupil-larger-wplus, fig1i-posture-before-lick reproduced
fig1j-jaw-speed-context partially reproduced (jaw holds; whisker speed differs by context)
fig1k-model-accuracy, fig1k-context-strongest-feature reproduced
fig1l-shap-whisker-trial-in-block not reproduced (trial 1 of a block moves against the new context; trial 2 toward it)
fig2c, fig2d, fig2e (2 claims), fig2-no-effect-control-mice, fig2cd-rsc, fig2f blocked, methods_underspecified (the null and threshold readings disagree)
supp2-muscimol-ws1-rsc reproduced
fig3c-jaw-onset reproduced, resting on the Methods' correct whisker trials (assumption)
fig3e-auditory-similar-across-contexts partially reproduced (similar, A1 first; the order of the others not found)
fig3f-whisker-divergence-after-50ms reproduced
fig3h-rsc-first-context-discrimination blocked, methods_underspecified (reproduced with the 50 ms baseline; a tie in the pixel version with the 250 ms baseline)
fig3-gcamp-consistent-controls-flat partially reproduced (GCaMP6f holds; control mice also show W+ vs W- differences)
supp3c-rsc-projects-to-wm blocked, data_missing
fig4b (3 claims) blocked, other (the seed-to-pixel analysis was not run in this attempt); an ROI-trace variant is shown
fig4c-inhibition-propagates-forward, supp4d-photoactivation-control, fig4fg-angle-predicts-lick-change reproduced
fig4d-trajectories-follow-lick not reproduced
fig4e-rsc-tjs1-smaller-angle partially reproduced (W+ only at RSC (-1.5, 0.5); both contexts at (-0.5, 0.5))

Differences from the paper's method: session groups and mouse lines come from the code's lists, since the files do not record the lines; the opto-map nulls and thresholds are run under every reading the claims file names; the Figure 3H pixel maps are computed from windowed reads of the stack, while the Figure 4A-B seed-to-pixel correlations are not run (an ROI-trace variant is shown); the gradient-boosted model of Figure 1K-L is rebuilt from the code and run with 4 threads.

What was found about the dataset: the subject genotype is "WT" for every mouse but one, so no file says which mice carry VGAT-ChR2, jRGECO1a, GCaMP6f, tdTomato or GFP; session type and day (Context Off, muscimol or Ringer, baseline or injection) are not recorded in a usable form; the DLC series carry the unit "seconds" and a conversion of 1/28 or 1/24 that does not turn them into the units of the paper (the whisker angle is stored in degrees, the pupil area in square pixels); three files have no context epochs; in some files the DLC timestamps and data differ in length; lick_time minus the stimulus time is about 100 ms longer than the paper's spout-contact times; the Context Off sessions still label their trials pink and brown noise. The printed outputs above give the numbers.