Ito & Doya (2009) from dandiset 001641¶

Paper: Ito M, Doya K (2009) Validation of decision-making models and analysis of decision variables in the rat basal ganglia. J Neurosci 29:9861-9874, doi:10.1523/jneurosci.6157-08.2009.

Dataset: DANDI:001641, version 0.260922.0719, streamed from the archive. The paper cites no version of the dataset (it predates it), so the most recent published version is pinned. It is the only published version, and its 70 files, 6 subjects and contents are those of the draft; nothing in the description of the claims file suggests an earlier version would match better.

Claims: claims/001641/10.1523-jneurosci.6157-08.2009.yaml, written from the version of record (PMC6666589) with the supplemental Methods (particle filter); supplemental Data 1 to 3 were not available to the reader. The paper links no code.

Claim Tested here
trial-counts, block-structure, reaction-time, tone-discrimination-errors tested
fig2b-reward-stronger-than-noreward, fig2b-two-back-history, fig2c-sequence-frequencies, fig2c-reward-effects-fade, fig2d-switching, fig2e-persevering tested
fig3-lsq-switching, table1-lsq-parameters tested
fig5-markov-accuracy, fig5-constant-models, fig5-variable-models-best, fig5-fq-dfq-beat-all-models, fig5-fq-dfq-no-difference, binary-prediction-accuracy, table2-ml-parameters, table3-parameter-averages, fig4-strategy-tracking, suppdata1-choice-vs-q-difference tested
neuron-counts, firing-rates, fig8b-state-coding, fig8b-action-value-psth, fig8b-action-command-coding, fig8b-action-coding, fig8b-reward-coding, fig8b-nac-vp-same-event-coding, fig8b-ql-vp-higher, fig8b-qr-no-region-difference, preference-balance, nac-noreward-preference tested
core-shell-no-difference blocked: the dataset does not say which NAc units are in the core or the shell
fig8c-regression-action-value, fig8c-ql-vp-higher, fig8c-regression-detects-more, fig8d-state-value-vp-higher, fig8d-policy, fig8-above-chance tested
fig9-state-information, fig9-action-information, fig9-reward-information, fig9-action-value-information-low, action-information-outlasts-reward-peak tested

Where the claims file lists readings of a method (O1 to O15 in its opening comment), every reading is run and shown. Method details the claims file does not give are taken from the paper and cited in the helper module ito2009.py.

In [1]:
import os
os.environ.setdefault("OMP_NUM_THREADS", "1")
import time
import numpy as np
import pandas as pd
import scipy.stats as ss
import statsmodels.api as sm
import matplotlib.pyplot as plt
import ito2009 as I

pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)
T0 = time.time()
print("dandiset", I.DANDISET, "version", I.VERSION)
dandiset 001641 version 0.260922.0719
In [2]:
assets = I.list_assets()
S = I.load_all(assets)
print(f"{len(S)} files streamed in {time.time() - T0:.0f} s")
70 files streamed in 48 s

Data check¶

In [3]:
T = I.all_trials(S)
seqs = I.choice_sequences(T)
per = pd.DataFrame([dict(file=s["path"].split("/")[1], subject=s["subject"], trials=len(s["trials"]),
                         blocks=len(s["blocks"]), finished_blocks=int(s["blocks"].FinishedBlock.sum()),
                         NAc=int((s["units"].area == "NAc").sum()), VP=int((s["units"].area == "VP").sum()))
                    for s in S])
print("files", len(S), "subjects", per.subject.nunique(), sorted(per.subject.unique()))
print("subject in file path equals subject_id in the file:",
      all(s["subject"] == s["subject_file"] for s in S))
print(per.groupby("subject")[["trials", "blocks", "NAc", "VP"]].agg(["count", "sum"]))
print("files without a units table:", [s["path"] for s in S if len(s["units"]) == 0])
print("sessions with no unit:", int(((per.NAc + per.VP) == 0).sum()))
print("\nTrial table: state x result x action x reward (all sessions)")
print(pd.crosstab([T.state.fillna(-1), T.result], [T.action.fillna(0), T.reward.fillna(-1)]))
print("\nunit areas:", pd.concat([s["units"] for s in S]).area.value_counts().to_dict())
print("electrode IDs by area:", pd.concat([s["units"] for s in S]).groupby("area").electrode.agg(["min", "max"]).to_dict())
files 70 subjects 6 ['31', '32', '34', '35', '42', '44']
subject in file path equals subject_id in the file: True
        trials        blocks        NAc        VP    
         count    sum  count  sum count sum count sum
subject                                              
31          13   9714     13  115    13  44    13  34
32          11   8466     11   91    11  19    11   2
34           9   8549      9   68     9  29     9  11
35          12  10385     12   93    12  45    12   0
42          13  11656     13  101    13  10    13  19
44          12  11441     12  106    12   1    12   0
files without a units table: ['sub-32/sub-32_ses-LE32-S1-02_ecephys.nwb', 'sub-32/sub-32_ses-LE32-S1-11_ecephys.nwb', 'sub-34/sub-34_ses-LE34-S1-01_ecephys.nwb', 'sub-35/sub-35_ses-LE35-S1-01_ecephys.nwb', 'sub-35/sub-35_ses-LE35-S1-10_ecephys.nwb', 'sub-42/sub-42_ses-LE42-S1-03_ecephys.nwb', 'sub-42/sub-42_ses-LE42-S1-05_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-01_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-02_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-03_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-04_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-06_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-07_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-08_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-09_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-10_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-11_ecephys.nwb', 'sub-44/sub-44_ses-LE44-S1-12_ecephys.nwb']
sessions with no unit: 18

Trial table: state x result x action x reward (all sessions)
action         0.0          1.0          2.0       
reward         0.0    1.0   0.0    1.0   0.0    1.0
state result                                       
-1.0  2.0        1      0     0      0     0      0
 1.0  1.0        0      0     0  10149     0  10387
      2.0     6842      0     0      0     0      0
      3.0        0      0  9226      0  9413      0
      5.0      104      0     0      0     0      0
 2.0  1.0        0  12707     0      0     0      0
      2.0     1241      0     0      0     0      0
      4.0      141      0     0      0     0      0

unit areas: {'NAc': 148, 'VP': 66}
electrode IDs by area: {'min': {'NAc': 1, 'VP': 17}, 'max': {'NAc': 16, 'VP': 32}}
In [4]:
# Event series: tone durations against the paper's (Behavioral task: start tone 1000 ms, cue tones
# 1000-2000 ms, reward tone 1000 ms, no-reward tone 250 ms, error tone 1000 ms).
def durations(name):
    out = []
    for s in S:
        ts, d = s["events"][name]
        a, b = ts[d == 1], ts[d == -1]
        m = min(len(a), len(b))
        out.append(b[:m] - a[:m])
    return np.concatenate(out)

for name in ["SpTone A", "SpTone B", "SpTone Rwd", "SpTone Err", "ViTrial Start Tone"]:
    d = durations(name)
    print(f"{name:20s} n={len(d):6d}  duration percentiles 1/50/99 = {np.percentile(d, [1, 50, 99]).round(3)} s")
d = durations("SpTone Err")
print("SpTone Err: under 1.5 s", int((d < 1.5).sum()), " over 1.5 s", int((d >= 1.5).sum()))
print("unrewarded choice trials (result 3):", int((T.result == 3).sum()),
      " error trials (result != 1, 3):", int(((T.result != 1) & (T.result != 3)).sum()))

# Clock: the trial table's event times against the acquisition series of the same sensor
dev = []
for s in S:
    ts, d = s["events"]["SpSensor C"]
    on = ts[d == 1]
    x = s["trials"].pokeC_on_time.dropna().values
    k = np.clip(np.searchsorted(on, x), 0, len(on) - 1)
    k2 = np.clip(k - 1, 0, len(on) - 1)
    dev.append(np.minimum(np.abs(on[k] - x), np.abs(on[k2] - x)))
dev = np.concatenate(dev)
print(f"\ncenter-hole entry in the trial table vs SpSensor C onsets: median |diff| {np.median(dev)*1e3:.3f} ms, 99th pct {np.percentile(dev, 99)*1e3:.1f} ms")

# Reward rules and block counts
print("\nblock reward rules (L, R):", T.groupby(["rule_L", "rule_R"]).size().to_dict())
print("blocks per session: min", per.blocks.min(), "max", per.blocks.max(), "total", per.blocks.sum(),
      "finished", per.finished_blocks.sum())
print("choice trials:", int(T.choice.sum()), " no-choice:", int(T.nochoice.sum()), " errors:", int(T.error.sum()))
print("units: spike times sorted in every unit:",
      all(np.all(np.diff(st) >= 0) for s in S for st in s["units"].spike_times))
SpTone A             n= 46066  duration percentiles 1/50/99 = [0.458 1.486 2.057] s
SpTone B             n= 14120  duration percentiles 1/50/99 = [0.807 1.522 2.062] s
SpTone Rwd           n= 33296  duration percentiles 1/50/99 = [1.005 1.05  1.158] s
SpTone Err           n= 26973  duration percentiles 1/50/99 = [0.255 0.311 2.071] s
ViTrial Start Tone   n= 60211  duration percentiles 1/50/99 = [1.    1.009 1.445] s
SpTone Err: under 1.5 s 18674  over 1.5 s 8299
unrewarded choice trials (result 3): 18639  error trials (result != 1, 3): 8329

center-hole entry in the trial table vs SpSensor C onsets: median |diff| 0.000 ms, 99th pct 0.0 ms

block reward rules (L, R): {(10.0, 50.0): 15922, (50.0, 10.0): 14775, (50.0, 90.0): 13847, (90.0, 50.0): 15667}
blocks per session: min 5 max 12 total 574 finished 521
choice trials: 39175  no-choice: 12707  errors: 8329
units: spike times sorted in every unit: True
In [5]:
# Recordings deposited more than once: identical trial tables or identical spike trains across files.
sig_trials = {}
for s in S:
    key = (len(s["trials"]), round(float(s["trials"].start_time.sum()), 3))
    sig_trials.setdefault(key, []).append(s["path"])
print("files sharing a trial table:", [v for v in sig_trials.values() if len(v) > 1])
sig_units = {}
for s in S:
    for _, u in s["units"].iterrows():
        st = u.spike_times
        key = (len(st), round(float(st[:50].sum()), 4) if len(st) else 0.0)
        sig_units.setdefault(key, []).append((s["path"].split("/")[1], u.unit_name))
print("unit spike trains that occur more than once:", [v for v in sig_units.values() if len(v) > 1])
files sharing a trial table: []
unit spike trains that occur more than once: []
In [6]:
# Spikes share the trial clock: action selectivity after center-hole exit (phase 4, left vs right
# choice trials) with the true alignment and with the alignment shifted by 30 s, where none is expected.
rows = []
for k, s in enumerate(S):
    if len(s["units"]) == 0:
        continue
    t = T[T.sess == k].reset_index(drop=True)
    L = (t.choice & (t.action == 1)).values
    R = (t.choice & (t.action == 2)).values
    for _, u in s["units"].iterrows():
        st = np.sort(u.spike_times)
        for shift in [0.0, 30.0]:
            c = I.count_spikes(st, t.pokeC_off_time.values + shift, 1.0)
            rows.append(dict(sess=k, shift=shift, sig=I.mw_p(c[L], c[R]) < 0.01))
clk = pd.DataFrame(rows)
print("units with L/R difference (p < 0.01) after center exit, by shift:",
      clk.groupby("shift").sig.agg(["sum", "count"]).to_dict("index"))
by = clk.pivot_table(index="sess", columns="shift", values="sig", aggfunc="sum")
print("sessions with units where no unit is selective at the true alignment:",
      [S[i]["path"].split("/")[1] for i in by.index[by[0.0] == 0]])
units with L/R difference (p < 0.01) after center exit, by shift: {0.0: {'sum': 89, 'count': 214}, 30.0: {'sum': 10, 'count': 214}}
sessions with units where no unit is selective at the true alignment: ['sub-32_ses-LE32-S1-03_ecephys.nwb', 'sub-32_ses-LE32-S1-04_ecephys.nwb', 'sub-32_ses-LE32-S1-06_ecephys.nwb', 'sub-32_ses-LE32-S1-07_ecephys.nwb', 'sub-32_ses-LE32-S1-10_ecephys.nwb', 'sub-34_ses-LE34-S1-08_ecephys.nwb', 'sub-35_ses-LE35-S1-07_ecephys.nwb', 'sub-35_ses-LE35-S1-08_ecephys.nwb', 'sub-35_ses-LE35-S1-09_ecephys.nwb', 'sub-35_ses-LE35-S1-11_ecephys.nwb', 'sub-42_ses-LE42-S1-02_ecephys.nwb', 'sub-42_ses-LE42-S1-08_ecephys.nwb', 'sub-42_ses-LE42-S1-09_ecephys.nwb', 'sub-42_ses-LE42-S1-11_ecephys.nwb', 'sub-44_ses-LE44-S1-05_ecephys.nwb']

The trial result column has no description in the files ("Refer to the Discription in 'Result' column", but no such description is there). From the table above: result 1 is a rewarded tone-A choice or a successful tone-B trial, 3 an unrewarded tone-A choice, and 2, 4 and 5 end without reward and without a successful choice, so they are errors. The no-reward tone of choice trials is stored in the SpTone Err series (short tones, about 0.3 s), together with the error tone (about 2 s, where the paper says 1000 ms). The counts of choice, no-choice and error trials are printed above and used below.

Checks of the description against the data: 6 subjects and 70 sessions as described; units labelled NAc on electrodes 1 to 16 and VP on 17 to 32, as the electrode groups say; the four reward rules of the paper and 5 to 12 blocks per session; tone durations as the paper gives them except the error tone. The trial table's center-hole entries coincide with the SpSensor C onsets (same clock). The spikes share the trial clock: 89 of 214 units differ between left and right choices in the second after center exit, against 10 when the alignment is shifted by 30 s. This is shown for the pooled units; in the 15 sessions listed above no unit is selective, so for them the alignment is consistent with the data, not shown.

trial-counts¶

The analysis covers 60,221 trials in 70 recording sessions from six rats, of which 39,175 are choice trials, 12,707 no-choice trials and 8329 error trials.

Readings of the total: (a) all trials started (rows of the trial tables); (b) trials in which a cue tone was presented.

In [7]:
n_all = len(T)
n_cue = int(T.tone_on_time.notna().sum())
print("sessions", len(S), " rats", T.subject.nunique())
print("total trials (a) all rows:", n_all, " (b) with a cue tone:", n_cue)
print("choice", int(T.choice.sum()), " no-choice", int(T.nochoice.sum()), " error", int(T.error.sum()))
print("choice + no-choice + error =", int(T.choice.sum() + T.nochoice.sum() + T.error.sum()))
print("paper: 60,221 total; 39,175 + 12,707 + 8329 =", 39175 + 12707 + 8329)
print("by rat:\n", T.groupby("subject").agg(trials=("choice", "size"), choice=("choice", "sum"),
                                          nochoice=("nochoice", "sum"), error=("error", "sum")))
sessions 70  rats 6
total trials (a) all rows: 60211  (b) with a cue tone: 60211
choice 39175  no-choice 12707  error 8329
choice + no-choice + error = 60211
paper: 60,221 total; 39,175 + 12,707 + 8329 = 60211
by rat:
          trials  choice  nochoice  error
subject                                 
31         9714    6174      2029   1511
32         8466    5640      1725   1101
34         8549    5394      1814   1341
35        10385    7051      2153   1181
42        11656    7469      2312   1875
44        11441    7447      2674   1320

Result: reproduced. Under both readings there are 60,211 trials (within 10% of 60,221), 70 sessions, 6 rats, 39,175 choice, 12,707 no-choice and 8329 error trials, the last three exactly as reported. The paper's three parts sum to 60,211, so its total of 60,221 differs from its own parts by 10.

block-structure¶

A block took 105.6 trials on average, and a session held 8.1 blocks on average, from 5 to 12.

Readings (criterion): (a) all trials, every block; (b) all trials, completed blocks only; (c) choice trials only, every block; (d) choice trials, completed blocks only. Blocks come from the BlockDesign table and its FinishedBlock flag; trials are assigned to blocks by the trial table's block column.

In [8]:
B = T.groupby(["sess", "block"]).agg(n_all=("choice", "size"), n_choice=("choice", "sum"),
                                     finished=("block_finished", "first")).reset_index()
nb_tab = pd.concat([s["blocks"].assign(sess=i) for i, s in enumerate(S)])
print("blocks in BlockDesign:", len(nb_tab), " blocks with trials:", len(B))
res = []
for name, col, fin in [("a", "n_all", False), ("b", "n_all", True), ("c", "n_choice", False), ("d", "n_choice", True)]:
    b = B[B.finished == 1] if fin else B
    per_sess = b.groupby("sess").size().reindex(range(len(S)), fill_value=0)
    res.append(dict(reading=name, mean_trials_per_block=b[col].mean(), mean_blocks=per_sess.mean(),
                    min_blocks=per_sess.min(), max_blocks=per_sess.max()))
res = pd.DataFrame(res)
exp = dict(mean_trials_per_block=(105.6, 10.56), mean_blocks=(8.1, 0.81), min_blocks=(5, 0.5), max_blocks=(12, 1.2))
for c, (v, tol) in exp.items():
    res[c + "_ok"] = (res[c] - v).abs() <= tol
print(res.round(2).to_string())
blocks in BlockDesign: 574  blocks with trials: 574
  reading  mean_trials_per_block  mean_blocks  min_blocks  max_blocks  mean_trials_per_block_ok  mean_blocks_ok  min_blocks_ok  max_blocks_ok
0       a                 104.90         8.20           5          12                      True            True           True           True
1       b                 107.87         7.44           4          11                      True            True          False           True
2       c                  68.25         8.20           5          12                     False            True           True           True
3       d                  70.19         7.44           4          11                     False            True          False           True

Result: reproduced. Under reading (a), all trials and every block, a block holds 104.9 trials on average and a session 8.2 blocks, from 5 to 12, all within tolerance. Readings counting choice trials only or completed blocks only do not match (table above).

reaction-time¶

In choice trials the time from center-hole exit to L or R hole entry was under 1 s in 72% of trials, with a median of 0.75 s.

In [9]:
C = T[T.choice]
rt_all = (C.action_on_time - C.pokeC_off_time).values
print("choice trials", len(rt_all), " missing", int(np.isnan(rt_all).sum()), " negative", int((rt_all < 0).sum()),
      "(values", np.sort(rt_all[rt_all < 0]).round(3), "; left out as timing errors)")
rt = rt_all[rt_all >= 0]
print(f"under 1 s: {100 * np.mean(rt < 1):.1f}%   median {np.median(rt):.3f} s   range {rt.min():.3f} to {rt.max():.1f} s")
print(f"with the negative values kept: under 1 s {100 * np.mean(rt_all < 1):.1f}%, median {np.median(rt_all):.3f} s")
print(C.assign(rt=rt_all)[rt_all >= 0].groupby("subject").rt.agg(lambda x: f"{100*np.mean(x < 1):.1f}% / median {np.median(x):.2f}"))
choice trials 39175  missing 0  negative 3 (values [-1.9828694e+04 -1.1553720e+04 -5.1550000e+00] ; left out as timing errors)
under 1 s: 72.1%   median 0.754 s   range 0.109 to 59.4 s
with the negative values kept: under 1 s 72.1%, median 0.754 s
subject
31    88.1% / median 0.73
32    91.3% / median 0.53
34    85.9% / median 0.69
35    35.0% / median 1.11
42    57.3% / median 0.92
44    84.5% / median 0.63
Name: rt, dtype: str

Result: reproduced. Over 39,172 choice trials (3 with a negative reaction time left out), 72.1% of reaction times are under 1 s and the median is 0.754 s, against 72% and 0.75 s. Keeping the three gives the same values. The rats differ (35.0% to 91.3% under 1 s).

tone-discrimination-errors¶

Rats rarely failed to poke after tone A (0.39% of choice trials) or poked wrongly after tone B (0.73% of no-choice trials).

Numerators, from the definitions in the Results (paragraph 2 of "Reaction time and tone discrimination"): tone-A trials in which the rat held the cue (did not leave the center hole before cue offset) and made no L or R entry within 60 s of center exit; tone-B trials in which the rat held the cue and entered L or R within 1 s of center exit. L/R entries are taken from the SpSensor L and SpSensor R series, as the trial table's action time is not filled for every error trial. The result codes 5 (tone A, 104 trials) and 4 (tone B, 141 trials), the rare error codes, are shown as a variant numerator. Denominators are the claim's readings (a) successful trials of that tone; (b) those plus the errors.

In [10]:
def lr_entries(s):
    out = []
    for n in ["SpSensor L", "SpSensor R"]:
        ts, d = s["events"][n]
        out.append(ts[d == 1])
    return np.sort(np.concatenate(out))

errA, errB = [], []   # (tone duration, result code, center exit minus tone offset) of each counted error trial
for k, s in enumerate(S):
    t = T[T.sess == k]
    lr = lr_entries(s)
    held = t.pokeC_off_time >= t.tone_off_time - 0.01
    for _, r in t[(t.state == 1) & held & t.error].iterrows():
        nxt = lr[lr > r.pokeC_off_time]
        if len(nxt) == 0 or nxt[0] - r.pokeC_off_time > 60:
            errA.append((r.tone_off_time - r.tone_on_time, r.result, r.pokeC_off_time - r.tone_off_time))
    for _, r in t[(t.state == 2) & held & t.error].iterrows():
        nxt = lr[lr > r.pokeC_off_time]
        if len(nxt) and nxt[0] - r.pokeC_off_time <= 1.0:
            errB.append((r.tone_off_time - r.tone_on_time, r.result, r.pokeC_off_time - r.tone_off_time))
errA, errB = np.array(errA), np.array(errB)
noresp, wrongB = len(errA), len(errB)
# The cue lasts 1000-2000 ms (Behavioral task); a shorter tone probably means the rat left the center hole
# and the tone stopped with it, which the `held` test above cannot exclude. Recount with tones of >= 1 s.
noresp1, wrongB1 = int((errA[:, 0] >= 1.0).sum()), int((errB[:, 0] >= 1.0).sum())
for lab, e in [("tone A, no L/R entry within 60 s", errA), ("tone B, L/R entry within 1 s", errB)]:
    print(f"{lab}: {len(e)} trials; tone duration percentiles 1/5/50 = {np.percentile(e[:, 0], [1, 5, 50]).round(3)} s; "
          f"under 1 s: {int((e[:, 0] < 1.0).sum())}; result codes {pd.Series(e[:, 1]).value_counts().to_dict()}")
# If the tone stops when the rat leaves, the center exit of a short-tone trial falls at the tone offset.
for lab, e in [("tone A", errA), ("tone B", errB)]:
    for part, m in [("tone < 1 s", e[:, 0] < 1.0), ("tone >= 1 s", e[:, 0] >= 1.0)]:
        if m.any():
            print(f"{lab}, {part}: {int(m.sum())} trials; center exit minus tone offset, percentiles 5/50/95 = "
                  f"{np.percentile(e[m, 2], [5, 50, 95]).round(3)} s")
for lab, st, code in [("A", 1, 5), ("B", 2, 4)]:
    d = T[(T.state == st) & (T.result == code)]
    print(f"result code {code} (tone {lab}): tone duration percentiles 1/50 = {np.percentile(d.tone_off_time - d.tone_on_time, [1, 50]).round(3)} s")
nA, nB = int(T.choice.sum()), int(T.nochoice.sum())
code5, code4 = int((T.result == 5).sum()), int((T.result == 4).sum())
rows = []
for lab, eA, eB in [("events", noresp, wrongB), ("events, tone >= 1 s", noresp1, wrongB1), ("result codes 5 and 4", code5, code4)]:
    for rd, dA, dB in [("a", nA, nB), ("b", nA + eA, nB + eB)]:
        rows.append(dict(numerator=lab, reading=rd, errors_A=eA, pct_A=100 * eA / dA, errors_B=eB, pct_B=100 * eB / dB))
te = pd.DataFrame(rows)
te["A_ok"] = (te.pct_A - 0.39).abs() <= 0.039
te["B_ok"] = (te.pct_B - 0.73).abs() <= 0.073
print(te.round(3).to_string())
print("paper: 0.39% (tone A no response, tol 0.039), 0.73% (tone B L/R poke, tol 0.073)")
tone A, no L/R entry within 60 s: 317 trials; tone duration percentiles 1/5/50 = [0.12  0.301 1.256] s; under 1 s: 96; result codes {2.0: 284, 5.0: 33}
tone B, L/R entry within 1 s: 129 trials; tone duration percentiles 1/5/50 = [0.249 1.037 1.406] s; under 1 s: 4; result codes {4.0: 123, 2.0: 6}
tone A, tone < 1 s: 96 trials; center exit minus tone offset, percentiles 5/50/95 = [-0.01  -0.007 -0.003] s
tone A, tone >= 1 s: 221 trials; center exit minus tone offset, percentiles 5/50/95 = [-0.01  -0.006  2.133] s
tone B, tone < 1 s: 4 trials; center exit minus tone offset, percentiles 5/50/95 = [-0.006 -0.005 -0.004] s
tone B, tone >= 1 s: 125 trials; center exit minus tone offset, percentiles 5/50/95 = [0.244 0.645 2.185] s
result code 5 (tone A): tone duration percentiles 1/50 = [1.051 1.549] s
result code 4 (tone B): tone duration percentiles 1/50 = [1.031 1.461] s
              numerator reading  errors_A  pct_A  errors_B  pct_B   A_ok   B_ok
0                events       a       317  0.809       129  1.015  False  False
1                events       b       317  0.803       129  1.005  False  False
2   events, tone >= 1 s       a       221  0.564       125  0.984  False  False
3   events, tone >= 1 s       b       221  0.561       125  0.974  False  False
4  result codes 5 and 4       a       104  0.265       141  1.110  False  False
5  result codes 5 and 4       b       104  0.265       141  1.097  False  False
paper: 0.39% (tone A no response, tol 0.039), 0.73% (tone B L/R poke, tol 0.073)

Result: not reproduced. No numerator and denominator gives both rates. Counted from the events, 317 tone-A trials without an L or R entry within 60 s (0.81% of choice trials) and 129 tone-B trials with an L or R entry within 1 s (1.0% of no-choice trials). 96 of the 317 tone-A trials had a tone shorter than 1 s (1st percentile 0.12 s), shorter than any cue the task gives (1000 to 2000 ms), so the rat probably left the center hole and the tone stopped with it; keeping tones of at least 1 s gives 221 and 125 trials (0.56% and 0.98%). This filter gives only an upper bound for tone A, since a cue of 1 to 2 s cut short after 1 s still passes it. Counted from the rare result codes 5 and 4, whose tones last over 1 s (1st percentile 1.05 and 1.03 s), 0.27% and 1.1%. For tone A the paper's 0.39% lies between the counts (0.27% to 0.81%), so the tone-A rate is not determined by these data. For tone B every count gives 0.97% to 1.11%, above the paper's 0.73% and outside its tolerance (0.073); the outcome rests on this part. The files do not say which result code marks which error, so the paper's counting cannot be identified.

History dependence (Fig. 2)¶

Conditional probabilities as the Methods define them: P(L | history) = NL / (NL + NR) over the choice trials that follow the history, pooled over all sessions, with the 99% interval betainv([0.005 0.995], NL, NR). Histories (O7): (a) the history and the following choice lie in one block; (b) within one session across block borders. Mann-Whitney tests (O8): (a) the 0/1 left-choice indicators of the trials following each history, pooled; (b) per-session conditional probabilities (sessions with at least one occurrence). Two-sided.

In [11]:
H = {wb: {d: I.history_counts(seqs, d, wb) for d in [1, 2, 3, 4]} for wb in [True, False]}
RD = {"a": True, "b": False}

def cond(h, wb):
    p = I.parse(h)
    v = H[wb][len(p)].get(p, [])
    x = np.array([y for y, _ in v])
    nl, nr = int(x.sum()), int(len(x) - x.sum())
    lo, hi = ss.beta.ppf([0.005, 0.995], max(nl, 1e-9), max(nr, 1e-9))
    return dict(history=h, n=len(x), P=nl / max(len(x), 1), ci_lo=lo, ci_hi=hi)

def mw_hist(h1, h2, wb):
    v1 = H[wb][len(I.parse(h1))].get(I.parse(h1), [])
    v2 = H[wb][len(I.parse(h2))].get(I.parse(h2), [])
    x1 = np.array([y for y, _ in v1]); x2 = np.array([y for y, _ in v2])
    pa = ss.mannwhitneyu(x1, x2, alternative="two-sided").pvalue
    s1 = pd.Series(x1).groupby([k for _, k in v1]).mean(); s2 = pd.Series(x2).groupby([k for _, k in v2]).mean()
    pb = ss.mannwhitneyu(s1, s2, alternative="two-sided").pvalue
    return pa, pb, len(s1), len(s2)

def prefixes(seq):
    e = seq.split()
    return [" ".join(e[i:]) for i in range(len(e) - 1, -1, -1)]

fig2b-reward-stronger-than-noreward¶

Both L1 and R0 in the previous trial raise the left-choice probability (0.68 and 0.62), more after L1; both R1 and L0 lower it (0.30 and 0.39), more after R1.

In [12]:
for rd, wb in RD.items():
    tab = pd.DataFrame([cond(h, wb) for h in ["L1", "R0", "L0", "R1"]])
    tab["expected"] = [0.68, 0.62, 0.39, 0.30]
    tab["ok"] = (tab.P - tab.expected).abs() <= 0.1 * tab.expected
    print(f"O7 ({rd})\n", tab.round(4).to_string())
    P = dict(zip(tab.history, tab.P))
    print("  order P(L|L1) > P(L|R0) > 0.5 > P(L|L0) > P(L|R1):", P["L1"] > P["R0"] > 0.5 > P["L0"] > P["R1"])
    for h1, h2 in [("L1", "R0"), ("R1", "L0")]:
        pa, pb, n1, n2 = mw_hist(h1, h2, wb)
        print(f"  {h1} vs {h2}: Mann-Whitney O8 (a) trials p = {pa:.2e}; O8 (b) sessions p = {pb:.2e} (n = {n1}, {n2})")
print("by rat, O7 (a):")
for sb in sorted(T.subject.unique()):
    ss_ = [s for s in seqs if s.subject.values[0] == sb]
    hh = I.history_counts(ss_, 1, True)
    print("  rat", sb, {h: round(np.mean([y for y, _ in hh[I.parse(h)]]), 3) for h in ["L1", "R0", "L0", "R1"]})
O7 (a)
   history      n       P   ci_lo   ci_hi  expected    ok
0      L1   9972  0.6775  0.6654  0.6895      0.68  True
1      R0   9319  0.6165  0.6035  0.6294      0.62  True
2      L0   9125  0.3862  0.3731  0.3994      0.39  True
3      R1  10185  0.3004  0.2888  0.3122      0.30  True
  order P(L|L1) > P(L|R0) > 0.5 > P(L|L0) > P(L|R1): True
  L1 vs R0: Mann-Whitney O8 (a) trials p = 7.53e-19; O8 (b) sessions p = 3.80e-06 (n = 70, 70)
  R1 vs L0: Mann-Whitney O8 (a) trials p = 4.01e-36; O8 (b) sessions p = 2.31e-06 (n = 70, 70)
O7 (b)
   history      n       P   ci_lo   ci_hi  expected    ok
0      L1  10135  0.6801  0.6681  0.6920      0.68  True
1      R0   9396  0.6155  0.6025  0.6284      0.62  True
2      L0   9205  0.3875  0.3745  0.4006      0.39  True
3      R1  10369  0.2987  0.2872  0.3103      0.30  True
  order P(L|L1) > P(L|R0) > 0.5 > P(L|L0) > P(L|R1): True
  L1 vs R0: Mann-Whitney O8 (a) trials p = 3.16e-21; O8 (b) sessions p = 1.23e-06 (n = 70, 70)
  R1 vs L0: Mann-Whitney O8 (a) trials p = 3.77e-39; O8 (b) sessions p = 9.73e-07 (n = 70, 70)
by rat, O7 (a):
  rat 31 {'L1': np.float64(0.704), 'R0': np.float64(0.508), 'L0': np.float64(0.443), 'R1': np.float64(0.355)}
  rat 32 {'L1': np.float64(0.696), 'R0': np.float64(0.586), 'L0': np.float64(0.466), 'R1': np.float64(0.304)}
  rat 34 {'L1': np.float64(0.659), 'R0': np.float64(0.64), 'L0': np.float64(0.397), 'R1': np.float64(0.295)}
  rat 35 {'L1': np.float64(0.658), 'R0': np.float64(0.685), 'L0': np.float64(0.261), 'R1': np.float64(0.222)}
  rat 42 {'L1': np.float64(0.693), 'R0': np.float64(0.521), 'L0': np.float64(0.442), 'R1': np.float64(0.348)}
  rat 44 {'L1': np.float64(0.661), 'R0': np.float64(0.711), 'L0': np.float64(0.301), 'R1': np.float64(0.264)}

Result: reproduced. Under both history readings P(L|L1) = 0.68, P(L|R0) = 0.62, P(L|L0) = 0.39 and P(L|R1) = 0.30, all within tolerance and in the stated order. Both Mann-Whitney tests give p < 0.0001 under both test readings (largest 3.80e-06). The order P(L|L1) > P(L|R0) does not hold in rats 35 and 44 taken alone.

fig2b-two-back-history¶

The experience two trials back still affects choice; P(L|R0 L1) = 0.66 differs from P(L|L1 L1) = 0.72.

In [13]:
for rd, wb in RD.items():
    tab = pd.DataFrame([cond(h, wb) for h in ["R0 L1", "L1 L1"]])
    tab["expected"] = [0.66, 0.72]
    tab["ok"] = (tab.P - tab.expected).abs() <= 0.1 * tab.expected
    pa, pb, n1, n2 = mw_hist("R0 L1", "L1 L1", wb)
    print(f"O7 ({rd})\n", tab.round(4).to_string())
    print(f"  difference {tab.P[1] - tab.P[0]:.3f}; Mann-Whitney O8 (a) p = {pa:.2e}; O8 (b) p = {pb:.2e}")
O7 (a)
   history     n       P   ci_lo   ci_hi  expected    ok
0   R0 L1  2739  0.6627  0.6392  0.6857      0.66  True
1   L1 L1  4289  0.7179  0.7000  0.7354      0.72  True
  difference 0.055; Mann-Whitney O8 (a) p = 9.09e-07; O8 (b) p = 3.22e-02
O7 (b)
   history     n       P   ci_lo   ci_hi  expected    ok
0   R0 L1  2768  0.6611  0.6377  0.6841      0.66  True
1   L1 L1  4464  0.7213  0.7039  0.7384      0.72  True
  difference 0.060; Mann-Whitney O8 (a) p = 5.93e-08; O8 (b) p = 1.20e-02

Result: blocked (methods underspecified). P(L|R0 L1) = 0.66 and P(L|L1 L1) = 0.72 under both history readings, in the stated order. The test on the trials' choices (O8 a) gives p = 9.1e-07 and 5.9e-08; the test on per-session probabilities (O8 b) gives p = 0.032 and 0.012, which do not reach p < 0.0001. The criterion asks for p < 0.0001 under every reading, and the claims file blocks a claim whose method readings disagree. O8 (a) is the reading under which the paper's p = 0.94 for Fig. 2C is matched (fig2c-reward-effects-fade), but the paper does not say what it ranked.

fig2c-sequence-frequencies¶

Of the 128 mirror-paired four-trial sequences, L1 L1 L1 L1 (with R1 R1 R1 R1) is the most frequent (6.87%), R0 L1 L1 L1 (with L0 R1 R1 R1) the second (2.87%), R0 L0 R0 L0 (with L0 R0 L0 R0) the third (2.55%), and L0 L0 L0 L0 with R0 R0 R0 R0 make 1.28%.

All windows of four consecutive choice trials; percentages of a pair are (a) the sum of the two mirror sequences or (b) their mean.

In [14]:
MIR = {0: 2, 1: 3, 2: 0, 3: 1}
for rd, wb in RD.items():
    W = I.window_counts(seqs, 4, wb)
    tot = sum(W.values())
    pairs = {}
    for p in W:
        q = tuple(MIR[x] for x in p)
        pairs[min(p, q)] = W.get(p, 0) + W.get(q, 0)
    ranked = sorted(pairs.items(), key=lambda kv: -kv[1])
    name = lambda k: " ".join(I.EXP[i] for i in k)
    print(f"O7 ({rd}): {tot} windows, {len(pairs)} pairs; top five:",
          [(name(k), round(100 * v / tot, 2)) for k, v in ranked[:5]])
    for pr, how in [("sum", 1.0), ("mean", 0.5)]:
        vals = []
        for h, e in [("L1 L1 L1 L1", 6.87), ("R0 L1 L1 L1", 2.87), ("R0 L0 R0 L0", 2.55), ("L0 L0 L0 L0", 1.28)]:
            p = I.parse(h); q = tuple(MIR[x] for x in p)
            v = how * 100 * (W.get(p, 0) + W.get(q, 0)) / tot
            vals.append((h, round(v, 3), e, abs(v - e) <= 0.1 * e))
        top3 = [name(k) for k, _ in ranked[:3]]
        want = [name(min(I.parse(h), tuple(MIR[x] for x in I.parse(h)))) for h in ["L1 L1 L1 L1", "R0 L1 L1 L1", "R0 L0 R0 L0"]]
        print(f"   pair as {pr}: {vals}; first three in order: {top3 == want}")
O7 (a): 37463 windows, 128 pairs; top five: [('L1 L1 L1 L1', 6.78), ('L0 R1 R1 R1', 2.94), ('L0 R0 L0 R0', 2.64), ('L1 L1 L1 L0', 2.07), ('L1 R0 L1 L1', 1.91)]
   pair as sum: [('L1 L1 L1 L1', 6.783, 6.87, True), ('R0 L1 L1 L1', 2.942, 2.87, True), ('R0 L0 R0 L0', 2.637, 2.55, True), ('L0 L0 L0 L0', 1.292, 1.28, True)]; first three in order: True
   pair as mean: [('L1 L1 L1 L1', 3.391, 6.87, False), ('R0 L1 L1 L1', 1.471, 2.87, False), ('R0 L0 R0 L0', 1.319, 2.55, False), ('L0 L0 L0 L0', 0.646, 1.28, False)]; first three in order: True
O7 (b): 38965 windows, 128 pairs; top five: [('L1 L1 L1 L1', 6.88), ('L0 R1 R1 R1', 2.87), ('L0 R0 L0 R0', 2.54), ('L1 L1 L1 L0', 2.34), ('L1 R0 L1 L1', 1.86)]
   pair as sum: [('L1 L1 L1 L1', 6.883, 6.87, True), ('R0 L1 L1 L1', 2.867, 2.87, True), ('R0 L0 R0 L0', 2.543, 2.55, True), ('L0 L0 L0 L0', 1.278, 1.28, True)]; first three in order: True
   pair as mean: [('L1 L1 L1 L1', 3.442, 6.87, False), ('R0 L1 L1 L1', 1.433, 2.87, False), ('R0 L0 R0 L0', 1.272, 2.55, False), ('L0 L0 L0 L0', 0.639, 1.28, False)]; first three in order: True

Result: reproduced. With a pair counted as the sum of the two mirror sequences, the four pairs make 6.78, 2.94, 2.64 and 1.29% (histories within blocks) or 6.88, 2.87, 2.54 and 1.28% (within sessions), all within tolerance, and the first three are the three most frequent pairs in that order. The mean reading gives half these values and does not match.

fig2c-reward-effects-fade¶

After repeated L1 the left-choice probability rises and converges near 0.75, and the effect of an earlier R0 fades under following L1s, so P(L|L1 L1 L1 L1) and P(L|R0 L1 L1 L1) do not differ (both 0.74).

The absence is judged on the Mann-Whitney test at p < 0.05 under O8 (a); O8 (b) is a variant.

In [15]:
for rd, wb in RD.items():
    tab = pd.DataFrame([cond(h, wb) for h in ["L1", "L1 L1", "L1 L1 L1", "L1 L1 L1 L1", "R0 L1 L1 L1"]])
    print(f"O7 ({rd})\n", tab.round(4).to_string())
    P = dict(zip(tab.history, tab.P))
    pa, pb, n1, n2 = mw_hist("L1 L1 L1 L1", "R0 L1 L1 L1", wb)
    print(f"  difference P(L|L1L1L1L1) - P(L|R0L1L1L1) = {P['L1 L1 L1 L1'] - P['R0 L1 L1 L1']:.4f};"
          f" Mann-Whitney O8 (a) p = {pa:.3f}; O8 (b) p = {pb:.3f}")
    print("  within tolerance (0.74 +- 0.074):", abs(P["L1 L1 L1 L1"] - 0.74) <= 0.074, abs(P["R0 L1 L1 L1"] - 0.74) <= 0.074,
          "| rise L1 < L1L1 < L1L1L1L1:", P["L1"] < P["L1 L1"] < P["L1 L1 L1 L1"],
          "| |P(L|L1x4) - 0.75| <= 0.075:", abs(P["L1 L1 L1 L1"] - 0.75) <= 0.075)
O7 (a)
        history     n       P   ci_lo   ci_hi
0           L1  9972  0.6775  0.6654  0.6895
1        L1 L1  4289  0.7179  0.7000  0.7354
2     L1 L1 L1  2149  0.7376  0.7127  0.7616
3  L1 L1 L1 L1  1164  0.7337  0.6996  0.7663
4  R0 L1 L1 L1   553  0.7360  0.6862  0.7825
  difference P(L|L1L1L1L1) - P(L|R0L1L1L1) = -0.0023; Mann-Whitney O8 (a) p = 0.919; O8 (b) p = 0.229
  within tolerance (0.74 +- 0.074): True True | rise L1 < L1L1 < L1L1L1L1: True | |P(L|L1x4) - 0.75| <= 0.075: True
O7 (b)
        history      n       P   ci_lo   ci_hi
0           L1  10135  0.6801  0.6681  0.6920
1        L1 L1   4464  0.7213  0.7039  0.7384
2     L1 L1 L1   2296  0.7443  0.7205  0.7674
3  L1 L1 L1 L1   1280  0.7430  0.7108  0.7737
4  R0 L1 L1 L1    572  0.7413  0.6926  0.7867
  difference P(L|L1L1L1L1) - P(L|R0L1L1L1) = 0.0017; Mann-Whitney O8 (a) p = 0.938; O8 (b) p = 0.240
  within tolerance (0.74 +- 0.074): True True | rise L1 < L1L1 < L1L1L1L1: True | |P(L|L1x4) - 0.75| <= 0.075: True

Result: reproduced. P(L|L1 L1 L1 L1) = 0.734 and 0.743 and P(L|R0 L1 L1 L1) = 0.736 and 0.741 under the two history readings; the Mann-Whitney test of O8 (a) gives p = 0.919 and 0.938 (paper 0.94), so it finds no difference (differences -0.002 and 0.002); O8 (b) gives p = 0.23 and 0.24. P(L) rises from 0.68 after L1 to 0.72 after L1 L1 and 0.73 to 0.74 after L1 L1 L1 L1, within 0.075 of 0.75.

fig2d-switching¶

After an unrewarded choice rats tended to choose the other action (switching), as seen in the alternating unrewarded sequences R0 L0 R0 L0 and L0 R0 L0 R0.

In [16]:
for rd, wb in RD.items():
    for seq in ["R0 L0 R0 L0", "L0 R0 L0 R0"]:
        tab = pd.DataFrame([cond(h, wb) for h in prefixes(seq)])
        tab["last"] = tab.history.str.split().str[-1]
        tab["switch_ok"] = np.where(tab["last"] == "L0", tab.P < 0.5, tab.P > 0.5)
        print(f"O7 ({rd}) {seq}\n", tab.round(4).to_string())
O7 (a) R0 L0 R0 L0
        history     n       P   ci_lo   ci_hi last  switch_ok
0           L0  9125  0.3862  0.3731  0.3994   L0       True
1        R0 L0  2987  0.3261  0.3042  0.3484   L0       True
2     L0 R0 L0  1211  0.3526  0.3177  0.3884   L0       True
3  R0 L0 R0 L0   506  0.3103  0.2589  0.3645   L0       True
O7 (a) L0 R0 L0 R0
        history     n       P   ci_lo   ci_hi last  switch_ok
0           R0  9319  0.6165  0.6035  0.6294   R0       True
1        L0 R0  3047  0.6511  0.6287  0.6732   R0       True
2     R0 L0 R0  1226  0.6509  0.6154  0.6855   R0       True
3  L0 R0 L0 R0   481  0.6965  0.6411  0.7488   R0       True
O7 (b) R0 L0 R0 L0
        history     n       P   ci_lo   ci_hi last  switch_ok
0           L0  9205  0.3875  0.3745  0.4006   L0       True
1        R0 L0  3007  0.3269  0.3051  0.3491   L0       True
2     L0 R0 L0  1216  0.3512  0.3164  0.3868   L0       True
3  R0 L0 R0 L0   508  0.3091  0.2578  0.3631   L0       True
O7 (b) L0 R0 L0 R0
        history     n       P   ci_lo   ci_hi last  switch_ok
0           R0  9396  0.6155  0.6025  0.6284   R0       True
1        L0 R0  3065  0.6522  0.6299  0.6742   R0       True
2     R0 L0 R0  1232  0.6502  0.6147  0.6847   R0       True
3  L0 R0 L0 R0   483  0.6957  0.6404  0.7479   R0       True

Result: reproduced. Under both history readings every prefix of R0 L0 R0 L0 and L0 R0 L0 R0 that ends in L0 gives P(L) of 0.31 to 0.39, and every one that ends in R0 gives 0.62 to 0.70. The 99% intervals of all eight exclude 0.5.

fig2e-persevering¶

After two or more unrewarded left choices the left-choice probability gradually rises, and P(L|L0 L0 L0) and P(L|L0 L0 L0 L0) are both above 0.5.

In [17]:
for rd, wb in RD.items():
    tab = pd.DataFrame([cond(h, wb) for h in prefixes("L0 L0 L0 L0")])
    P = dict(zip(tab.history, tab.P))
    print(f"O7 ({rd}) left sequence\n", tab.round(4).to_string())
    print("  rise L0L0 < L0L0L0 < L0L0L0L0:", P["L0 L0"] < P["L0 L0 L0"] < P["L0 L0 L0 L0"],
          "| both > 0.5:", P["L0 L0 L0"] > 0.5 and P["L0 L0 L0 L0"] > 0.5)
    tabr = pd.DataFrame([cond(h, wb) for h in prefixes("R0 R0 R0 R0")])
    tabr["P_right"] = 1 - tabr.P
    print(f"O7 ({rd}) mirrored sequence, P(R)\n", tabr[["history", "n", "P_right"]].round(4).to_string())
O7 (a) left sequence
        history     n       P   ci_lo   ci_hi
0           L0  9125  0.3862  0.3731  0.3994
1        L0 L0  2155  0.4636  0.4360  0.4913
2     L0 L0 L0   713  0.5750  0.5270  0.6222
3  L0 L0 L0 L0   321  0.6978  0.6298  0.7612
  rise L0L0 < L0L0L0 < L0L0L0L0: True | both > 0.5: True
O7 (a) mirrored sequence, P(R)
        history     n  P_right
0           R0  9319   0.3835
1        R0 R0  2040   0.4324
2     R0 R0 R0   552   0.4493
3  R0 R0 R0 R0   160   0.5062
O7 (b) left sequence
        history     n       P   ci_lo   ci_hi
0           L0  9205  0.3875  0.3745  0.4006
1        L0 L0  2197  0.4670  0.4397  0.4945
2     L0 L0 L0   735  0.5741  0.5269  0.6207
3  L0 L0 L0 L0   330  0.6970  0.6298  0.7596
  rise L0L0 < L0L0L0 < L0L0L0L0: True | both > 0.5: True
O7 (b) mirrored sequence, P(R)
        history     n  P_right
0           R0  9396   0.3845
1        R0 R0  2090   0.4344
2     R0 R0 R0   570   0.4491
3  R0 R0 R0 R0   167   0.5090

Result: reproduced. P(L) after L0 L0, L0 L0 L0 and L0 L0 L0 L0 is 0.46, 0.57 and 0.70 (histories within blocks) and 0.47, 0.57 and 0.70 (within sessions): it rises, and the last two exceed 0.5. The mirrored sequence also rises (P(R) 0.43, 0.45, 0.51), but P(R|R0 R0 R0) = 0.45 stays below 0.5.

fig3-lsq-switching and table1-lsq-parameters¶

Fitted by least squares to the six four-trial sequences of Fig. 2C and 2D, the local matching law and standard Q-learning cannot represent switching, while F-Q and DF-Q can; the averaged residual errors are 0.0102, 0.0073, 0.0010 and 0.0002.

The least-squares fits give the parameters of Table 1 (alpha1, alpha2, kappa1, kappa2, Q0) for each model.

Data: the prefix probabilities of L1 L1 L1 L1, R1 R1 R1 R1, R0 L1 L1 L1, L0 R1 R1 R1, R0 L0 R0 L0 and L0 R0 L0 R0 (24 points), under both history readings O7. Each model starts from QL = QR = Q0, applies the sequence and predicts P(L) after each prefix; parameters minimize the squared error (L-BFGS-B from a grid of starting points, a standard choice; bounds alpha in [0, 1], kappa1 in [0, 10], kappa2 in [-10, 10], Q0 in [0, 10]). Update forms O1 (a) and (b). Residual readings: (a) mean squared error over the 24 points; (b) over the 12 points of the three left-ending sequences with each mirror pair averaged. The models are symmetric in left and right, so both readings have the same optimum.

In [18]:
from scipy.optimize import minimize
import itertools
SEQ6 = ["L1 L1 L1 L1", "R1 R1 R1 R1", "R0 L1 L1 L1", "L0 R1 R1 R1", "R0 L0 R0 L0", "L0 R0 L0 R0"]
LSQ_MODELS = {"LM": ["alpha1", "Q0"], "Q": ["alpha1", "kappa1", "Q0"], "FQ": ["alpha1", "kappa1", "kappa2", "Q0"],
              "DFQ": ["alpha1", "alpha2", "kappa1", "kappa2", "Q0"]}
LSQ_BOUNDS = {"alpha1": (0, 1), "alpha2": (0, 1), "kappa1": (0, 10), "kappa2": (-10, 10), "Q0": (0, 10)}

def lsq_targets(wb):
    return np.array([[cond(" ".join(seq.split()[:i + 1]), wb)["P"] for i in range(4)] for seq in SEQ6])

def lsq_predict(model, x, form):
    p = dict(zip(LSQ_MODELS[model], x))
    a1 = p["alpha1"]; a2 = p.get("alpha2", a1 if model in ("FQ", "LM") else 0.0)
    k1 = p.get("kappa1", 1.0); k2 = p.get("kappa2", 0.0)
    out = np.zeros((6, 4))
    for i, seq in enumerate(SEQ6):
        ql = qr = p["Q0"]
        for j, e in enumerate(seq.split()):
            r = 1 if e[1] == "1" else 0
            if e[0] == "L":
                ql, qr = I.q_update(ql, qr, r, a1, a2, k1, k2, form)
            else:
                qr, ql = I.q_update(qr, ql, r, a1, a2, k1, k2, form)
            out[i, j] = I.p_left(ql, qr, model == "LM")
    return out

def lsq_fit(model, y, form):
    names = LSQ_MODELS[model]
    f = lambda x: float(((lsq_predict(model, x, form) - y) ** 2).sum())
    grids = {"alpha1": [0.1, 0.5, 0.9], "alpha2": [0.1, 0.5, 0.9], "kappa1": [0.5, 1.5, 3.0],
             "kappa2": [-1.0, 0.5, 1.5], "Q0": [0.05, 0.5, 1.0]}
    best = None
    for x0 in itertools.product(*[grids[n] for n in names]):
        r = minimize(f, x0, method="L-BFGS-B", bounds=[LSQ_BOUNDS[n] for n in names])
        if best is None or r.fun < best.fun:
            best = r
    return best.x

def mirror_avg(m):
    # rows (0,1), (2,3), (4,5) are mirror pairs: average P(L) of the left-ending one with 1 - P(L) of its mirror
    left = [0, 2, 4]; right = [1, 3, 5]
    return np.array([(m[l] + 1 - m[r]) / 2 for l, r in zip(left, right)])

def represents_switching(pred):
    # Fig. 3 reading: after each L0 of R0 L0 R0 L0 P(L) < 0.5 and after each R0 P(L) > 0.5
    seq = SEQ6[4].split()
    return all((pred[4, j] < 0.5) if seq[j] == "L0" else (pred[4, j] > 0.5) for j in range(4))

lsq = {}
t0 = time.time()
for rd, wb in RD.items():
    y = lsq_targets(wb)
    for form in [0, 1]:
        for model in ["LM", "Q", "FQ", "DFQ"]:
            x = lsq_fit(model, y, form)
            pred = lsq_predict(model, x, form)
            lsq[(rd, form, model)] = dict(x=dict(zip(LSQ_MODELS[model], x)), mse24=((pred - y) ** 2).mean(),
                                         mse12=((mirror_avg(pred) - mirror_avg(y)) ** 2).mean(),
                                         switching=represents_switching(pred), pred=pred)
print(f"fits in {time.time() - t0:.0f} s")
fits in 8 s
In [19]:
EXP_RES = {"LM": 0.0102, "Q": 0.0073, "FQ": 0.0010, "DFQ": 0.0002}
rows = []
for (rd, form, model), v in lsq.items():
    for rr in ["mse24", "mse12"]:
        rows.append(dict(O7=rd, O1="ab"[form], residual=rr, model=model, value=v[rr], expected=EXP_RES[model],
                         ok=abs(v[rr] - EXP_RES[model]) <= 0.1 * EXP_RES[model], switching=v["switching"]))
R3 = pd.DataFrame(rows)
piv = R3.pivot_table(index=["O7", "O1", "residual"], columns="model", values="value")[["LM", "Q", "FQ", "DFQ"]]
piv["order LM>Q>FQ>DFQ"] = (piv.LM > piv.Q) & (piv.Q > piv.FQ) & (piv.FQ > piv.DFQ)
piv["n within tol"] = R3.groupby(["O7", "O1", "residual"]).ok.sum()
print(piv.to_string(float_format=lambda v: f"{v:.5f}"))
print("\nrepresents switching (P(L) < 0.5 after each L0 and > 0.5 after each R0 of R0 L0 R0 L0):")
print(R3.drop_duplicates(["O7", "O1", "model"]).pivot_table(index=["O7", "O1"], columns="model", values="switching")[["LM", "Q", "FQ", "DFQ"]])
print("\nfitted P(L) after each prefix of R0 L0 R0 L0, O7 (b), O1 (a):")
print(pd.DataFrame({m: lsq[("b", 0, m)]["pred"][4] for m in ["LM", "Q", "FQ", "DFQ"]}, index=prefixes("R0 L0 R0 L0")[::-1] if False else ["R0", "R0 L0", "R0 L0 R0", "R0 L0 R0 L0"]).round(3))
model               LM       Q      FQ     DFQ  order LM>Q>FQ>DFQ  n within tol
O7 O1 residual                                                                 
a  a  mse12    0.01003 0.00706 0.00079 0.00013               True             2
      mse24    0.01018 0.00720 0.00094 0.00027               True             3
   b  mse12    0.01003 0.00706 0.00079 0.00013               True             2
      mse24    0.01018 0.00720 0.00094 0.00027               True             3
b  a  mse12    0.00993 0.00713 0.00089 0.00011               True             2
      mse24    0.01006 0.00727 0.00102 0.00025               True             3
   b  mse12    0.00993 0.00713 0.00089 0.00011               True             2
      mse24    0.01006 0.00727 0.00102 0.00025               True             3

represents switching (P(L) < 0.5 after each L0 and > 0.5 after each R0 of R0 L0 R0 L0):
model   LM    Q   FQ  DFQ
O7 O1                    
a  a   0.0  0.0  1.0  1.0
   b   0.0  0.0  1.0  1.0
b  a   0.0  0.0  1.0  1.0
   b   0.0  0.0  1.0  1.0

fitted P(L) after each prefix of R0 L0 R0 L0, O7 (b), O1 (a):
              LM      Q     FQ    DFQ
R0           0.5  0.596  0.649  0.621
R0 L0        0.5  0.500  0.356  0.343
R0 L0 R0     0.5  0.567  0.644  0.666
R0 L0 R0 L0  0.5  0.500  0.356  0.332

Result: partially reproduced. Under every reading the residuals fall in the stated order (local matching 0.0099 to 0.0102, standard Q 0.0071 to 0.0073, F-Q 0.00079 to 0.00102, DF-Q 0.00011 to 0.00027), F-Q and DF-Q represent switching and the local matching law and standard Q do not. The DF-Q residual is outside its tolerance (0.0002 ± 0.00002) under every reading, and F-Q is outside under the 12-point reading, so the values match in part (2 or 3 of 4).

In [20]:
T1 = {("Q", "alpha1"): 0.37, ("Q", "kappa1"): 2.37, ("Q", "Q0"): 1.00, ("FQ", "alpha1"): 0.96, ("FQ", "kappa1"): 0.99,
      ("FQ", "kappa2"): 0.64, ("FQ", "Q0"): 0.00, ("DFQ", "alpha1"): 0.52, ("DFQ", "alpha2"): 0.88,
      ("DFQ", "kappa1"): 1.18, ("DFQ", "kappa2"): 1.44, ("DFQ", "Q0"): 0.71, ("LM", "alpha1"): 0.05, ("LM", "Q0"): 0.07}
rows = []
for rd in RD:
    for form in [0, 1]:
        for (m, p), e in T1.items():
            v = lsq[(rd, form, m)]["x"][p]
            tol = 0.01 if e == 0 else 0.1 * e
            rows.append(dict(O7=rd, O1="ab"[form], model=m, param=p, fitted=v, expected=e, ok=abs(v - e) <= tol))
T1r = pd.DataFrame(rows)
print(T1r.pivot_table(index=["model", "param"], columns=["O7", "O1"], values="fitted").round(3))
print("\nvalues within tolerance (of 14):")
print(T1r.groupby(["O7", "O1"]).ok.sum())

# Residuals at the paper's Table 1 values next to the fitted optimum: a second optimum gives an equal or
# lower residual at the paper's values, a mismatch a higher one.
rows = []
for rd, wb in RD.items():
    y = lsq_targets(wb)
    for form in [0, 1]:
        for m in ["LM", "Q", "FQ", "DFQ"]:
            xp = [T1[(m, p)] for p in LSQ_MODELS[m]]
            pp = lsq_predict(m, xp, form)
            rows.append(dict(O7=rd, O1="ab"[form], model=m, mse24_paper_values=((pp - y) ** 2).mean(),
                             mse24_fitted=lsq[(rd, form, m)]["mse24"], switching_paper_values=represents_switching(pp)))
print("\nresidual (mean over the 24 points) at the paper's Table 1 values and at the fitted optimum:")
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda v: f"{v:.5f}"))
O7                a             b       
O1                a      b      a      b
model param                             
DFQ   Q0      0.704  0.704  0.754  0.754
      alpha1  0.540  0.540  0.492  0.492
      alpha2  0.883  0.883  0.853  0.853
      kappa1  1.145  0.618  1.195  0.588
      kappa2  1.375  0.742  1.552  0.764
FQ    Q0      1.000  1.000  0.500  0.050
      alpha1  0.974  0.974  0.967  0.967
      kappa1  0.972  0.947  0.988  0.955
      kappa2  0.629  0.613  0.635  0.614
LM    Q0      0.000  1.295  0.000  1.261
      alpha1  0.000  0.000  0.000  0.000
Q     Q0      1.242  1.242  1.287  1.287
      alpha1  0.320  0.320  0.302  0.302
      kappa1  2.707  0.866  2.850  0.862

values within tolerance (of 14):
O7  O1
a   a     8
    b     6
b   a     8
    b     6
Name: ok, dtype: int64

residual (mean over the 24 points) at the paper's Table 1 values and at the fitted optimum:
O7 O1 model  mse24_paper_values  mse24_fitted  switching_paper_values
 a  a    LM             0.01030       0.01018                   False
 a  a     Q             0.00722       0.00720                   False
 a  a    FQ             0.00094       0.00094                    True
 a  a   DFQ             0.00028       0.00027                    True
 a  b    LM             0.04406       0.01018                   False
 a  b     Q             0.03778       0.00720                   False
 a  b    FQ             0.00102       0.00094                    True
 a  b   DFQ             0.01800       0.00027                    True
 b  a    LM             0.01017       0.01006                   False
 b  a     Q             0.00729       0.00727                   False
 b  a    FQ             0.00102       0.00102                    True
 b  a   DFQ             0.00025       0.00025                    True
 b  b    LM             0.04328       0.01006                   False
 b  b     Q             0.03704       0.00727                   False
 b  b    FQ             0.00107       0.00102                    True
 b  b   DFQ             0.01758       0.00025                    True

Result: not reproduced. At most 8 of the 14 parameters are within tolerance (O1 a; 6 under O1 b), short of the 10 the criterion asks for partial reproduction. Under O1 (a) the F-Q alpha, kappa1 and kappa2 (0.97, 0.97 to 0.99, 0.63 to 0.64) and all five DF-Q values match; the standard Q fit (alpha 0.30 to 0.32, kappa1 2.71 to 2.85, Q0 1.24 to 1.29), the F-Q Q0 and the local matching law (alpha 0, predicting 0.5 throughout) do not. With alpha1 = alpha2, Q0 cancels from QL - QR, so the F-Q Q0 is not determined by the fit (fitted values 0.05 to 1.0). Under O1 (a) the paper's own Table 1 values give nearly the same residual as the fitted optimum (local matching law 0.0103 against 0.0102 under O7 a, its residual at alpha 0.05 and Q0 0.07; standard Q 0.00722 against 0.00720; F-Q equal; DF-Q 0.00028 against 0.00027), so the surface is flat and the paper's values are close to optimal here; under O1 (b) they are far worse (0.018 to 0.044 for all but F-Q).

Prediction of choices (Fig. 5, Tables 2 and 3)¶

Normalized likelihood (O2): the geometric mean of the per-trial likelihood of the observed choice over all test trials, and per session for the paired tests. Splits (O3): (a) alternate sessions in recording order over all rats (files sorted by subject and session; even positions train); (b) alternate sessions within each rat; (c) a seeded random half. Markov first trials (O6): (a) P(L) = 0.5 for the first d trials of a session; (b) the first 4 trials of every session left out of the score of every model. Constant models: maximum likelihood on the training sessions, Qi(1) = 0 (Methods), O4 (a) grid optimum (0.05 steps, 0.01 for the local matching law) and (b) continuous optimum. Time-varying models: particle filter with 5000 particles (supplemental Methods); sigma_alpha and sigma_kappa chosen on the training sessions from a grid that holds every value of Table 2 (sigma_alpha 0.0025, 0.005, 0.01, 0.02; sigma_kappa 0.05, 0.07, 0.10, 0.15), the search run with 1000 particles to fit the time limit, then the chosen sigmas run with 5000 particles. Drift bounds O5: (a) none; (b) alpha clipped to [0, 1].

The local matching law with Qi(1) = 0 is undefined: P(L) = QL / (QL + QR) is 0/0 on the first trial, and after the first reward of one side the model predicts that side with probability 1, so one choice of the other side gives the likelihood 0. The paper reports 0.508 with alpha = 0.01, which such a model cannot give. It is run here with Qi(1) = 0 (P(L) = 0.5 while QL + QR = 0, predictions floored at 1e-12), and, as an assumption, with Qi(1) = 0.1, 0.5 and 1.0 for this model only.

In [21]:
SPL = I.splits(seqs)
nch = np.array([len(s) for s in seqs])
for k, m in SPL.items():
    print(f"split ({k}): training {m.sum()} sessions, {nch[m].sum()} choice trials; test {(~m).sum()} sessions, {nch[~m].sum()} choice trials")
print("paper: training 19,986, test 19,186 choice trials")
SKIP = {"a": 0, "b": 4}   # O6

def sub(lst, mask):
    return [x for x, m in zip(lst, mask) if m]

# Markov models
markov = {}
for sk, m in SPL.items():
    tr, te = sub(seqs, m), sub(seqs, ~m)
    for d in [1, 2, 3, 4]:
        NL, NR = I.markov_counts(tr, d)
        pl = I.markov_predict(NL, NR, d, seqs)       # predictions for every session (test ones are scored)
        markov[(sk, d)] = [np.where(np.isnan(p), 0.5, p) for p in pl]

# Constant models
t0 = time.time()
const = {}
for sk, m in SPL.items():
    tr = sub(seqs, m)
    for form in [0, 1]:
        for model in ["Q", "FQ", "DFQ"]:
            fit = I.fit_constant(model, tr, form)
            for o4 in ["grid", "cont"]:
                const[(sk, form, model, o4, 0.0)] = dict(x=fit[o4], pl=I.predict_sessions(model, fit[o4], seqs, form))
        for q0 in [0.0, 0.1, 0.5, 1.0]:
            fit = I.fit_constant("LM", tr, form, q0)
            for o4 in ["grid", "cont"]:
                const[(sk, form, "LM", o4, q0)] = dict(x=fit[o4], pl=I.predict_sessions("LM", fit[o4], seqs, form, q0))
print(f"constant fits: {time.time() - t0:.0f} s")
split (a): training 35 sessions, 19986 choice trials; test 35 sessions, 19189 choice trials
split (b): training 37 sessions, 21070 choice trials; test 33 sessions, 18105 choice trials
split (c): training 35 sessions, 20233 choice trials; test 35 sessions, 18942 choice trials
paper: training 19,986, test 19,186 choice trials
constant fits: 32 s
In [22]:
# 5000-particle runs of the filter over all 70 sessions, kept for reuse.
pf_cache = {}
def pf_run(model, sa, sk_, form, clip):
    key = (model, sa, sk_, form, clip)
    if key not in pf_cache:
        pf_cache[key] = I.particle_filter(seqs, model, sa, sk_, form, clip, npart=I.N_PARTICLES, seed=2)
    return pf_cache[key]
In [23]:
# Time-varying models: sigma search. The filter of a session does not depend on the other sessions
# (each restarts from the prior with its own seed), so one run over all 70 sessions per sigma pair scores
# the training sessions of every split.
SA = [0.0025, 0.005, 0.01, 0.02]
SKs = [0.05, 0.07, 0.10, 0.15]
t0 = time.time()
search = {}
for model in ["Q", "FQ", "DFQ"]:
    for form in [0, 1]:
        for clip in [0, 1]:
            for sa in SA:
                for sk_ in SKs:
                    pl, _, _ = I.particle_filter(seqs, model, sa, sk_, form, clip, npart=1000, seed=1)
                    lz = [I.loglik(p, s.a.values) for p, s in zip(pl, seqs)]
                    search[(model, form, clip, sa, sk_)] = lz
print(f"sigma search: {time.time() - t0:.0f} s")
best_sigma = {}
for model in ["Q", "FQ", "DFQ"]:
    for form in [0, 1]:
        for clip in [0, 1]:
            for spk, m in SPL.items():
                sc = {(sa, sk_): I.norm_lik(np.concatenate(sub(search[(model, form, clip, sa, sk_)], m)))
                      for sa in SA for sk_ in SKs}
                best_sigma[(spk, form, clip, model)] = max(sc, key=sc.get)
                if spk == "a" and form == 0 and clip == 0:
                    print(model, "training normalized likelihood over the sigma grid, split (a), O1 (a), O5 (a):")
                    print(pd.Series(sc).unstack().round(5))

t0 = time.time()
variable = {}
for (spk, form, clip, model), (sa, sk_) in best_sigma.items():
    variable[(spk, form, clip, model)] = dict(sigma=(sa, sk_), pl=pf_run(model, sa, sk_, form, clip)[0])
print(f"5000-particle runs at the chosen sigmas: {len(pf_cache)} runs, {time.time() - t0:.0f} s")
sigma search: 258 s
Q training normalized likelihood over the sigma grid, split (a), O1 (a), O5 (a):
           0.05     0.07     0.10     0.15
0.0025  0.52603  0.52604  0.52633  0.52784
0.0050  0.52638  0.52633  0.52643  0.52605
0.0100  0.52652  0.52675  0.52699  0.52669
0.0200  0.52867  0.52894  0.52668  0.52806
FQ training normalized likelihood over the sigma grid, split (a), O1 (a), O5 (a):
           0.05     0.07     0.10     0.15
0.0025  0.53478  0.53481  0.53476  0.53383
0.0050  0.53484  0.53490  0.53466  0.53366
0.0100  0.53495  0.53545  0.53482  0.53403
0.0200  0.53527  0.53538  0.53481  0.53389
DFQ training normalized likelihood over the sigma grid, split (a), O1 (a), O5 (a):
           0.05     0.07     0.10     0.15
0.0025  0.53429  0.53451  0.53429  0.53300
0.0050  0.53407  0.53452  0.53404  0.53335
0.0100  0.53468  0.53494  0.53451  0.53354
0.0200  0.53482  0.53461  0.53416  0.53326
5000-particle runs at the chosen sigmas: 23 runs, 152 s
In [24]:
# Scores of every model under every reading, on the test sessions of each split.
def scores(pls, mask, skip):
    te_pl, te_s = sub(pls, ~mask), sub(seqs, ~mask)
    return I.pooled_normlik(te_pl, te_s, skip), I.session_normlik(te_pl, te_s, skip)

MODELS10 = ["Markov1", "Markov2", "Markov3", "Markov4", "LM", "Q const", "FQ const", "DFQ const", "Q var", "FQ var", "DFQ var"]
def model_pls(spk, form, clip, o4, q0_lm):
    d = {f"Markov{k}": markov[(spk, k)] for k in [1, 2, 3, 4]}
    d["LM"] = const[(spk, form, "LM", o4, q0_lm)]["pl"]
    for m in ["Q", "FQ", "DFQ"]:
        d[f"{m} const"] = const[(spk, form, m, o4, 0.0)]["pl"]
        d[f"{m} var"] = variable[(spk, form, clip, m)]["pl"]
    return d

rows, per_session, lm_session = [], {}, {}
for spk, mask in SPL.items():
    for form in [0, 1]:
        for clip in [0, 1]:
            for o4 in ["grid", "cont"]:
                for o6, skip in SKIP.items():
                    for q0 in [0.5, 0.1, 1.0, 0.0]:
                        pls = model_pls(spk, form, clip, o4, q0)
                        row = dict(O3=spk, O1="ab"[form], O5="ab"[clip], O4=o4, O6=o6, LM_Q0=q0)
                        for name, pl in pls.items():
                            pooled, sess = scores(pl, mask, skip)
                            row[name] = pooled
                            if q0 == 0.5:
                                per_session[(spk, form, clip, o4, o6, name)] = sess
                            if name == "LM":
                                lm_session[(spk, form, clip, o4, o6, q0)] = sess
                        rows.append(row)
NLK = pd.DataFrame(rows)
KEYS = ["O3", "O1", "O5", "O4", "O6", "LM_Q0"]
main = NLK[(NLK.O3 == "a") & (NLK.O1 == "a") & (NLK.O5 == "a") & (NLK.O4 == "grid") & (NLK.O6 == "a") & (NLK.LM_Q0 == 0.5)]
main0 = NLK[(NLK.O3 == "a") & (NLK.O1 == "a") & (NLK.O5 == "a") & (NLK.O4 == "grid") & (NLK.O6 == "a") & (NLK.LM_Q0 == 0.0)]
tab = main[MODELS10].T.round(4).rename(columns=lambda c: "normalized likelihood")
tab.loc["LM"] = np.nan
tab.loc["LM, Qi(1) = 0 (as the Methods and the criterion give it)"] = main0.LM.values[0].round(4)
tab.loc["LM, Qi(1) = 0.5 (an assumption, not the paper's method)"] = main.LM.values[0].round(4)
print("Main reading (O3 a, O1 a, O5 a, O4 grid, O6 a):")
print(tab.drop(index="LM"))
Main reading (O3 a, O1 a, O5 a, O4 grid, O6 a):
                                                    normalized likelihood
Markov1                                                            0.5283
Markov2                                                            0.5318
Markov3                                                            0.5336
Markov4                                                            0.5319
Q const                                                            0.5266
FQ const                                                           0.5306
DFQ const                                                          0.5295
Q var                                                              0.5304
FQ var                                                             0.5374
DFQ var                                                            0.5369
LM, Qi(1) = 0 (as the Methods and the criterion...                 0.5000
LM, Qi(1) = 0.5 (an assumption, not the paper's...                 0.5064

Checks on the filter and the sigma search (added after verification round 1)¶

Three checks, each on the main split (O3 a). (1) Seed noise: the 5000-particle runs of F-Q and DF-Q (variable) at the chosen sigmas are repeated with five more seeds on the test sessions, under every reading of O1 and O5, and the six runs are also averaged per trial (a filter of 30,000 particles in six independent groups), the least noisy estimate here. (2) The sigma search is repeated with 5000 particles on a wider grid (sigma_alpha up to 0.08, sigma_kappa from 0.025) on the training sessions, under O1 (a) and both readings of O5; the chosen sigmas are then scored on the test sessions. (3) The test sessions are scored at the paper's Table 2 sigmas, under every split and reading of O1 and O5.

In [25]:
SIG2_PAPER = {"Q": (0.005, 0.10), "FQ": (0.005, 0.07), "DFQ": (0.010, 0.07)}
def main_scores(clip, model, form=0):
    return NLK[(NLK.O3 == "a") & (NLK.O1 == "ab"[form]) & (NLK.O5 == "ab"[clip]) & (NLK.O4 == "grid") & (NLK.O6 == "a")][f"{model} var"].values[0]

# (1) Seed noise of the 5000-particle filter on the test sessions of split (a).
SEEDS = [2, 3, 4, 5, 6, 7]          # seed 2 is the run used above
te_a = sub(seqs, ~SPL["a"])
t0 = time.time()
seedrun = {}   # (form, clip, model) -> list over seeds of per-session P_L on the test sessions
for form in [0, 1]:
    for clip in [0, 1]:
        for model in ["FQ", "DFQ"]:
            sa, sk_ = variable[("a", form, clip, model)]["sigma"]
            seedrun[(form, clip, model)] = [sub(variable[("a", form, clip, model)]["pl"], ~SPL["a"])] + \
                [I.particle_filter(te_a, model, sa, sk_, form, clip, npart=I.N_PARTICLES, seed=sd)[0] for sd in SEEDS[1:]]
print(f"seed runs: {time.time() - t0:.0f} s")

def sess_scores(pls, skip=0):
    return I.session_normlik(pls, te_a, skip)

rows = []
for (form, clip, model), runs in seedrun.items():
    sc = np.array([sess_scores(pl) for pl in runs])                    # seeds x sessions
    avg = [np.mean([r[i] for r in runs], axis=0) for i in range(len(te_a))]
    rows.append(dict(O1="ab"[form], O5="ab"[clip], model=model,
                     pooled_by_seed=" ".join(f"{I.pooled_normlik(pl, te_a):.4f}" for pl in runs),
                     pooled_seed_avg=I.pooled_normlik(avg, te_a), per_session_sd_over_seeds_median=np.median(sc.std(axis=0, ddof=1))))
print(pd.DataFrame(rows).to_string(index=False, float_format=lambda v: f"{v:.5f}"))
seed runs: 141 s
O1 O5 model                            pooled_by_seed  pooled_seed_avg  per_session_sd_over_seeds_median
 a  a    FQ 0.5374 0.5374 0.5375 0.5374 0.5375 0.5374          0.53752                           0.00021
 a  a   DFQ 0.5369 0.5370 0.5370 0.5370 0.5370 0.5370          0.53710                           0.00029
 a  b    FQ 0.5379 0.5379 0.5380 0.5379 0.5379 0.5380          0.53805                           0.00020
 a  b   DFQ 0.5375 0.5375 0.5374 0.5374 0.5376 0.5375          0.53757                           0.00022
 b  a    FQ 0.5343 0.5342 0.5342 0.5343 0.5342 0.5342          0.53435                           0.00025
 b  a   DFQ 0.5341 0.5341 0.5341 0.5340 0.5343 0.5341          0.53432                           0.00031
 b  b    FQ 0.5346 0.5345 0.5346 0.5346 0.5347 0.5346          0.53468                           0.00029
 b  b   DFQ 0.5348 0.5347 0.5346 0.5347 0.5347 0.5347          0.53481                           0.00026
In [26]:
# (2) Sigma search with 5000 particles on a wider grid, training sessions of split (a), O1 (a).
SA5 = [0.0025, 0.005, 0.01, 0.02, 0.04, 0.08]
SK5 = [0.025, 0.05, 0.07, 0.10, 0.15]
tr_a = sub(seqs, SPL["a"])
t0 = time.time()
search5, best5, collapsed5 = {}, {}, {}
for clip in [0, 1]:
    for model in ["Q", "FQ", "DFQ"]:
        for sa in SA5:
            for sk_ in SK5:
                pl = I.particle_filter(tr_a, model, sa, sk_, 0, clip, npart=I.N_PARTICLES, seed=1)[0]
                search5[(clip, model, sa, sk_)] = I.pooled_normlik(pl, tr_a)
                collapsed5[(clip, model, sa, sk_)] = int((I.session_normlik(pl, tr_a) < 0.45).sum())
        sc = {(sa, sk_): search5[(clip, model, sa, sk_)] for sa in SA5 for sk_ in SK5}
        best5[(clip, model)] = max(sc, key=sc.get)
        print(f"{model}, O5 ({'ab'[clip]}): training normalized likelihood, 5000 particles (rows sigma_alpha, columns sigma_kappa); "
              f"best {best5[(clip, model)]}, 1000-particle search chose {variable[('a', 0, clip, model)]['sigma']}, Table 2 {SIG2_PAPER[model]}")
        print(pd.Series(sc).unstack().round(5).to_string())
        bad = {k[2:]: v for k, v in collapsed5.items() if k[:2] == (clip, model) and v}
        if bad:
            print("  grid points with a training session scored under 0.45 (filter collapse):", bad)
print(f"5000-particle sigma search: {time.time() - t0:.0f} s")
rows = []
for (clip, model), (sa, sk_) in best5.items():
    pl = pf_run(model, sa, sk_, 0, clip)[0]
    rows.append(dict(O5="ab"[clip], model=model, sigma=(sa, sk_), test_pooled=I.pooled_normlik(sub(pl, ~SPL["a"]), te_a),
                     test_pooled_1000_search=main_scores(clip, model)))
S5 = pd.DataFrame(rows)
print("\ntest scores (split a, O1 a, O4 grid, O6 a) at the sigmas of the 5000-particle search, against those of the 1000-particle search:")
print(S5.to_string(index=False, float_format=lambda v: f"{v:.4f}"))
Q, O5 (a): training normalized likelihood, 5000 particles (rows sigma_alpha, columns sigma_kappa); best (0.02, 0.07), 1000-particle search chose (0.02, 0.07), Table 2 (0.005, 0.1)
          0.025    0.050    0.070    0.100    0.150
0.0025  0.52616  0.52615  0.52635  0.52646  0.52615
0.0050  0.52629  0.52661  0.52667  0.52664  0.52663
0.0100  0.52666  0.52692  0.52904  0.52861  0.52818
0.0200  0.52873  0.52901  0.52914  0.39847  0.52841
0.0400  0.52841  0.52845  0.52844  0.52826  0.52765
0.0800  0.52618  0.52643  0.52636  0.52610  0.52542
  grid points with a training session scored under 0.45 (filter collapse): {(0.02, 0.1): 1}
FQ, O5 (a): training normalized likelihood, 5000 particles (rows sigma_alpha, columns sigma_kappa); best (0.02, 0.025), 1000-particle search chose (0.01, 0.07), Table 2 (0.005, 0.07)
          0.025    0.050    0.070    0.100    0.150
0.0025  0.53437  0.53545  0.53531  0.53491  0.53377
0.0050  0.53498  0.53534  0.53528  0.53486  0.53391
0.0100  0.53486  0.53539  0.53558  0.53503  0.53404
0.0200  0.53576  0.53570  0.53552  0.53504  0.53392
0.0400  0.53516  0.53537  0.53506  0.53442  0.53326
0.0800  0.53348  0.53317  0.53295  0.53227  0.53086
DFQ, O5 (a): training normalized likelihood, 5000 particles (rows sigma_alpha, columns sigma_kappa); best (0.01, 0.025), 1000-particle search chose (0.01, 0.07), Table 2 (0.01, 0.07)
          0.025    0.050    0.070    0.100    0.150
0.0025  0.53429  0.53521  0.53499  0.53461  0.53356
0.0050  0.53398  0.53490  0.53520  0.53451  0.53360
0.0100  0.53534  0.53498  0.53492  0.53459  0.53365
0.0200  0.53514  0.53508  0.53484  0.53426  0.53329
0.0400  0.53424  0.53408  0.53376  0.53314  0.53185
0.0800  0.53067  0.53066  0.53013  0.52941  0.52793
Q, O5 (b): training normalized likelihood, 5000 particles (rows sigma_alpha, columns sigma_kappa); best (0.04, 0.15), 1000-particle search chose (0.02, 0.15), Table 2 (0.005, 0.1)
          0.025    0.050    0.070    0.100    0.150
0.0025  0.52617  0.52633  0.52639  0.52651  0.52639
0.0050  0.52649  0.52683  0.52674  0.52692  0.52678
0.0100  0.52662  0.52694  0.52684  0.52741  0.52703
0.0200  0.52675  0.52712  0.52720  0.52749  0.52725
0.0400  0.52673  0.52720  0.52736  0.52763  0.52778
0.0800  0.52695  0.52751  0.52754  0.52774  0.52763
FQ, O5 (b): training normalized likelihood, 5000 particles (rows sigma_alpha, columns sigma_kappa); best (0.08, 0.07), 1000-particle search chose (0.02, 0.07), Table 2 (0.005, 0.07)
          0.025    0.050    0.070    0.100    0.150
0.0025  0.53483  0.53539  0.53520  0.53493  0.53395
0.0050  0.53505  0.53542  0.53543  0.53529  0.53415
0.0100  0.53506  0.53558  0.53574  0.53537  0.53440
0.0200  0.53537  0.53608  0.53604  0.53585  0.53477
0.0400  0.53547  0.53618  0.53623  0.53596  0.53509
0.0800  0.53532  0.53602  0.53624  0.53600  0.53508
DFQ, O5 (b): training normalized likelihood, 5000 particles (rows sigma_alpha, columns sigma_kappa); best (0.04, 0.05), 1000-particle search chose (0.02, 0.07), Table 2 (0.01, 0.07)
          0.025    0.050    0.070    0.100    0.150
0.0025  0.53411  0.53467  0.53500  0.53454  0.53359
0.0050  0.53430  0.53481  0.53513  0.53483  0.53375
0.0100  0.53504  0.53530  0.53541  0.53485  0.53399
0.0200  0.53490  0.53551  0.53534  0.53505  0.53426
0.0400  0.53481  0.53565  0.53562  0.53516  0.53434
0.0800  0.53455  0.53512  0.53542  0.53508  0.53427
5000-particle sigma search: 616 s
test scores (split a, O1 a, O4 grid, O6 a) at the sigmas of the 5000-particle search, against those of the 1000-particle search:
O5 model         sigma  test_pooled  test_pooled_1000_search
 a     Q  (0.02, 0.07)       0.5304                   0.5304
 a    FQ (0.02, 0.025)       0.5372                   0.5374
 a   DFQ (0.01, 0.025)       0.5372                   0.5369
 b     Q  (0.04, 0.15)       0.5303                   0.5302
 b    FQ  (0.08, 0.07)       0.5374                   0.5379
 b   DFQ  (0.04, 0.05)       0.5373                   0.5375
In [27]:
# (3) Test scores at the paper's Table 2 sigmas, every split, O1 and O5 (O6 a).
rows = []
for spk, mask in SPL.items():
    for form in [0, 1]:
        for clip in [0, 1]:
            row = dict(O3=spk, O1="ab"[form], O5="ab"[clip])
            for m in ["Q", "FQ", "DFQ"]:
                pl = pf_run(m, *SIG2_PAPER[m], form, clip)[0]
                row[f"{m} var (Table 2 sigmas)"] = I.pooled_normlik(sub(pl, ~mask), sub(seqs, ~mask))
                row[f"{m} var (chosen sigmas)"] = NLK[(NLK.O3 == spk) & (NLK.O1 == "ab"[form]) & (NLK.O5 == "ab"[clip]) & (NLK.O6 == "a")][f"{m} var"].values[0]
            rows.append(row)
TS2 = pd.DataFrame(rows)
print(TS2.to_string(index=False, float_format=lambda v: f"{v:.4f}"))
print("paper: Q 0.5304, F-Q 0.5375, DF-Q 0.5368")
O3 O1 O5  Q var (Table 2 sigmas)  Q var (chosen sigmas)  FQ var (Table 2 sigmas)  FQ var (chosen sigmas)  DFQ var (Table 2 sigmas)  DFQ var (chosen sigmas)
 a  a  a                  0.5297                 0.5304                   0.5376                  0.5374                    0.5369                   0.5369
 a  a  b                  0.5299                 0.5302                   0.5378                  0.5379                    0.5374                   0.5375
 a  b  a                  0.5267                 0.5287                   0.5334                  0.5343                    0.5336                   0.5341
 a  b  b                  0.5268                 0.5291                   0.5336                  0.5346                    0.5338                   0.5348
 b  a  a                  0.5306                 0.5294                   0.5394                  0.5395                    0.5393                   0.5393
 b  a  b                  0.5294                 0.5296                   0.5397                  0.5399                    0.5395                   0.5395
 b  b  a                  0.5267                 0.5302                   0.5364                  0.5377                    0.5365                   0.5373
 b  b  b                  0.5270                 0.5305                   0.5365                  0.5377                    0.5366                   0.5378
 c  a  a                  0.5298                 0.5308                   0.5383                  0.5386                    0.5380                   0.5380
 c  a  b                  0.5286                 0.5287                   0.5385                  0.5389                    0.5384                   0.5384
 c  b  a                  0.5254                 0.5288                   0.5352                  0.5363                    0.5353                   0.5361
 c  b  b                  0.5258                 0.5291                   0.5352                  0.5365                    0.5356                   0.5364
paper: Q 0.5304, F-Q 0.5375, DF-Q 0.5368

fig5-markov-accuracy¶

The first- to fourth-order Markov models reach normalized likelihoods of 0.528, 0.532, 0.534 and 0.532 on test data; the third order is best and the fourth is lower, presumably by overfitting its 256 parameters.

In [28]:
mk = NLK.drop_duplicates(["O3", "O6"])[["O3", "O6", "Markov1", "Markov2", "Markov3", "Markov4"]].copy()
expm = [0.528, 0.532, 0.534, 0.532]
mk["all within 0.005"] = np.all(np.abs(mk[["Markov1", "Markov2", "Markov3", "Markov4"]].values - expm) <= 0.005, axis=1)
mk["order 3 highest"] = mk[["Markov1", "Markov2", "Markov3", "Markov4"]].values.argmax(axis=1) == 2
mk["order 4 below 3"] = mk.Markov4 < mk.Markov3
print(mk.round(4).to_string(index=False))
O3 O6  Markov1  Markov2  Markov3  Markov4  all within 0.005  order 3 highest  order 4 below 3
 a  a   0.5283   0.5318   0.5336   0.5319              True             True             True
 a  b   0.5285   0.5319   0.5337   0.5322              True             True             True
 b  a   0.5288   0.5332   0.5350   0.5345              True             True             True
 b  b   0.5289   0.5333   0.5352   0.5348              True             True             True
 c  a   0.5267   0.5308   0.5332   0.5334              True            False            False
 c  b   0.5268   0.5310   0.5333   0.5337              True            False            False

Result: blocked (methods underspecified). Under the split by alternate sessions (O3 a), whose training set holds exactly the paper's 19,986 choice trials, the four orders give 0.5283, 0.5318, 0.5336 and 0.5319 (paper 0.528, 0.532, 0.534, 0.532), with order 3 highest; the same holds for O3 (b). Under the random split (O3 c) all values are within tolerance but order 4 (0.5334) exceeds order 3 (0.5332). The criterion asks for the result under every reading of the split, and the readings disagree.

fig5-constant-models¶

With constant parameters, standard Q, F-Q and DF-Q (0.527, 0.531, 0.531) predict much better than the local matching law (0.508), but worse than the first- or second-order Markov models.

In [29]:
cm = NLK.drop_duplicates(["O3", "O1", "O4", "O6", "LM_Q0"])[["O3", "O1", "O4", "O6", "LM_Q0", "Q const", "FQ const", "DFQ const", "LM", "Markov1", "Markov2"]].copy()
expc = [0.527, 0.531, 0.531, 0.508]
cm["Q models in tol"] = np.all(np.abs(cm[["Q const", "FQ const", "DFQ const"]].values - expc[:3]) <= 0.005, axis=1)
cm["LM in tol"] = (cm.LM - 0.508).abs() <= 0.005
cm["Q models > LM"] = cm[["Q const", "FQ const", "DFQ const"]].min(axis=1) > cm.LM
cm["below Markov1"] = cm[["Q const", "FQ const", "DFQ const"]].max(axis=1) < cm.Markov1
print(cm.round(4).to_string(index=False))
print("\nFitted constant parameters (alpha1, [alpha2], kappa1, [kappa2]) by split and O1, grid optimum:")
for spk in SPL:
    for form in [0, 1]:
        print(f"  O3 ({spk}) O1 ({'ab'[form]}):", {m: np.round(const[(spk, form, m, "grid", 0.0)]["x"], 3).tolist() for m in ["Q", "FQ", "DFQ"]},
              "LM alpha (Qi(1)=0, 0.1, 0.5, 1):", [np.round(const[(spk, form, "LM", "grid", q)]["x"], 3).tolist() for q in [0.0, 0.1, 0.5, 1.0]])
O3 O1   O4 O6  LM_Q0  Q const  FQ const  DFQ const     LM  Markov1  Markov2  Q models in tol  LM in tol  Q models > LM  below Markov1
 a  a grid  a    0.5   0.5266    0.5306     0.5295 0.5064   0.5283   0.5318             True       True           True          False
 a  a grid  a    0.1   0.5266    0.5306     0.5295 0.5058   0.5283   0.5318             True       True           True          False
 a  a grid  a    1.0   0.5266    0.5306     0.5295 0.5062   0.5283   0.5318             True       True           True          False
 a  a grid  a    0.0   0.5266    0.5306     0.5295 0.5000   0.5283   0.5318             True      False           True          False
 a  a grid  b    0.5   0.5267    0.5307     0.5296 0.5064   0.5285   0.5319             True       True           True          False
 a  a grid  b    0.1   0.5267    0.5307     0.5296 0.5058   0.5285   0.5319             True       True           True          False
 a  a grid  b    1.0   0.5267    0.5307     0.5296 0.5062   0.5285   0.5319             True       True           True          False
 a  a grid  b    0.0   0.5267    0.5307     0.5296 0.5000   0.5285   0.5319             True      False           True          False
 a  a cont  a    0.5   0.5266    0.5306     0.5296 0.5068   0.5283   0.5318             True       True           True          False
 a  a cont  a    0.1   0.5266    0.5306     0.5296 0.5058   0.5283   0.5318             True       True           True          False
 a  a cont  a    1.0   0.5266    0.5306     0.5296 0.5067   0.5283   0.5318             True       True           True          False
 a  a cont  a    0.0   0.5266    0.5306     0.5296 0.5000   0.5283   0.5318             True      False           True          False
 a  a cont  b    0.5   0.5267    0.5307     0.5297 0.5068   0.5285   0.5319             True       True           True          False
 a  a cont  b    0.1   0.5267    0.5307     0.5297 0.5058   0.5285   0.5319             True       True           True          False
 a  a cont  b    1.0   0.5267    0.5307     0.5297 0.5068   0.5285   0.5319             True       True           True          False
 a  a cont  b    0.0   0.5267    0.5307     0.5297 0.5000   0.5285   0.5319             True      False           True          False
 a  b grid  a    0.5   0.5266    0.5307     0.5296 0.4994   0.5283   0.5318             True      False           True          False
 a  b grid  a    0.1   0.5266    0.5307     0.5296 0.4943   0.5283   0.5318             True      False           True          False
 a  b grid  a    1.0   0.5266    0.5307     0.5296 0.5013   0.5283   0.5318             True      False           True          False
 a  b grid  a    0.0   0.5266    0.5307     0.5296 0.4152   0.5283   0.5318             True      False           True          False
 a  b grid  b    0.5   0.5267    0.5308     0.5297 0.4993   0.5285   0.5319             True      False           True          False
 a  b grid  b    0.1   0.5267    0.5308     0.5297 0.4946   0.5285   0.5319             True      False           True          False
 a  b grid  b    1.0   0.5267    0.5308     0.5297 0.5012   0.5285   0.5319             True      False           True          False
 a  b grid  b    0.0   0.5267    0.5308     0.5297 0.4270   0.5285   0.5319             True      False           True          False
 a  b cont  a    0.5   0.5266    0.5306     0.5296 0.5001   0.5283   0.5318             True      False           True          False
 a  b cont  a    0.1   0.5266    0.5306     0.5296 0.4951   0.5283   0.5318             True      False           True          False
 a  b cont  a    1.0   0.5266    0.5306     0.5296 0.5020   0.5283   0.5318             True      False           True          False
 a  b cont  a    0.0   0.5266    0.5306     0.5296 0.4161   0.5283   0.5318             True      False           True          False
 a  b cont  b    0.5   0.5267    0.5307     0.5297 0.5001   0.5285   0.5319             True      False           True          False
 a  b cont  b    0.1   0.5267    0.5307     0.5297 0.4954   0.5285   0.5319             True      False           True          False
 a  b cont  b    1.0   0.5267    0.5307     0.5297 0.5019   0.5285   0.5319             True      False           True          False
 a  b cont  b    0.0   0.5267    0.5307     0.5297 0.4279   0.5285   0.5319             True      False           True          False
 b  a grid  a    0.5   0.5259    0.5306     0.5303 0.5057   0.5288   0.5332             True       True           True          False
 b  a grid  a    0.1   0.5259    0.5306     0.5303 0.5042   0.5288   0.5332             True       True           True          False
 b  a grid  a    1.0   0.5259    0.5306     0.5303 0.5058   0.5288   0.5332             True       True           True          False
 b  a grid  a    0.0   0.5259    0.5306     0.5303 0.5000   0.5288   0.5332             True      False           True          False
 b  a grid  b    0.5   0.5260    0.5307     0.5304 0.5058   0.5289   0.5333             True       True           True          False
 b  a grid  b    0.1   0.5260    0.5307     0.5304 0.5042   0.5289   0.5333             True       True           True          False
 b  a grid  b    1.0   0.5260    0.5307     0.5304 0.5059   0.5289   0.5333             True       True           True          False
 b  a grid  b    0.0   0.5260    0.5307     0.5304 0.5000   0.5289   0.5333             True      False           True          False
 b  a cont  a    0.5   0.5260    0.5305     0.5305 0.5057   0.5288   0.5332             True       True           True          False
 b  a cont  a    0.1   0.5260    0.5305     0.5305 0.5039   0.5288   0.5332             True       True           True          False
 b  a cont  a    1.0   0.5260    0.5305     0.5305 0.5058   0.5288   0.5332             True       True           True          False
 b  a cont  a    0.0   0.5260    0.5305     0.5305 0.5000   0.5288   0.5332             True      False           True          False
 b  a cont  b    0.5   0.5261    0.5306     0.5306 0.5057   0.5289   0.5333             True       True           True          False
 b  a cont  b    0.1   0.5261    0.5306     0.5306 0.5039   0.5289   0.5333             True       True           True          False
 b  a cont  b    1.0   0.5261    0.5306     0.5306 0.5059   0.5289   0.5333             True       True           True          False
 b  a cont  b    0.0   0.5261    0.5306     0.5306 0.5000   0.5289   0.5333             True      False           True          False
 b  b grid  a    0.5   0.5259    0.5302     0.5302 0.4959   0.5288   0.5332             True      False           True          False
 b  b grid  a    0.1   0.5259    0.5302     0.5302 0.4908   0.5288   0.5332             True      False           True          False
 b  b grid  a    1.0   0.5259    0.5302     0.5302 0.4981   0.5288   0.5332             True      False           True          False
 b  b grid  a    0.0   0.5259    0.5302     0.5302 0.4122   0.5288   0.5332             True      False           True          False
 b  b grid  b    0.5   0.5260    0.5304     0.5304 0.4959   0.5289   0.5333             True      False           True          False
 b  b grid  b    0.1   0.5260    0.5304     0.5304 0.4912   0.5289   0.5333             True      False           True          False
 b  b grid  b    1.0   0.5260    0.5304     0.5304 0.4980   0.5289   0.5333             True      False           True          False
 b  b grid  b    0.0   0.5260    0.5304     0.5304 0.4248   0.5289   0.5333             True      False           True          False
 b  b cont  a    0.5   0.5260    0.5305     0.5305 0.4965   0.5288   0.5332             True      False           True          False
 b  b cont  a    0.1   0.5260    0.5305     0.5305 0.4912   0.5288   0.5332             True      False           True          False
 b  b cont  a    1.0   0.5260    0.5305     0.5305 0.4986   0.5288   0.5332             True      False           True          False
 b  b cont  a    0.0   0.5260    0.5305     0.5305 0.4125   0.5288   0.5332             True      False           True          False
 b  b cont  b    0.5   0.5261    0.5306     0.5306 0.4964   0.5289   0.5333             True      False           True          False
 b  b cont  b    0.1   0.5261    0.5306     0.5306 0.4917   0.5289   0.5333             True      False           True          False
 b  b cont  b    1.0   0.5261    0.5306     0.5306 0.4985   0.5289   0.5333             True      False           True          False
 b  b cont  b    0.0   0.5261    0.5306     0.5306 0.4250   0.5289   0.5333             True      False           True          False
 c  a grid  a    0.5   0.5241    0.5280     0.5283 0.5071   0.5267   0.5308             True       True           True          False
 c  a grid  a    0.1   0.5241    0.5280     0.5283 0.5064   0.5267   0.5308             True       True           True          False
 c  a grid  a    1.0   0.5241    0.5280     0.5283 0.5069   0.5267   0.5308             True       True           True          False
 c  a grid  a    0.0   0.5241    0.5280     0.5283 0.5000   0.5267   0.5308             True      False           True          False
 c  a grid  b    0.5   0.5240    0.5281     0.5284 0.5071   0.5268   0.5310             True       True           True          False
 c  a grid  b    0.1   0.5240    0.5281     0.5284 0.5064   0.5268   0.5310             True       True           True          False
 c  a grid  b    1.0   0.5240    0.5281     0.5284 0.5070   0.5268   0.5310             True       True           True          False
 c  a grid  b    0.0   0.5240    0.5281     0.5284 0.5000   0.5268   0.5310             True      False           True          False
 c  a cont  a    0.5   0.5240    0.5281     0.5283 0.5075   0.5267   0.5308             True       True           True          False
 c  a cont  a    0.1   0.5240    0.5281     0.5283 0.5065   0.5267   0.5308             True       True           True          False
 c  a cont  a    1.0   0.5240    0.5281     0.5283 0.5074   0.5267   0.5308             True       True           True          False
 c  a cont  a    0.0   0.5240    0.5281     0.5283 0.5000   0.5267   0.5308             True      False           True          False
 c  a cont  b    0.5   0.5240    0.5282     0.5284 0.5075   0.5268   0.5310             True       True           True          False
 c  a cont  b    0.1   0.5240    0.5282     0.5284 0.5064   0.5268   0.5310             True       True           True          False
 c  a cont  b    1.0   0.5240    0.5282     0.5284 0.5075   0.5268   0.5310             True       True           True          False
 c  a cont  b    0.0   0.5240    0.5282     0.5284 0.5000   0.5268   0.5310             True      False           True          False
 c  b grid  a    0.5   0.5240    0.5282     0.5284 0.4993   0.5267   0.5308             True      False           True          False
 c  b grid  a    0.1   0.5240    0.5282     0.5284 0.4942   0.5267   0.5308             True      False           True          False
 c  b grid  a    1.0   0.5240    0.5282     0.5284 0.5014   0.5267   0.5308             True      False           True          False
 c  b grid  a    0.0   0.5240    0.5282     0.5284 0.4190   0.5267   0.5308             True      False           True          False
 c  b grid  b    0.5   0.5240    0.5283     0.5284 0.4992   0.5268   0.5310             True      False           True          False
 c  b grid  b    0.1   0.5240    0.5283     0.5284 0.4944   0.5268   0.5310             True      False           True          False
 c  b grid  b    1.0   0.5240    0.5283     0.5284 0.5012   0.5268   0.5310             True      False           True          False
 c  b grid  b    0.0   0.5240    0.5283     0.5284 0.4292   0.5268   0.5310             True      False           True          False
 c  b cont  a    0.5   0.5240    0.5281     0.5283 0.5001   0.5267   0.5308             True      False           True          False
 c  b cont  a    0.1   0.5240    0.5281     0.5283 0.4951   0.5267   0.5308             True      False           True          False
 c  b cont  a    1.0   0.5240    0.5281     0.5283 0.5020   0.5267   0.5308             True      False           True          False
 c  b cont  a    0.0   0.5240    0.5281     0.5283 0.4199   0.5267   0.5308             True      False           True          False
 c  b cont  b    0.5   0.5240    0.5282     0.5284 0.4999   0.5268   0.5310             True      False           True          False
 c  b cont  b    0.1   0.5240    0.5282     0.5284 0.4952   0.5268   0.5310             True      False           True          False
 c  b cont  b    1.0   0.5240    0.5282     0.5284 0.5019   0.5268   0.5310             True      False           True          False
 c  b cont  b    0.0   0.5240    0.5282     0.5284 0.4301   0.5268   0.5310             True      False           True          False

Fitted constant parameters (alpha1, [alpha2], kappa1, [kappa2]) by split and O1, grid optimum:
  O3 (a) O1 (a): {'Q': [0.5, 1.2], 'FQ': [0.6, 1.15, 0.55], 'DFQ': [0.45, 0.05, 2.25, -1.1]} LM alpha (Qi(1)=0, 0.1, 0.5, 1): [[0.0], [0.01], [0.01], [0.01]]
  O3 (a) O1 (b): {'Q': [0.5, 0.6], 'FQ': [0.6, 0.7, 0.35], 'DFQ': [0.45, 0.05, 0.95, -0.45]} LM alpha (Qi(1)=0, 0.1, 0.5, 1): [[0.01], [0.01], [0.01], [0.01]]
  O3 (b) O1 (a): {'Q': [0.35, 1.3], 'FQ': [0.5, 1.25, 0.6], 'DFQ': [0.45, 0.3, 1.3, 0.4]} LM alpha (Qi(1)=0, 0.1, 0.5, 1): [[0.0], [0.01], [0.01], [0.01]]
  O3 (b) O1 (b): {'Q': [0.35, 0.45], 'FQ': [0.45, 0.6, 0.25], 'DFQ': [0.45, 0.3, 0.6, 0.15]} LM alpha (Qi(1)=0, 0.1, 0.5, 1): [[0.02], [0.02], [0.01], [0.01]]
  O3 (c) O1 (a): {'Q': [0.45, 1.3], 'FQ': [0.55, 1.25, 0.7], 'DFQ': [0.6, 0.5, 1.2, 0.6]} LM alpha (Qi(1)=0, 0.1, 0.5, 1): [[0.0], [0.01], [0.01], [0.01]]
  O3 (c) O1 (b): {'Q': [0.45, 0.6], 'FQ': [0.6, 0.7, 0.4], 'DFQ': [0.6, 0.5, 0.7, 0.35]} LM alpha (Qi(1)=0, 0.1, 0.5, 1): [[0.01], [0.01], [0.01], [0.01]]

Result: blocked (methods underspecified). Under every reading standard Q, F-Q and DF-Q give 0.5240 to 0.5267, 0.5280 to 0.5308 and 0.5283 to 0.5306, within 0.005 of 0.527, 0.531 and 0.531, and exceed the local matching law. The local matching law with Qi(1) = 0, as the Methods and the criterion give it, is degenerate (0/0 on the first trial, probability 1 after the first reward): it scores 0.500 under O1 (a), its optimum being alpha 0, a constant 0.5, and less under O1 (b), out of tolerance. Only with a non-zero initial value, which the paper does not give, does it reach 0.504 to 0.508 (Qi(1) = 0.1, 0.5 or 1.0, O1 a). The paper's 0.508 cannot come from the model as specified, so the procedure is not fixed. As the paper's own numbers do, F-Q and DF-Q (constant) exceed the first-order Markov model (0.5306 against 0.5283 in the main reading).

fig5-variable-models-best¶

With time-varying parameters standard Q, F-Q and DF-Q improve to 0.5304, 0.5375 and 0.5368, and F-Q with time-varying parameters predicts best of all models.

In [30]:
vm = NLK[NLK.LM_Q0 == 0.5].copy()
expv = [0.5304, 0.5375, 0.5368]
vm["in tol"] = np.all(np.abs(vm[["Q var", "FQ var", "DFQ var"]].values - expv) <= 0.005, axis=1)
vm["each > const"] = (vm["Q var"] > vm["Q const"]) & (vm["FQ var"] > vm["FQ const"]) & (vm["DFQ var"] > vm["DFQ const"])
vm["best model"] = vm[MODELS10].idxmax(axis=1)
print(vm[["O3", "O1", "O5", "O4", "O6", "Q var", "FQ var", "DFQ var", "Q const", "FQ const", "DFQ const", "Markov3", "in tol", "each > const", "best model"]].round(4).to_string(index=False))
print("\nreadings:", len(vm), "| all in tolerance:", int(vm["in tol"].sum()), "| each variable > its constant:", int(vm["each > const"].sum()),
      "| best model counts:", vm["best model"].value_counts().to_dict())
print("chosen sigmas (sigma_alpha, sigma_kappa):")
print(pd.Series({k: v["sigma"] for k, v in variable.items()}).unstack(level=3))
O3 O1 O5   O4 O6  Q var  FQ var  DFQ var  Q const  FQ const  DFQ const  Markov3  in tol  each > const best model
 a  a  a grid  a 0.5304  0.5374   0.5369   0.5266    0.5306     0.5295   0.5336    True          True     FQ var
 a  a  a grid  b 0.5305  0.5377   0.5371   0.5267    0.5307     0.5296   0.5337    True          True     FQ var
 a  a  a cont  a 0.5304  0.5374   0.5369   0.5266    0.5306     0.5296   0.5336    True          True     FQ var
 a  a  a cont  b 0.5305  0.5377   0.5371   0.5267    0.5307     0.5297   0.5337    True          True     FQ var
 a  a  b grid  a 0.5302  0.5379   0.5375   0.5266    0.5306     0.5295   0.5336    True          True     FQ var
 a  a  b grid  b 0.5303  0.5382   0.5378   0.5267    0.5307     0.5296   0.5337    True          True     FQ var
 a  a  b cont  a 0.5302  0.5379   0.5375   0.5266    0.5306     0.5296   0.5336    True          True     FQ var
 a  a  b cont  b 0.5303  0.5382   0.5378   0.5267    0.5307     0.5297   0.5337    True          True     FQ var
 a  b  a grid  a 0.5287  0.5343   0.5341   0.5266    0.5307     0.5296   0.5336    True          True     FQ var
 a  b  a grid  b 0.5289  0.5348   0.5346   0.5267    0.5308     0.5297   0.5337    True          True     FQ var
 a  b  a cont  a 0.5287  0.5343   0.5341   0.5266    0.5306     0.5296   0.5336    True          True     FQ var
 a  b  a cont  b 0.5289  0.5348   0.5346   0.5267    0.5307     0.5297   0.5337    True          True     FQ var
 a  b  b grid  a 0.5291  0.5346   0.5348   0.5266    0.5307     0.5296   0.5336    True          True    DFQ var
 a  b  b grid  b 0.5293  0.5351   0.5353   0.5267    0.5308     0.5297   0.5337    True          True    DFQ var
 a  b  b cont  a 0.5291  0.5346   0.5348   0.5266    0.5306     0.5296   0.5336    True          True    DFQ var
 a  b  b cont  b 0.5293  0.5351   0.5353   0.5267    0.5307     0.5297   0.5337    True          True    DFQ var
 b  a  a grid  a 0.5294  0.5395   0.5393   0.5259    0.5306     0.5303   0.5350    True          True     FQ var
 b  a  a grid  b 0.5295  0.5397   0.5396   0.5260    0.5307     0.5304   0.5352    True          True     FQ var
 b  a  a cont  a 0.5294  0.5395   0.5393   0.5260    0.5305     0.5305   0.5350    True          True     FQ var
 b  a  a cont  b 0.5295  0.5397   0.5396   0.5261    0.5306     0.5306   0.5352    True          True     FQ var
 b  a  b grid  a 0.5296  0.5399   0.5395   0.5259    0.5306     0.5303   0.5350    True          True     FQ var
 b  a  b grid  b 0.5297  0.5402   0.5397   0.5260    0.5307     0.5304   0.5352    True          True     FQ var
 b  a  b cont  a 0.5296  0.5399   0.5395   0.5260    0.5305     0.5305   0.5350    True          True     FQ var
 b  a  b cont  b 0.5297  0.5402   0.5397   0.5261    0.5306     0.5306   0.5352    True          True     FQ var
 b  b  a grid  a 0.5302  0.5377   0.5373   0.5259    0.5302     0.5302   0.5350    True          True     FQ var
 b  b  a grid  b 0.5305  0.5382   0.5378   0.5260    0.5304     0.5304   0.5352    True          True     FQ var
 b  b  a cont  a 0.5302  0.5377   0.5373   0.5260    0.5305     0.5305   0.5350    True          True     FQ var
 b  b  a cont  b 0.5305  0.5382   0.5378   0.5261    0.5306     0.5306   0.5352    True          True     FQ var
 b  b  b grid  a 0.5305  0.5377   0.5378   0.5259    0.5302     0.5302   0.5350    True          True    DFQ var
 b  b  b grid  b 0.5308  0.5382   0.5383   0.5260    0.5304     0.5304   0.5352    True          True    DFQ var
 b  b  b cont  a 0.5305  0.5377   0.5378   0.5260    0.5305     0.5305   0.5350    True          True    DFQ var
 b  b  b cont  b 0.5308  0.5382   0.5383   0.5261    0.5306     0.5306   0.5352    True          True    DFQ var
 c  a  a grid  a 0.5308  0.5386   0.5380   0.5241    0.5280     0.5283   0.5332    True          True     FQ var
 c  a  a grid  b 0.5308  0.5388   0.5382   0.5240    0.5281     0.5284   0.5333    True          True     FQ var
 c  a  a cont  a 0.5308  0.5386   0.5380   0.5240    0.5281     0.5283   0.5332    True          True     FQ var
 c  a  a cont  b 0.5308  0.5388   0.5382   0.5240    0.5282     0.5284   0.5333    True          True     FQ var
 c  a  b grid  a 0.5287  0.5389   0.5384   0.5241    0.5280     0.5283   0.5332    True          True     FQ var
 c  a  b grid  b 0.5287  0.5392   0.5387   0.5240    0.5281     0.5284   0.5333    True          True     FQ var
 c  a  b cont  a 0.5287  0.5389   0.5384   0.5240    0.5281     0.5283   0.5332    True          True     FQ var
 c  a  b cont  b 0.5287  0.5392   0.5387   0.5240    0.5282     0.5284   0.5333    True          True     FQ var
 c  b  a grid  a 0.5288  0.5363   0.5361   0.5240    0.5282     0.5284   0.5332    True          True     FQ var
 c  b  a grid  b 0.5289  0.5368   0.5366   0.5240    0.5283     0.5284   0.5333    True          True     FQ var
 c  b  a cont  a 0.5288  0.5363   0.5361   0.5240    0.5281     0.5283   0.5332    True          True     FQ var
 c  b  a cont  b 0.5289  0.5368   0.5366   0.5240    0.5282     0.5284   0.5333    True          True     FQ var
 c  b  b grid  a 0.5291  0.5365   0.5364   0.5240    0.5282     0.5284   0.5332    True          True     FQ var
 c  b  b grid  b 0.5292  0.5370   0.5369   0.5240    0.5283     0.5284   0.5333    True          True     FQ var
 c  b  b cont  a 0.5291  0.5365   0.5364   0.5240    0.5281     0.5283   0.5332    True          True     FQ var
 c  b  b cont  b 0.5292  0.5370   0.5369   0.5240    0.5282     0.5284   0.5333    True          True     FQ var

readings: 48 | all in tolerance: 48 | each variable > its constant: 48 | best model counts: {'FQ var': 40, 'DFQ var': 8}
chosen sigmas (sigma_alpha, sigma_kappa):
                  DFQ            FQ             Q
a 0 0    (0.01, 0.07)  (0.01, 0.07)  (0.02, 0.07)
    1    (0.02, 0.07)  (0.02, 0.07)  (0.02, 0.15)
  1 0    (0.02, 0.05)  (0.02, 0.05)  (0.02, 0.05)
    1    (0.02, 0.05)  (0.02, 0.05)  (0.02, 0.05)
b 0 0    (0.01, 0.05)  (0.01, 0.07)  (0.01, 0.07)
    1    (0.02, 0.07)  (0.02, 0.07)  (0.02, 0.07)
  1 0   (0.005, 0.05)  (0.02, 0.05)  (0.02, 0.05)
    1    (0.02, 0.05)  (0.01, 0.05)  (0.02, 0.05)
c 0 0    (0.01, 0.05)  (0.01, 0.05)  (0.02, 0.05)
    1    (0.02, 0.05)  (0.02, 0.05)  (0.02, 0.07)
  1 0  (0.0025, 0.05)  (0.01, 0.05)  (0.02, 0.05)
    1    (0.02, 0.05)  (0.02, 0.05)  (0.02, 0.05)

Result: partially reproduced. Under all 48 readings the three time-varying models are within tolerance (main reading 0.5304, 0.5374 and 0.5369, paper 0.5304, 0.5375 and 0.5368) and each exceeds its constant version. F-Q (variable) has the highest normalized likelihood in 40 readings; in 8 of the 12 readings with the update O1 (b) and clipped drift O5 (b), those on splits (a) and (b), DF-Q (variable) is highest, by at most 0.0002, so F-Q is not first under every reading; on split (c) F-Q leads under these readings too. On split (a), the six-seed average of the filter (check 1) keeps the same order: F-Q leads DF-Q under O1 (a) (0.53752 against 0.53710 under O5 a, 0.53805 against 0.53757 under O5 b), and DF-Q leads under O1 (b), O5 (b) (0.53481 against 0.53468). At the sigmas of the 5000-particle search (check 2) F-Q and DF-Q give 0.5372 and 0.5372 (O5 a) and 0.5374 and 0.5373 (O5 b); at the paper's Table 2 sigmas (check 3) 0.5376 and 0.5369 in the main reading. The outcome reads the criterion's partial rule as holding when, under every reading, F-Q or DF-Q (variable) is highest with the values in tolerance, although in 40 readings F-Q is first, which alone would be reproduced. The claims file's general rule blocks a claim whose readings give different outcomes; this reading of the partial rule is an assumption (attempt record).

fig5-fq-dfq-beat-all-models and fig5-fq-dfq-no-difference¶

Per test session, the F-Q and DF-Q models with time-varying parameters predict significantly better than every other model, including the third-order Markov model.

The F-Q and DF-Q models with time-varying parameters do not differ in prediction accuracy (p = 0.067), so F-Q, with fewer parameters, is regarded as the better model.

Paired Wilcoxon signed-rank tests of per-session normalized likelihoods over the 35 test sessions, two-sided and one-sided (greater) for the first claim; two-sided (one-sided shown) for the second.

In [31]:
OTHERS = ["Q var", "Q const", "FQ const", "DFQ const", "LM", "Markov1", "Markov2", "Markov3", "Markov4"]
rows = []
for (spk, form, clip, o4, o6, name), v in per_session.items():
    if name not in ("FQ var", "DFQ var"):
        continue
    for other in OTHERS:
        w = per_session[(spk, form, clip, o4, o6, other)]
        d = v - w
        p2 = ss.wilcoxon(v, w, alternative="two-sided").pvalue
        p1 = ss.wilcoxon(v, w, alternative="greater").pvalue
        rows.append(dict(O3=spk, O1="ab"[form], O5="ab"[clip], O4=o4, O6=o6, model=name, other=other,
                         median_diff=np.median(d), n_better=int((d > 0).sum()), p_two=p2, p_one=p1))
WX = pd.DataFrame(rows)
WX["need"] = np.where(WX.other == "Markov3", 0.05, 0.01)
for side in ["p_two", "p_one"]:
    WX["ok_" + side] = (WX[side] < WX.need) & (WX.median_diff > 0)
mainw = WX[(WX.O3 == "a") & (WX.O1 == "a") & (WX.O5 == "a") & (WX.O4 == "grid") & (WX.O6 == "a")]
print("main reading:\n", mainw[["model", "other", "median_diff", "n_better", "p_two", "p_one", "need"]].to_string(index=False, float_format=lambda v: f"{v:.4g}"))
g = WX.groupby(["O3", "O1", "O5", "O4", "O6"])
summ = pd.DataFrame({"all 18 two-sided": g.ok_p_two.all(), "all 18 one-sided": g.ok_p_one.all(),
                     "n ok two-sided": g.ok_p_two.sum(), "n ok one-sided": g.ok_p_one.sum(),
                     "partial: all p<0.05, median>0 (two-sided)": g.apply(lambda x: ((x.p_two < 0.05) & (x.median_diff > 0)).all()),
                     "partial: all p<0.05, median>0 (one-sided)": g.apply(lambda x: ((x.p_one < 0.05) & (x.median_diff > 0)).all())})
print(summ.to_string())
print("failing comparisons, all readings (two-sided):")
print(WX[~WX.ok_p_two].groupby(["model", "other"]).size())

# The local matching law under each initial value (Qi(1) = 0 is the Methods' and the criterion's).
rows = []
for (spk, form, clip, o4, o6, q0), w in lm_session.items():
    if o4 != "grid" or o6 != "a":
        continue
    for name in ["FQ var", "DFQ var"]:
        v = per_session[(spk, form, clip, o4, o6, name)]
        rows.append(dict(O3=spk, O1="ab"[form], O5="ab"[clip], LM_Qi1=q0, model=name, median_diff=np.median(v - w),
                         p_two=ss.wilcoxon(v, w).pvalue, p_one=ss.wilcoxon(v, w, alternative="greater").pvalue))
LMW = pd.DataFrame(rows)
print("\nagainst the local matching law, by its initial value (O4 grid, O6 a): largest p over splits, O1 and O5")
print(LMW.groupby(["LM_Qi1", "model"]).agg(min_median_diff=("median_diff", "min"), max_p_two=("p_two", "max"), max_p_one=("p_one", "max")).to_string(float_format=lambda v: f"{v:.3g}"))

# Main reading with the seed-averaged filter (six seeds, check 1 above) for F-Q and DF-Q (variable).
rows = []
for name, model in [("FQ var", "FQ"), ("DFQ var", "DFQ")]:
    runs = seedrun[(0, 0, model)]
    v_avg = sess_scores([np.mean([r[i] for r in runs], axis=0) for i in range(len(te_a))])
    for other in OTHERS:
        w = per_session[("a", 0, 0, "grid", "a", other)]
        ps = [ss.wilcoxon(sess_scores(r), w).pvalue for r in runs]
        rows.append(dict(model=name, other=other, median_diff_seed_avg=np.median(v_avg - w), p_two_seed_avg=ss.wilcoxon(v_avg, w).pvalue,
                         p_one_seed_avg=ss.wilcoxon(v_avg, w, alternative="greater").pvalue,
                         p_two_min_over_seeds=min(ps), p_two_max_over_seeds=max(ps)))
SW = pd.DataFrame(rows)
SW["need"] = np.where(SW.other == "Markov3", 0.05, 0.01)
print("\nmain reading (O3 a, O1 a, O5 a, O4 grid, O6 a), F-Q and DF-Q from the six-seed average and per seed:")
print(SW.to_string(index=False, float_format=lambda v: f"{v:.4g}"))
main reading:
   model     other  median_diff  n_better     p_two     p_one  need
 FQ var     Q var     0.001129        21  0.007022  0.003511  0.01
 FQ var   Q const     0.009114        27 4.563e-06 2.282e-06  0.01
 FQ var  FQ const     0.003656        22  0.001338  0.000669  0.01
 FQ var DFQ const     0.002395        19   0.03562   0.01781  0.01
 FQ var        LM       0.0284        35 5.821e-11  2.91e-11  0.01
 FQ var   Markov1     0.005852        30 3.255e-06 1.627e-06  0.01
 FQ var   Markov2     0.004464        27 0.0001392 6.962e-05  0.01
 FQ var   Markov3     0.003986        25  0.006654  0.003327  0.05
 FQ var   Markov4     0.004339        29 4.986e-05 2.493e-05  0.01
DFQ var     Q var    0.0008211        20   0.03001     0.015  0.01
DFQ var   Q const     0.008221        27 1.454e-05 7.272e-06  0.01
DFQ var  FQ const     0.001855        24  0.003803  0.001902  0.01
DFQ var DFQ const     0.001454        19   0.07262   0.03631  0.01
DFQ var        LM      0.02681        34 1.164e-10 5.821e-11  0.01
DFQ var   Markov1     0.005432        31 2.298e-06 1.149e-06  0.01
DFQ var   Markov2     0.003941        26 0.0003554 0.0001777  0.01
DFQ var   Markov3     0.002914        23   0.01368  0.006841  0.05
DFQ var   Markov4     0.003705        26  0.000243 0.0001215  0.01
                  all 18 two-sided  all 18 one-sided  n ok two-sided  n ok one-sided  partial: all p<0.05, median>0 (two-sided)  partial: all p<0.05, median>0 (one-sided)
O3 O1 O5 O4   O6                                                                                                                                                          
a  a  a  cont a              False             False              15              15                                      False                                       True
              b              False             False              15              15                                      False                                       True
         grid a              False             False              15              15                                      False                                       True
              b              False             False              15              15                                      False                                       True
      b  cont a              False             False              16              17                                       True                                       True
              b              False             False              16              17                                       True                                       True
         grid a              False             False              16              17                                       True                                       True
              b              False             False              16              17                                       True                                       True
   b  a  cont a              False             False               4               6                                      False                                      False
              b              False             False               6               6                                      False                                      False
         grid a              False             False               4               6                                      False                                      False
              b              False             False               6               6                                      False                                      False
      b  cont a              False             False               5               6                                      False                                      False
              b              False             False               6               7                                      False                                      False
         grid a              False             False               6               6                                      False                                      False
              b              False             False               6               7                                      False                                      False
b  a  a  cont a               True              True              18              18                                       True                                       True
              b              False              True              17              18                                       True                                       True
         grid a               True              True              18              18                                       True                                       True
              b              False              True              17              18                                       True                                       True
      b  cont a              False              True              17              18                                      False                                       True
              b              False              True              17              18                                       True                                       True
         grid a              False              True              16              18                                      False                                       True
              b              False              True              17              18                                       True                                       True
   b  a  cont a              False             False               8               8                                      False                                      False
              b              False             False               8               8                                      False                                      False
         grid a              False             False               8               8                                      False                                      False
              b              False             False               8               8                                      False                                      False
      b  cont a              False             False               8               8                                      False                                      False
              b              False             False               8               8                                      False                                      False
         grid a              False             False               8               8                                      False                                      False
              b              False             False               8               8                                      False                                      False
c  a  a  cont a              False             False              15              16                                      False                                       True
              b              False             False              16              16                                       True                                       True
         grid a              False             False              15              16                                      False                                       True
              b              False             False              16              16                                       True                                       True
      b  cont a              False             False              17              17                                       True                                       True
              b              False             False              17              17                                       True                                       True
         grid a              False             False              17              17                                       True                                       True
              b              False             False              17              17                                       True                                       True
   b  a  cont a              False             False               8               8                                      False                                      False
              b              False             False               8               8                                      False                                      False
         grid a              False             False               8               8                                      False                                      False
              b              False             False               8               8                                      False                                      False
      b  cont a              False             False               8               8                                      False                                      False
              b              False             False               8               8                                      False                                      False
         grid a              False             False               8               8                                      False                                      False
              b              False             False               8               8                                      False                                      False
failing comparisons, all readings (two-sided):
model    other    
DFQ var  DFQ const    33
         FQ const     24
         Markov2      24
         Markov3      28
         Markov4      36
         Q const       2
         Q var        12
FQ var   DFQ const    32
         FQ const     24
         Markov2      24
         Markov3      24
         Markov4      28
         Q const       3
         Q var         8
dtype: int64

against the local matching law, by its initial value (O4 grid, O6 a): largest p over splits, O1 and O5
                min_median_diff  max_p_two  max_p_one
LM_Qi1 model                                         
0.0    DFQ var           0.0314   2.33e-10   1.16e-10
       FQ var            0.0316   2.33e-10   1.16e-10
0.1    DFQ var           0.0275   2.33e-10   1.16e-10
       FQ var            0.0281   2.33e-10   1.16e-10
0.5    DFQ var           0.0266   2.33e-10   1.16e-10
       FQ var            0.0277   2.33e-10   1.16e-10
1.0    DFQ var           0.0262   2.33e-10   1.16e-10
       FQ var            0.0266   2.33e-10   1.16e-10
main reading (O3 a, O1 a, O5 a, O4 grid, O6 a), F-Q and DF-Q from the six-seed average and per seed:
  model     other  median_diff_seed_avg  p_two_seed_avg  p_one_seed_avg  p_two_min_over_seeds  p_two_max_over_seeds  need
 FQ var     Q var              0.001441        0.005968        0.002984              0.005649              0.009625  0.01
 FQ var   Q const              0.009076       4.563e-06       2.282e-06             4.563e-06             6.335e-06  0.01
 FQ var  FQ const               0.00313       0.0008382       0.0004191              0.001027              0.001338  0.01
 FQ var DFQ const              0.002533         0.03414         0.01707               0.03562               0.04383  0.01
 FQ var        LM               0.02838       5.821e-11        2.91e-11             5.821e-11             5.821e-11  0.01
 FQ var   Markov1               0.00544       1.604e-06       8.018e-07             1.419e-06             3.255e-06  0.01
 FQ var   Markov2                0.0045       0.0001392       6.962e-05             0.0001392             0.0002834  0.01
 FQ var   Markov3              0.003915        0.005968        0.002984              0.005968              0.008678  0.05
 FQ var   Markov4              0.004288       4.161e-05        2.08e-05             4.986e-05             0.0001181  0.01
DFQ var     Q var              0.001144          0.0263         0.01315               0.02749               0.04037  0.01
DFQ var   Q const              0.008301       1.188e-05       5.941e-06             1.073e-05             1.454e-05  0.01
DFQ var  FQ const              0.001914        0.002667        0.001334              0.002511              0.003803  0.01
DFQ var DFQ const               0.00136         0.07262         0.03631               0.07262               0.09022  0.01
DFQ var        LM               0.02678       1.164e-10       5.821e-11             1.164e-10             1.164e-10  0.01
DFQ var   Markov1              0.005827        1.81e-06       9.051e-07             1.604e-06             4.082e-06  0.01
DFQ var   Markov2              0.004098       0.0002834       0.0001417             0.0002625             0.0004122  0.01
DFQ var   Markov3              0.002933        0.008678        0.004339               0.01013               0.01508  0.05
DFQ var   Markov4              0.003974       0.0001283       6.414e-05             0.0001181             0.0002834  0.01

Result: blocked (methods underspecified). In the main reading (O3 a, O1 a, O5 a), 15 of the 18 comparisons meet the paper's levels. F-Q (variable) does not beat DF-Q (constant) at p < 0.01 (p = 0.036), and DF-Q (variable) does not beat standard Q (variable) (p = 0.030) or DF-Q (constant) (p = 0.073, so not even p < 0.05). Both beat the third-order Markov model (p = 0.0067 and 0.014). With the six-seed average of the filter these p are 0.034, 0.026 and 0.073, and over the six seeds 0.036 to 0.044, 0.027 to 0.040 and 0.073 to 0.090, so filter noise does not change them. Among the 48 readings, all 18 comparisons pass two-sided in 2 (split b, O1 a, O5 a) and one-sided in 8; the partial condition (all p < 0.05, medians higher) holds in some readings and not in others, and under O1 (b) only 4 to 8 of 18 pass. The readings give different outcomes. The local matching law is beaten at p < 1e-9 under every initial value.

In [32]:
rows = []
for (spk, form, clip, o4, o6, name), v in per_session.items():
    if name != "FQ var" or o6 != "a":
        continue
    w = per_session[(spk, form, clip, o4, o6, "DFQ var")]
    rows.append(dict(O3=spk, O1="ab"[form], O5="ab"[clip], O4=o4, median_diff_FQ_minus_DFQ=np.median(v - w),
                     n_FQ_better=int((v > w).sum()), p_two=ss.wilcoxon(v, w).pvalue,
                     p_one_FQ_greater=ss.wilcoxon(v, w, alternative="greater").pvalue,
                     p_one_DFQ_greater=ss.wilcoxon(v, w, alternative="less").pvalue))
ND = pd.DataFrame(rows).drop_duplicates(["O3", "O1", "O5"])  # O4 does not affect the variable models
ND["difference found (two-sided p < 0.05)"] = ND.p_two < 0.05
print(ND.drop(columns="O4").to_string(index=False, float_format=lambda v: f"{v:.4g}"))

# Seed noise (check 1): the test for each of the six seeds, and on the six-seed average, split (a), O6 a.
rows = []
for form in [0, 1]:
    for clip in [0, 1]:
        fq, dfq = seedrun[(form, clip, "FQ")], seedrun[(form, clip, "DFQ")]
        for i, sd in enumerate(SEEDS):
            v, w = sess_scores(fq[i]), sess_scores(dfq[i])
            rows.append(dict(O1="ab"[form], O5="ab"[clip], seed=sd, median_diff=np.median(v - w), n_FQ_better=int((v > w).sum()),
                             p_two=ss.wilcoxon(v, w).pvalue))
        v = sess_scores([np.mean([r[i] for r in fq], axis=0) for i in range(len(te_a))])
        w = sess_scores([np.mean([r[i] for r in dfq], axis=0) for i in range(len(te_a))])
        rows.append(dict(O1="ab"[form], O5="ab"[clip], seed="average of six", median_diff=np.median(v - w), n_FQ_better=int((v > w).sum()),
                         p_two=ss.wilcoxon(v, w).pvalue))
SN = pd.DataFrame(rows)
print("\nF-Q against DF-Q (variable), split (a), by seed:")
print(SN.to_string(index=False, float_format=lambda v: f"{v:.4g}"))
print("seeds finding a difference (p < 0.05):", SN[SN.seed != "average of six"].groupby(["O1", "O5"]).p_two.apply(lambda p: int((p < 0.05).sum())).to_dict())
O3 O1 O5  median_diff_FQ_minus_DFQ  n_FQ_better    p_two  p_one_FQ_greater  p_one_DFQ_greater  difference found (two-sided p < 0.05)
 a  a  a                 0.0006403           27 0.008235          0.004117             0.9961                                   True
 a  a  b                 0.0006759           24  0.01302          0.006512             0.9938                                   True
 a  b  a                 0.0002231           20   0.3423            0.1712              0.833                                  False
 a  b  b                -5.901e-05           17   0.5764            0.7173             0.2882                                  False
 b  a  a                 0.0002171           20   0.3483            0.1742             0.8304                                  False
 b  a  b                 0.0008045           24  0.01369          0.006845             0.9935                                   True
 b  b  a                 0.0004276           22  0.05753           0.02876             0.9724                                  False
 b  b  b                 0.0001294           17    0.698             0.349             0.6575                                  False
 c  a  a                 0.0003823           23  0.08401           0.04201             0.9595                                  False
 c  a  b                 0.0005273           27 0.005968          0.002984             0.9972                                   True
 c  b  a                 0.0001025           21   0.5764            0.2882             0.7173                                  False
 c  b  b                 0.0002413           20   0.3423            0.1712              0.833                                  False

F-Q against DF-Q (variable), split (a), by seed:
O1 O5           seed  median_diff  n_FQ_better    p_two
 a  a              2    0.0006403           27 0.008235
 a  a              3    0.0004413           24  0.01741
 a  a              4    0.0003147           23  0.03873
 a  a              5    0.0005476           25  0.02515
 a  a              6    0.0005069           26 0.005345
 a  a              7    0.0005622           23  0.03271
 a  a average of six    0.0005898           25  0.01741
 a  b              2    0.0006759           24  0.01302
 a  b              3    0.0003324           24  0.02098
 a  b              4    0.0007525           25 0.003007
 a  b              5    0.0007725           22  0.02873
 a  b              6    0.0006554           24  0.02003
 a  b              7    0.0002881           24  0.03001
 a  b average of six    0.0006374           24 0.009141
 b  a              2    0.0002231           20   0.3423
 b  a              3    9.678e-05           21   0.4222
 b  a              4    0.0002183           20   0.5988
 b  a              5    0.0005099           23   0.1268
 b  a              6    3.536e-05           18    0.942
 b  a              7    0.0002424           23   0.1898
 b  a average of six    0.0001297           21    0.633
 b  b              2   -5.901e-05           17   0.5764
 b  b              3   -0.0001481           17   0.7038
 b  b              4    1.156e-05           18   0.9806
 b  b              5    3.387e-05           19    0.942
 b  b              6    5.139e-05           19   0.6446
 b  b              7    4.813e-05           19   0.9678
 b  b average of six    6.517e-05           18   0.9678
seeds finding a difference (p < 0.05): {('a', 'a'): 6, ('a', 'b'): 6, ('b', 'a'): 0, ('b', 'b'): 0}

Result: blocked (methods underspecified). In the main reading the two-sided Wilcoxon test finds F-Q (variable) better than DF-Q (variable), p = 0.0082 (27 of 35 sessions, median difference 0.00064). Of the 12 readings, 4 find a difference at p < 0.05 and 8 do not (p 0.058 to 0.70), so the readings disagree. Filter noise does not explain this: on split (a) with O1 (a), each of six seeds finds a difference (p 0.0053 to 0.039 under O5 a, 0.0030 to 0.030 under O5 b; six-seed average 0.017 and 0.0091), and with O1 (b) none does (p 0.13 to 0.98).

binary-prediction-accuracy¶

Taking left when the predicted P(L) exceeds 0.5 and right otherwise, the best model predicts 68% of choices correctly, averaged over the 35 test sessions.

In [33]:
rows = []
for (spk, form, clip, model), v in variable.items():
    if model != "FQ":
        continue
    m = SPL[spk]
    acc = []
    for pl, s in zip(sub(v["pl"], ~m), sub(seqs, ~m)):
        pred_left = pl > 0.5
        correct = np.where(pl == 0.5, 0.5, (pred_left == (s.a.values == 0)).astype(float))
        acc.append(100 * correct.mean())
    rows.append(dict(O3=spk, O1="ab"[form], O5="ab"[clip], mean_pct_correct=np.mean(acc), min=np.min(acc), max=np.max(acc)))
BA = pd.DataFrame(rows)
BA["ok"] = (BA.mean_pct_correct - 68).abs() <= 6.8
print(BA.round(2).to_string(index=False))
O3 O1 O5  mean_pct_correct   min   max   ok
 a  a  a             67.68 60.68 77.20 True
 b  a  a             67.89 60.75 77.20 True
 c  a  a             67.53 60.32 77.20 True
 a  a  b             67.86 61.57 77.43 True
 b  a  b             68.03 60.26 77.43 True
 c  a  b             67.53 60.19 77.20 True
 a  b  a             66.99 57.69 77.43 True
 b  b  a             67.75 57.69 77.43 True
 c  b  a             67.51 58.84 77.43 True
 a  b  b             67.00 57.49 77.20 True
 b  b  b             67.67 57.49 77.20 True
 c  b  b             67.35 59.11 77.20 True

Result: reproduced. F-Q (variable) predicts 67.0 to 68.0% of test choices correctly, averaged over test sessions, under all 12 readings (main 67.7%, sessions 60.7 to 77.2%), against 68%.

table2-ml-parameters¶

The maximum-likelihood parameters on the training data are those of Table 2.

In [34]:
T2 = [("Q", "alpha1", 0, 0.45), ("Q", "kappa1", 1, 1.25), ("FQ", "alpha1", 0, 0.55), ("FQ", "kappa1", 1, 1.25),
      ("FQ", "kappa2", 2, 0.55), ("DFQ", "alpha1", 0, 0.60), ("DFQ", "alpha2", 1, 0.45), ("DFQ", "kappa1", 2, 1.20),
      ("DFQ", "kappa2", 3, 0.45), ("LM", "alpha1", 0, 0.01)]
T2v = [("Q", "sigma_alpha", 0, 0.005), ("Q", "sigma_kappa", 1, 0.10), ("FQ", "sigma_alpha", 0, 0.005),
       ("FQ", "sigma_kappa", 1, 0.07), ("DFQ", "sigma_alpha", 0, 0.010), ("DFQ", "sigma_kappa", 1, 0.07)]
rows = []
for spk in SPL:
    for form in [0, 1]:
        for clip in [0, 1]:
            for o4 in ["grid", "cont"]:
                vals = []
                for m, p, i, e in T2:
                    q0 = 0.5 if m == "LM" else 0.0
                    vals.append((f"{m} {p}", const[(spk, form, m, o4, q0)]["x"][i], e))
                for m, p, i, e in T2v:
                    vals.append((f"{m} var {p}", variable[(spk, form, clip, m)]["sigma"][i], e))
                row = dict(O3=spk, O1="ab"[form], O5="ab"[clip], O4=o4)
                row.update({k: v for k, v, _ in vals})
                row["n within 10%"] = sum(abs(v - e) <= 0.1 * e + 1e-12 for _, v, e in vals)
                rows.append(row)
TB2 = pd.DataFrame(rows)
print(TB2.round(4).T.to_string())
print("\nwithin tolerance (of 16) by O1:", TB2.groupby("O1")["n within 10%"].agg(["min", "max"]).to_dict("index"))

# Training log-likelihood at the paper's Table 2 values next to the fitted optimum (per training trial,
# normalized likelihood), to tell a second optimum (equal or better at the paper's values) from a mismatch.
PAPER_CONST = {"Q": [0.45, 1.25], "FQ": [0.55, 1.25, 0.55], "DFQ": [0.60, 0.45, 1.20, 0.45], "LM": [0.01]}
rows = []
for spk, m in SPL.items():
    tr = sub(seqs, m); ntr = sum(len(s) for s in tr)
    for form in [0, 1]:
        for model, xp in PAPER_CONST.items():
            q0s = [0.0, 0.5] if model == "LM" else [0.0]
            for q0 in q0s:
                fit = const[(spk, form, model, "grid", q0)]["x"]
                rows.append(dict(O3=spk, O1="ab"[form], model=model + (f" Qi(1)={q0}" if model == "LM" else ""),
                                 fitted=np.round(fit, 3).tolist(),
                                 train_nl_fitted=np.exp(I.total_loglik(model, fit, tr, form, q0) / ntr),
                                 train_nl_paper=np.exp(I.total_loglik(model, np.array(xp), tr, form, q0) / ntr)))
TL = pd.DataFrame(rows)
TL["paper minus fitted"] = TL.train_nl_paper - TL.train_nl_fitted
print("\ntraining normalized likelihood at the fitted (grid) optimum and at Table 2's values:")
print(TL.to_string(index=False, float_format=lambda v: f"{v:.5f}"))
print("\nsigmas of the 5000-particle search (split a, O1 a; check 2):", {f"{m} O5 ({'ab'[cl]})": v for (cl, m), v in best5.items()})
print("training score at Table 2's sigmas minus the best, 5000 particles:",
      {f"{m} O5 ({'ab'[cl]})": round(search5[(cl, m, *SIG2_PAPER[m])] - search5[(cl, m, *best5[(cl, m)])], 5) for (cl, m) in best5})
                       0       1     2       3     4       5     6       7     8       9     10      11     12      13    14      15    16      17    18      19      20      21    22      23
O3                      a       a     a       a     a       a     a       a     b       b     b       b      b       b     b       b     c       c     c       c       c       c     c       c
O1                      a       a     a       a     b       b     b       b     a       a     a       a      b       b     b       b     a       a     a       a       b       b     b       b
O5                      a       a     b       b     a       a     b       b     a       a     b       b      a       a     b       b     a       a     b       b       a       a     b       b
O4                   grid    cont  grid    cont  grid    cont  grid    cont  grid    cont  grid    cont   grid    cont  grid    cont  grid    cont  grid    cont    grid    cont  grid    cont
Q alpha1              0.5   0.483   0.5   0.483   0.5   0.483   0.5   0.483  0.35  0.3519  0.35  0.3519   0.35  0.3519  0.35  0.3519  0.45  0.4368  0.45  0.4368    0.45  0.4368  0.45  0.4368
Q kappa1              1.2  1.2156   1.2  1.2156   0.6  0.5871   0.6  0.5871   1.3  1.3203   1.3  1.3203   0.45  0.4646  0.45  0.4646   1.3  1.3245   1.3  1.3245     0.6  0.5786   0.6  0.5786
FQ alpha1             0.6  0.5902   0.6  0.5902   0.6  0.5902   0.6  0.5902   0.5  0.4831   0.5  0.4831   0.45  0.4831  0.45  0.4831  0.55  0.5552  0.55  0.5552     0.6  0.5552   0.6  0.5552
FQ kappa1            1.15  1.1763  1.15  1.1763   0.7  0.6943   0.7  0.6943  1.25  1.2779  1.25  1.2779    0.6  0.6173   0.6  0.6173  1.25   1.229  1.25   1.229     0.7  0.6824   0.7  0.6824
FQ kappa2            0.55  0.5478  0.55  0.5478  0.35  0.3233  0.35  0.3233   0.6  0.5867   0.6  0.5867   0.25  0.2834  0.25  0.2834   0.7  0.6772   0.7  0.6772     0.4   0.376   0.4   0.376
DFQ alpha1           0.45  0.4382  0.45  0.4382  0.45  0.4382  0.45  0.4382  0.45  0.4745  0.45  0.4745   0.45  0.4745  0.45  0.4745   0.6  0.5776   0.6  0.5776     0.6  0.5776   0.6  0.5776
DFQ alpha2           0.05  0.0383  0.05  0.0383  0.05  0.0383  0.05  0.0383   0.3  0.3148   0.3  0.3148    0.3  0.3148   0.3  0.3148   0.5  0.4904   0.5  0.4904     0.5  0.4904   0.5  0.4904
DFQ kappa1           2.25   2.376  2.25   2.376  0.95  1.0412  0.95  1.0412   1.3  1.2822   1.3  1.2822    0.6  0.6084   0.6  0.6084   1.2  1.1994   1.2  1.1994     0.7  0.6927   0.7  0.6927
DFQ kappa2           -1.1 -1.2331  -1.1 -1.2331 -0.45 -0.5404 -0.45 -0.5404   0.4  0.3907   0.4  0.3907   0.15  0.1854  0.15  0.1854   0.6  0.6129   0.6  0.6129    0.35   0.354  0.35   0.354
LM alpha1            0.01  0.0118  0.01  0.0118  0.01  0.0137  0.01  0.0137  0.01  0.0138  0.01  0.0138   0.01  0.0145  0.01  0.0145  0.01  0.0123  0.01  0.0123    0.01  0.0139  0.01  0.0139
Q var sigma_alpha    0.02    0.02  0.02    0.02  0.02    0.02  0.02    0.02  0.01    0.01  0.02    0.02   0.02    0.02  0.02    0.02  0.02    0.02  0.02    0.02    0.02    0.02  0.02    0.02
Q var sigma_kappa    0.07    0.07  0.15    0.15  0.05    0.05  0.05    0.05  0.07    0.07  0.07    0.07   0.05    0.05  0.05    0.05  0.05    0.05  0.07    0.07    0.05    0.05  0.05    0.05
FQ var sigma_alpha   0.01    0.01  0.02    0.02  0.02    0.02  0.02    0.02  0.01    0.01  0.02    0.02   0.02    0.02  0.01    0.01  0.01    0.01  0.02    0.02    0.01    0.01  0.02    0.02
FQ var sigma_kappa   0.07    0.07  0.07    0.07  0.05    0.05  0.05    0.05  0.07    0.07  0.07    0.07   0.05    0.05  0.05    0.05  0.05    0.05  0.05    0.05    0.05    0.05  0.05    0.05
DFQ var sigma_alpha  0.01    0.01  0.02    0.02  0.02    0.02  0.02    0.02  0.01    0.01  0.02    0.02  0.005   0.005  0.02    0.02  0.01    0.01  0.02    0.02  0.0025  0.0025  0.02    0.02
DFQ var sigma_kappa  0.07    0.07  0.07    0.07  0.05    0.05  0.05    0.05  0.05    0.05  0.07    0.07   0.05    0.05  0.05    0.05  0.05    0.05  0.05    0.05    0.05    0.05  0.05    0.05
n within 10%            8       8     7       7     2       2     2       2     8       6     8       6      1       0     1       0     8       8     7       7       4       4     4       4

within tolerance (of 16) by O1: {'a': {'min': 6, 'max': 8}, 'b': {'min': 0, 'max': 4}}
training normalized likelihood at the fitted (grid) optimum and at Table 2's values:
O3 O1        model                    fitted  train_nl_fitted  train_nl_paper  paper minus fitted
 a  a            Q                [0.5, 1.2]          0.52192         0.52190            -0.00001
 a  a           FQ         [0.6, 1.15, 0.55]          0.52675         0.52672            -0.00003
 a  a          DFQ  [0.45, 0.05, 2.25, -1.1]          0.52719         0.52690            -0.00029
 a  a LM Qi(1)=0.0                     [0.0]          0.50000         0.41871            -0.08129
 a  a LM Qi(1)=0.5                    [0.01]          0.50828         0.50828             0.00000
 a  b            Q                [0.5, 0.6]          0.52192         0.49575            -0.02617
 a  b           FQ          [0.6, 0.7, 0.35]          0.52673         0.51106            -0.01567
 a  b          DFQ [0.45, 0.05, 0.95, -0.45]          0.52722         0.51589            -0.01134
 a  b LM Qi(1)=0.0                    [0.01]          0.41871         0.41871             0.00000
 a  b LM Qi(1)=0.5                    [0.01]          0.49879         0.49879             0.00000
 b  a            Q               [0.35, 1.3]          0.52235         0.52224            -0.00011
 b  a           FQ          [0.5, 1.25, 0.6]          0.52683         0.52675            -0.00009
 b  a          DFQ     [0.45, 0.3, 1.3, 0.4]          0.52694         0.52680            -0.00014
 b  a LM Qi(1)=0.0                     [0.0]          0.50000         0.42146            -0.07854
 b  a LM Qi(1)=0.5                    [0.01]          0.50872         0.50872             0.00000
 b  b            Q              [0.35, 0.45]          0.52234         0.49548            -0.02686
 b  b           FQ         [0.45, 0.6, 0.25]          0.52682         0.51051            -0.01631
 b  b          DFQ    [0.45, 0.3, 0.6, 0.15]          0.52692         0.51521            -0.01171
 b  b LM Qi(1)=0.0                    [0.02]          0.42176         0.42146            -0.00030
 b  b LM Qi(1)=0.5                    [0.01]          0.50180         0.50180             0.00000
 c  a            Q               [0.45, 1.3]          0.52449         0.52444            -0.00005
 c  a           FQ         [0.55, 1.25, 0.7]          0.52912         0.52895            -0.00017
 c  a          DFQ      [0.6, 0.5, 1.2, 0.6]          0.52916         0.52901            -0.00016
 c  a LM Qi(1)=0.0                     [0.0]          0.50000         0.41509            -0.08491
 c  a LM Qi(1)=0.5                    [0.01]          0.50757         0.50757             0.00000
 c  b            Q               [0.45, 0.6]          0.52449         0.50087            -0.02361
 c  b           FQ           [0.6, 0.7, 0.4]          0.52910         0.51471            -0.01438
 c  b          DFQ     [0.6, 0.5, 0.7, 0.35]          0.52916         0.51902            -0.01014
 c  b LM Qi(1)=0.0                    [0.01]          0.41509         0.41509             0.00000
 c  b LM Qi(1)=0.5                    [0.01]          0.49881         0.49881             0.00000

sigmas of the 5000-particle search (split a, O1 a; check 2): {'Q O5 (a)': (0.02, 0.07), 'FQ O5 (a)': (0.02, 0.025), 'DFQ O5 (a)': (0.01, 0.025), 'Q O5 (b)': (0.04, 0.15), 'FQ O5 (b)': (0.08, 0.07), 'DFQ O5 (b)': (0.04, 0.05)}
training score at Table 2's sigmas minus the best, 5000 particles: {'Q O5 (a)': -0.0025, 'FQ O5 (a)': -0.00048, 'DFQ O5 (a)': -0.00042, 'Q O5 (b)': -0.00086, 'FQ O5 (b)': -0.0008, 'DFQ O5 (b)': -0.00024}

Result: not reproduced. In the main reading 8 of 16 values are within 10%: standard Q kappa1, F-Q alpha1, kappa1 and kappa2, the local matching law alpha (with Qi(1) = 0.5; with Qi(1) = 0 its fitted alpha is 0), the F-Q sigma_kappa and both DF-Q sigmas. Other readings of O3 to O5 under O1 (a) give 6 to 8 of 16, and O1 (b) gives 0 to 4, so the 8 the criterion asks for partial reproduction is not reached under every reading. On split (a) the DF-Q constant fit lies elsewhere (alpha1 0.45, alpha2 0.05, kappa1 2.25, kappa2 -1.1 against 0.60, 0.45, 1.20, 0.45), and its training normalized likelihood is 0.00029 higher than at the paper's values, a different optimum, not a second equal one; on splits (b) and (c) the paper's values are within 0.0002 of the optimum. Under O1 (b) the paper's values are 0.010 to 0.027 below the optimum for every Q model. The sigma surface is flat: with 5000 particles on a wider grid (check 2) the best sigmas change (F-Q 0.02 and 0.025, DF-Q 0.01 and 0.025 under O5 a), with training scores within 0.0005 of those at the Table 2 sigmas for F-Q and DF-Q under O5 (a); under O5 (b) the Table 2 sigmas score 0.0008 below the best for F-Q. The local matching law alpha counts as a match only with the initial value Qi(1) = 0.5, which the paper does not give; with the Methods' Qi(1) = 0 the main reading has 7 of 16.

Runs with the sigmas of Table 2 (for Table 3, Fig. 4, supplemental Data 1 and Fig. 9)¶

Table 3, Fig. 4 and the action values of Fig. 9 use the time-varying models with the paper's own sigmas (Table 2: standard Q 0.005 and 0.10, F-Q 0.005 and 0.07, DF-Q 0.010 and 0.07), run over all 70 sessions with 5000 particles, under O1 (a, b) and O5 (a, b). Per-trial estimates are (O13) (a) the predictive mean at trial t, given e(1:t-1), or (b) the posterior mean after e(t).

In [35]:
SIG2 = {"Q": (0.005, 0.10), "FQ": (0.005, 0.07), "DFQ": (0.010, 0.07)}
t0 = time.time()
tab2runs = {(m, form, clip): pf_run(m, *SIG2[m], form, clip) for m in SIG2 for form in [0, 1] for clip in [0, 1]}
print(f"{len(tab2runs)} runs available, {time.time() - t0:.0f} s; filter cache holds {len(pf_cache)} runs")
COLS = ["QL", "QR", "alpha1", "alpha2", "kappa1", "kappa2"]
12 runs available, 0 s; filter cache holds 39 runs

table3-parameter-averages¶

Across all data the time-varying estimates average, for F-Q, alpha1 0.47 ± 0.25, kappa1 1.61 ± 0.77, kappa2 1.10 ± 0.87, and for DF-Q, alpha1 0.45 ± 0.19, alpha2 0.46 ± 0.19, kappa1 1.69 ± 0.77, kappa2 1.24 ± 0.92; standard Q alpha1 0.45 ± 0.23, kappa1 1.86 ± 0.68.

Averages (a) over all choice trials pooled; (b) over sessions, of per-session means.

In [36]:
T3 = [("Q", "alpha1", 0.45, 0.23), ("Q", "kappa1", 1.86, 0.68), ("FQ", "alpha1", 0.47, 0.25), ("FQ", "kappa1", 1.61, 0.77),
      ("FQ", "kappa2", 1.10, 0.87), ("DFQ", "alpha1", 0.45, 0.19), ("DFQ", "alpha2", 0.46, 0.19), ("DFQ", "kappa1", 1.69, 0.77),
      ("DFQ", "kappa2", 1.24, 0.92)]
rows = []
for form in [0, 1]:
    for clip in [0, 1]:
        for o13, idx in [("a", 1), ("b", 2)]:
            for avg in ["a", "b"]:
                row = dict(O1="ab"[form], O5="ab"[clip], O13=o13, average=avg)
                n_ok = 0
                for m, p, e, sd in T3:
                    est = tab2runs[(m, form, clip)][idx]
                    j = COLS.index(p)
                    if avg == "a":
                        x = np.concatenate([q[:, j] for q in est]); mu, sdv = x.mean(), x.std()
                    else:
                        x = np.array([q[:, j].mean() for q in est]); mu, sdv = x.mean(), x.std()
                    row[f"{m} {p}"] = f"{mu:.2f} ± {sdv:.2f}"
                    n_ok += abs(mu - e) <= sd
                row["means within tolerance (of 9)"] = n_ok
                rows.append(row)
TB3 = pd.DataFrame(rows)
print(TB3.T.to_string())
print("paper:", {f"{m} {p}": f"{e} ± {sd}" for m, p, e, sd in T3})
                                        0            1            2            3            4            5            6            7            8            9            10           11           12           13           14           15
O1                                       a            a            a            a            a            a            a            a            b            b            b            b            b            b            b            b
O5                                       a            a            a            a            b            b            b            b            a            a            a            a            b            b            b            b
O13                                      a            a            b            b            a            a            b            b            a            a            b            b            a            a            b            b
average                                  a            b            a            b            a            b            a            b            a            b            a            b            a            b            a            b
Q alpha1                       0.45 ± 0.25  0.44 ± 0.21  0.45 ± 0.25  0.44 ± 0.21  0.45 ± 0.25  0.44 ± 0.21  0.45 ± 0.25  0.44 ± 0.21  0.59 ± 0.22  0.58 ± 0.18  0.59 ± 0.22  0.58 ± 0.18  0.58 ± 0.22  0.57 ± 0.19  0.58 ± 0.22  0.57 ± 0.19
Q kappa1                       1.83 ± 0.85  1.88 ± 0.57  1.83 ± 0.85  1.88 ± 0.57  1.85 ± 0.87  1.90 ± 0.58  1.85 ± 0.87  1.90 ± 0.58  0.87 ± 0.60  0.87 ± 0.31  0.87 ± 0.59  0.87 ± 0.31  0.86 ± 0.59  0.87 ± 0.31  0.86 ± 0.59  0.87 ± 0.32
FQ alpha1                      0.48 ± 0.27  0.47 ± 0.24  0.48 ± 0.27  0.47 ± 0.24  0.47 ± 0.28  0.46 ± 0.25  0.47 ± 0.28  0.46 ± 0.25  0.61 ± 0.22  0.59 ± 0.20  0.61 ± 0.22  0.59 ± 0.20  0.60 ± 0.22  0.58 ± 0.19  0.60 ± 0.22  0.58 ± 0.19
FQ kappa1                      1.64 ± 0.79  1.70 ± 0.55  1.64 ± 0.79  1.70 ± 0.55  1.69 ± 0.83  1.74 ± 0.59  1.69 ± 0.83  1.74 ± 0.59  0.77 ± 0.54  0.78 ± 0.31  0.77 ± 0.53  0.78 ± 0.31  0.77 ± 0.54  0.78 ± 0.31  0.77 ± 0.53  0.78 ± 0.31
FQ kappa2                      1.19 ± 0.82  1.20 ± 0.54  1.18 ± 0.82  1.20 ± 0.54  1.25 ± 0.84  1.26 ± 0.56  1.24 ± 0.84  1.26 ± 0.56  0.66 ± 0.63  0.65 ± 0.39  0.66 ± 0.63  0.65 ± 0.39  0.66 ± 0.63  0.65 ± 0.40  0.66 ± 0.63  0.65 ± 0.40
DFQ alpha1                     0.47 ± 0.24  0.46 ± 0.21  0.47 ± 0.24  0.46 ± 0.21  0.46 ± 0.23  0.45 ± 0.21  0.46 ± 0.23  0.45 ± 0.21  0.64 ± 0.20  0.63 ± 0.17  0.64 ± 0.20  0.63 ± 0.17  0.61 ± 0.18  0.61 ± 0.15  0.61 ± 0.18  0.61 ± 0.15
DFQ alpha2                     0.51 ± 0.27  0.50 ± 0.23  0.51 ± 0.27  0.50 ± 0.23  0.50 ± 0.24  0.49 ± 0.21  0.50 ± 0.24  0.49 ± 0.21  0.53 ± 0.24  0.52 ± 0.20  0.53 ± 0.24  0.52 ± 0.20  0.52 ± 0.23  0.51 ± 0.20  0.52 ± 0.23  0.51 ± 0.20
DFQ kappa1                     1.72 ± 0.78  1.76 ± 0.56  1.72 ± 0.78  1.76 ± 0.56  1.77 ± 0.80  1.81 ± 0.58  1.77 ± 0.80  1.81 ± 0.58  0.79 ± 0.51  0.81 ± 0.29  0.79 ± 0.51  0.80 ± 0.29  0.79 ± 0.52  0.80 ± 0.29  0.79 ± 0.52  0.80 ± 0.29
DFQ kappa2                     1.26 ± 0.86  1.26 ± 0.59  1.26 ± 0.86  1.25 ± 0.59  1.30 ± 0.89  1.30 ± 0.60  1.30 ± 0.89  1.30 ± 0.60  0.65 ± 0.68  0.63 ± 0.45  0.64 ± 0.68  0.63 ± 0.45  0.64 ± 0.69  0.62 ± 0.45  0.63 ± 0.69  0.62 ± 0.45
means within tolerance (of 9)            9            9            9            9            9            9            9            9            6            6            6            6            6            6            6            6
paper: {'Q alpha1': '0.45 ± 0.23', 'Q kappa1': '1.86 ± 0.68', 'FQ alpha1': '0.47 ± 0.25', 'FQ kappa1': '1.61 ± 0.77', 'FQ kappa2': '1.1 ± 0.87', 'DFQ alpha1': '0.45 ± 0.19', 'DFQ alpha2': '0.46 ± 0.19', 'DFQ kappa1': '1.69 ± 0.77', 'DFQ kappa2': '1.24 ± 0.92'}

Result: blocked (methods underspecified). Under the update O1 (a), all nine means are within their tolerance in all 8 readings of O5, O13 and the averaging (for example F-Q alpha1 0.48 ± 0.27, kappa1 1.64 ± 0.79, kappa2 1.19 ± 0.82 over pooled trials). Under O1 (b) only 6 of 9 are, as the kappas take about half the scale. The criterion asks for every reading of O1; the readings disagree. The table 1 and 2 criteria treat O1 as the parameterization of the reported values, which would make O1 (a) the match; this inconsistency is asked of a reader (questions/001641.yaml).

fig4-strategy-tracking¶

With time-varying parameters, F-Q and DF-Q capture win-stay-lose-switch behaviour by raising kappa2 close to kappa1, and persevering behaviour by a negative kappa2, which the standard Q model cannot.

Episodes as the criterion defines them: a win-stay-lose-switch episode is a run of at least L choice trials in which every rewarded choice was repeated and every unrewarded one switched; a persevering episode is a run of at least L consecutive choices of the less advantageous side in a (10, 50) or (50, 10) block; L = 5, 10, 15. Episodes lie within a session (runs over block borders allowed for win-stay-lose-switch, as the definition does not use the block). kappa1 and kappa2 are the F-Q (variable) estimates at the episode's last trial (O13); "within 25%" is |kappa2 - kappa1| <= 0.25 kappa1.

In [37]:
def runs_of(flag, minlen):
    out, start = [], None
    for i, f in enumerate(np.r_[flag, False]):
        if f and start is None:
            start = i
        elif not f and start is not None:
            if i - start >= minlen:
                out.append((start, i))
            start = None
    return out

rows = []
for form in [0, 1]:
    for clip in [0, 1]:
        fq = tab2runs[("FQ", form, clip)]; sq = tab2runs[("Q", form, clip)]
        for o13, idx in [("a", 1), ("b", 2)]:
            for Lmin in [5, 10, 15]:
                wsls_close, wsls_n, pers_neg, pers_n, lik_fq, lik_q = 0, 0, 0, 0, [], []
                for k, s in enumerate(seqs):
                    a, r = s.a.values, s.r.values
                    # transition t -> t+1 follows WSLS
                    ok = np.r_[(a[1:] == np.where(r[:-1] == 1, a[:-1], 1 - a[:-1])), False]
                    # a run of n trials with WSLS holds n-1 transitions: trials start..end-1 all followed by a WSLS move
                    for st_, en in runs_of(ok[:-1], Lmin - 1):
                        last = en  # last trial of the episode
                        k1, k2 = fq[idx][k][last, 4], fq[idx][k][last, 5]
                        wsls_n += 1; wsls_close += abs(k2 - k1) <= 0.25 * abs(k1)
                        sl = slice(st_, en + 1)
                        lik_fq.append(np.exp(I.loglik(fq[0][k][sl], a[sl])).mean()); lik_q.append(np.exp(I.loglik(sq[0][k][sl], a[sl])).mean())
                    worse = np.where(s.rule_L.values < s.rule_R.values, 0, 1)
                    lowblock = np.isin(list(zip(s.rule_L.values, s.rule_R.values)), [(10, 50), (50, 10)]).all(axis=1) if False else (
                        ((s.rule_L.values == 10) & (s.rule_R.values == 50)) | ((s.rule_L.values == 50) & (s.rule_R.values == 10)))
                    pflag = lowblock & (a == worse)
                    # runs within one block
                    bchange = np.r_[False, s.block.values[1:] != s.block.values[:-1]]
                    for st_, en in runs_of(pflag, Lmin):
                        if bchange[st_ + 1:en].any():
                            continue
                        k2 = fq[idx][k][en - 1, 5]
                        pers_n += 1; pers_neg += k2 < 0
                        sl = slice(st_, en)
                        lik_fq.append(np.exp(I.loglik(fq[0][k][sl], a[sl])).mean()); lik_q.append(np.exp(I.loglik(sq[0][k][sl], a[sl])).mean())
                rows.append(dict(O1="ab"[form], O5="ab"[clip], O13=o13, L=Lmin, wsls_episodes=wsls_n, wsls_k2_close_k1=wsls_close,
                                 persev_episodes=pers_n, persev_k2_negative=pers_neg,
                                 mean_lik_FQvar=np.mean(lik_fq), mean_lik_Qvar=np.mean(lik_q)))
F4 = pd.DataFrame(rows)
F4["holds"] = (F4.wsls_k2_close_k1 > 0) & (F4.persev_k2_negative > 0) & (F4.mean_lik_FQvar > F4.mean_lik_Qvar)
print(F4.round(4).to_string(index=False))
print("readings where the criterion holds:", int(F4.holds.sum()), "of", len(F4))
O1 O5 O13  L  wsls_episodes  wsls_k2_close_k1  persev_episodes  persev_k2_negative  mean_lik_FQvar  mean_lik_Qvar  holds
 a  a   a  5           2374               708              131                  23          0.6251         0.5887   True
 a  a   a 10            409               124               15                  11          0.6775         0.6225   True
 a  a   a 15             75                25                4                   4          0.7283         0.6704   True
 a  a   b  5           2374               717              131                  25          0.6251         0.5887   True
 a  a   b 10            409               119               15                  11          0.6775         0.6225   True
 a  a   b 15             75                24                4                   4          0.7283         0.6704   True
 a  b   a  5           2374               723              131                  22          0.6245         0.5881   True
 a  b   a 10            409               120               15                  12          0.6767         0.6196   True
 a  b   a 15             75                24                4                   4          0.7282         0.6649   True
 a  b   b  5           2374               728              131                  23          0.6245         0.5881   True
 a  b   b 10            409               122               15                  13          0.6767         0.6196   True
 a  b   b 15             75                24                4                   4          0.7282         0.6649   True
 b  a   a  5           2374               588              131                  75          0.6340         0.5930   True
 b  a   a 10            409               114               15                  15          0.6903         0.6293   True
 b  a   a 15             75                27                4                   4          0.7442         0.6789   True
 b  a   b  5           2374               612              131                  82          0.6340         0.5930   True
 b  a   b 10            409               111               15                  15          0.6903         0.6293   True
 b  a   b 15             75                26                4                   4          0.7442         0.6789   True
 b  b   a  5           2374               581              131                  76          0.6342         0.5934   True
 b  b   a 10            409               115               15                  15          0.6907         0.6294   True
 b  b   a 15             75                24                4                   4          0.7448         0.6801   True
 b  b   b  5           2374               607              131                  81          0.6342         0.5934   True
 b  b   b 10            409               116               15                  15          0.6907         0.6294   True
 b  b   b 15             75                22                4                   4          0.7448         0.6801   True
readings where the criterion holds: 24 of 24

Result: reproduced. In all 24 readings some win-stay-lose-switch episode ends with F-Q kappa2 within 25% of kappa1 (22 to 728 episodes), some persevering episode ends with kappa2 below 0 (4 to 82 episodes), and over these episodes F-Q (variable) gives a higher mean per-trial likelihood than standard Q (variable), 0.62 to 0.74 against 0.59 to 0.68.

suppdata1-choice-vs-q-difference¶

The actual left-choice probability, plotted against QL - QR from the standard Q, F-Q and DF-Q models, confirms that the models' predictions are meaningful.

QL - QR before each choice (O13 a), over all choice trials of the 70 sessions, in ten equal-count bins; variable versions (Table 2 sigmas, O1 a, O5 a) and constant versions (parameters fitted on split (a), O1 a, grid; for these QL - QR = logit P(L)). Spearman correlation of the bins' mean QL - QR and their left-choice fraction.

In [38]:
aL = np.concatenate([1 - s.a.values for s in seqs])
rows = []
fig, ax = plt.subplots(1, 2, figsize=(9, 3.5))
for ver in ["variable", "constant"]:
    for m in ["Q", "FQ", "DFQ"]:
        for form in [0, 1]:
            if ver == "variable":
                pred = tab2runs[(m, form, 0)][1]
                dq = np.concatenate([q[:, 0] - q[:, 1] for q in pred])
            else:
                p = np.clip(np.concatenate(const[("a", form, m, "grid", 0.0)]["pl"]), 1e-12, 1 - 1e-12)
                dq = np.log(p / (1 - p))
            bins = pd.qcut(dq, 10, labels=False, duplicates="drop")
            g = pd.DataFrame(dict(dq=dq, L=aL, b=bins)).groupby("b").agg(dq=("dq", "mean"), L=("L", "mean"), n=("L", "size"))
            rho = ss.spearmanr(g.dq, g.L).statistic
            rows.append(dict(version=ver, model=m, O1="ab"[form], bins=len(g), spearman=rho,
                             fraction_left_lowest_bin=g.L.iloc[0], fraction_left_highest_bin=g.L.iloc[-1]))
            if form == 0:
                ax[int(ver == "constant")].plot(g.dq, g.L, "o-", label=m)
for a_, t_ in zip(ax, ["variable (Table 2 sigmas)", "constant"]):
    a_.set(xlabel="QL - QR (bin mean)", ylabel="fraction of left choices", title=t_); a_.legend()
plt.tight_layout(); plt.show()
SD1 = pd.DataFrame(rows)
SD1["rises"] = SD1.spearman > 0.9
print(SD1.round(3).to_string(index=False))
No description has been provided for this image
 version model O1  bins  spearman  fraction_left_lowest_bin  fraction_left_highest_bin  rises
variable     Q  a    10       1.0                     0.223                      0.778   True
variable     Q  b    10       1.0                     0.238                      0.769   True
variable    FQ  a    10       1.0                     0.228                      0.772   True
variable    FQ  b    10       1.0                     0.234                      0.766   True
variable   DFQ  a    10       1.0                     0.227                      0.765   True
variable   DFQ  b    10       1.0                     0.234                      0.767   True
constant     Q  a    10       1.0                     0.240                      0.745   True
constant     Q  b    10       1.0                     0.240                      0.745   True
constant    FQ  a    10       1.0                     0.239                      0.733   True
constant    FQ  b    10       1.0                     0.240                      0.731   True
constant   DFQ  a    10       1.0                     0.234                      0.784   True
constant   DFQ  b    10       1.0                     0.233                      0.784   True

Result: reproduced. For the variable and constant versions of all three models, under both update forms, the left-choice fraction rises over the ten bins of QL - QR (Spearman 1.0 in all 12), from 0.22 to 0.24 in the lowest bin to 0.73 to 0.78 in the highest.

Neural data¶

Units are taken as the dataset gives them (Area NAc or VP). Each unit is recorded in one session (electrodes advanced 125 um per session, Surgery), so units are not matched across sessions. Spike counts are taken in the 1 s bins of Fig. 8A (helper PHASES); phase 5 starts at the reward or no-reward tone onset found in the event series.

In [39]:
UN = []
for k, s in enumerate(S):
    for i, u in s["units"].iterrows():
        UN.append(dict(sess=k, subject=s["subject"], i=i, area=u.area, unit=u.unit_name, n_spikes=len(u.spike_times)))
UN = pd.DataFrame(UN)
rows = []
t0 = time.time()
for k, s in enumerate(S):
    if len(s["units"]) == 0:
        continue
    t = T[T.sess == k].reset_index(drop=True)
    pc = I.phase_counts(s, t)
    ch = t.choice.values; nc = t.nochoice.values
    cueA = (t.state == 1).values & t.tone_on_time.notna().values; cueB = (t.state == 2).values & t.tone_on_time.notna().values
    L = ch & (t.action == 1).values; R = ch & (t.action == 2).values
    rw = ch & (t.reward == 1).values; nr = ch & (t.reward == 0).values
    last20 = np.zeros(len(t), bool)
    for b, g in t[t.choice].groupby("block"):
        last20[g.index[-20:]] = True
    rule = np.array(list(zip(t.rule_L, t.rule_R)))
    blk = {p: (rule[:, 0] == p[0]) & (rule[:, 1] == p[1]) for p in [(90, 50), (50, 90), (50, 10), (10, 50)]}
    for i, u in s["units"].iterrows():
        Cn = pc[i]
        d = dict(sess=k, subject=s["subject"], area=u.area, unit=u.unit_name)
        d["p_state"] = I.mw_p(Cn[ch & (t.state == 1).values, 1], Cn[nc, 1])
        d["p_state_all"] = I.mw_p(Cn[cueA, 1], Cn[cueB, 1])
        d["p_ac"] = I.mw_p(Cn[L, 2], Cn[R, 2]); d["p_act"] = I.mw_p(Cn[L, 3], Cn[R, 3]); d["p_rew"] = I.mw_p(Cn[rw, 4], Cn[nr, 4])
        d["d_state"] = np.nanmean(Cn[ch & (t.state == 1).values, 1]) - np.nanmean(Cn[nc, 1])
        d["d_state_all"] = np.nanmean(Cn[cueA, 1]) - np.nanmean(Cn[cueB, 1])
        d["d_ac"] = np.nanmean(Cn[L, 2]) - np.nanmean(Cn[R, 2]); d["d_act"] = np.nanmean(Cn[L, 3]) - np.nanmean(Cn[R, 3])
        d["d_rew"] = np.nanmean(Cn[rw, 4]) - np.nanmean(Cn[nr, 4])
        d["n_phase5_missing"] = int(np.isnan(Cn[ch, 4]).sum())
        for ph in [1, 2, 3]:
            x = Cn[:, ph - 1]
            m = last20 & ch
            pL = I.mw_p(x[m & blk[(90, 50)]], x[m & blk[(10, 50)]]); pR = I.mw_p(x[m & blk[(50, 90)]], x[m & blk[(50, 10)]])
            d[f"QL{ph}"] = bool((pL < 0.01) and not (pR < 0.01)); d[f"QR{ph}"] = bool((pR < 0.01) and not (pL < 0.01))
            d[f"blocks_missing{ph}"] = int(sum((m & blk[p]).sum() == 0 for p in blk))
            ok = m & ~np.isnan(x)
            y = x[ok]; X = np.c_[rule[ok, 0] / 100, rule[ok, 1] / 100]
            if y.std() > 0 and np.linalg.matrix_rank(np.c_[np.ones(len(y)), X]) == 3:
                r1 = sm.OLS(y, sm.add_constant(X)).fit(); r2 = sm.OLS(y, sm.add_constant(np.c_[X.sum(1), X[:, 0] - X[:, 1]])).fit()
                p1, p2 = r1.pvalues[1], r1.pvalues[2]; p3, p4 = r2.pvalues[1], r2.pvalues[2]
            else:
                p1 = p2 = p3 = p4 = 1.0
                d[f"reg_failed{ph}"] = True
            d[f"rQL{ph}"] = bool(p1 < 0.01 and not p2 < 0.01); d[f"rQR{ph}"] = bool(p2 < 0.01 and not p1 < 0.01)
            d[f"V{ph}"] = bool(p3 < 0.01 and not p4 < 0.01); d[f"P{ph}"] = bool(p4 < 0.01 and not p3 < 0.01)
        rows.append(d)
D = pd.DataFrame(rows)
NREG = D.area.value_counts().to_dict()
print(f"{len(D)} units in {D.sess.nunique()} sessions ({time.time() - t0:.0f} s); per area {NREG}")
print("units with a missing phase-5 onset in some choice trial:", int((D.n_phase5_missing > 0).sum()),
      " total trials:", int(D.n_phase5_missing.sum()))
print("units whose session lacks a block type among the last-20 trials (phase 1):", int((D.blocks_missing1 > 0).sum()))
print("regressions that could not be fitted (no variance):", int(D.filter(like="reg_failed").notna().any(axis=1).sum()))

def count(col, area):
    return int(D.loc[D.area == area, col].sum())
214 units in 52 sessions (1 s); per area {'NAc': 148, 'VP': 66}
units with a missing phase-5 onset in some choice trial: 30  total trials: 695
units whose session lacks a block type among the last-20 trials (phase 1): 0
regressions that could not be fitted (no variance): 1

neuron-counts¶

Analysis used 148 NAc neurons and 66 VP neurons from six rats in 70 sessions.

In [40]:
print(UN.groupby("area").size().to_dict())
print("by rat:\n", UN.pivot_table(index="subject", columns="area", values="unit", aggfunc="count", fill_value=0))
print("sessions with at least one unit:", UN.sess.nunique(), "of", len(S), "; rats with units:", UN.subject.nunique())
{'NAc': 148, 'VP': 66}
by rat:
 area     NAc  VP
subject         
31        44  34
32        19   2
34        29  11
35        45   0
42        10  19
44         1   0
sessions with at least one unit: 52 of 70 ; rats with units: 6

Result: reproduced. The dataset holds 148 NAc and 66 VP units from six rats, in 52 of the 70 sessions; the other 18 files have no units.

firing-rates¶

VP neurons fire faster than NAc neurons during the task (10.2 ± 9.1 against 2.6 ± 2.6 Hz, mean ± SD).

Readings O15: (a) spikes over the whole recording of the session (from the session's first to its last recorded spike or trial event, as the files give no recording span); (b) spikes from the first trial start to the last trial end.

In [41]:
rows = []
for k, s in enumerate(S):
    if len(s["units"]) == 0:
        continue
    t = s["trials"]
    allsp = np.concatenate(list(s["units"].spike_times))
    a0, a1 = min(allsp.min(), t.start_time.min()), max(allsp.max(), t.stop_time.max())
    b0, b1 = t.start_time.min(), t.stop_time.max()
    for _, u in s["units"].iterrows():
        st = u.spike_times
        rows.append(dict(sess=k, subject=s["subject"], area=u.area, rate_a=len(st) / (a1 - a0),
                         rate_b=((st >= b0) & (st <= b1)).sum() / (b1 - b0)))
FR = pd.DataFrame(rows)
print(FR.groupby("area")[["rate_a", "rate_b"]].agg(["mean", "std", "median", "min", "max"]).round(2).T)
print("paper: VP 10.2 ± 9.1, NAc 2.6 ± 2.6 Hz")
print("by rat (reading b, mean Hz):\n", FR.pivot_table(index="subject", columns="area", values="rate_b", aggfunc="mean").round(2))
area             NAc     VP
rate_a mean     2.60  10.21
       std      2.59   9.14
       median   1.74   7.22
       min      0.18   0.58
       max     15.25  42.12
rate_b mean     2.62  10.21
       std      2.61   9.15
       median   1.75   7.21
       min      0.18   0.58
       max     15.25  42.14
paper: VP 10.2 ± 9.1, NAc 2.6 ± 2.6 Hz
by rat (reading b, mean Hz):
 area      NAc     VP
subject             
31       2.61  12.06
32       1.74   5.20
34       2.84   7.12
35       2.59    NaN
42       3.84   9.24
44       2.14    NaN

Result: reproduced. VP units fire at 10.21 ± 9.14 Hz and NAc units at 2.60 ± 2.59 Hz over the whole recording (10.21 ± 9.15 and 2.62 ± 2.61 Hz over the trials), against 10.2 ± 9.1 and 2.6 ± 2.6 Hz; the SDs are within 10%. VP is faster in every rat with VP units.

fig8b-state-coding¶

After cue onset (phase 2), 54% of NAc neurons (80 of 148) and 50% of VP neurons (33 of 66) fire differently for the choice and the no-choice tone (state-coding neurons).

Trials O14: (a) successful choice and no-choice trials; (b) all trials with tone A or tone B.

In [42]:
for lab, col in [("O14 (a)", "p_state"), ("O14 (b)", "p_state_all")]:
    print(lab, {a: f"{count(col + '_sig', a) if False else int((D.loc[D.area == a, col] < 0.01).sum())} of {NREG[a]}" for a in ["NAc", "VP"]})
print("paper: NAc 80 of 148 (tol 8), VP 33 of 66 (tol 3.3)")
print("by rat, O14 (a):\n", D.assign(sig=D.p_state < 0.01).pivot_table(index="subject", columns="area", values="sig", aggfunc=["sum", "count"]))
for thr in [0.005, 0.01, 0.05]:
    print(f"  threshold {thr}:", {a: int((D.loc[D.area == a, "p_state"] < thr).sum()) for a in ["NAc", "VP"]})
O14 (a) {'NAc': '80 of 148', 'VP': '33 of 66'}
O14 (b) {'NAc': '83 of 148', 'VP': '37 of 66'}
paper: NAc 80 of 148 (tol 8), VP 33 of 66 (tol 3.3)
by rat, O14 (a):
           sum       count      
area      NAc    VP   NAc    VP
subject                        
31       18.0  12.0  44.0  34.0
32        7.0   1.0  19.0   2.0
34       22.0   8.0  29.0  11.0
35       28.0   NaN  45.0   NaN
42        4.0  12.0  10.0  19.0
44        1.0   NaN   1.0   NaN
  threshold 0.005: {'NAc': 76, 'VP': 31}
  threshold 0.01: {'NAc': 80, 'VP': 33}
  threshold 0.05: {'NAc': 93, 'VP': 40}

Result: blocked (methods underspecified). With successful choice and no-choice trials (O14 a), 80 of 148 NAc and 33 of 66 VP units differ, exactly as reported. Counting all tone-A and tone-B trials (O14 b) gives 83 and 37, and 37 is outside the VP tolerance. The criterion asks for both readings; they disagree. O14 (a) follows the Methods' comparison of "choice trials and no-choice trials", which the task defines as successful trials, but the paper does not say that error trials were left out.

fig8b-action-value-psth¶

By block comparison of firing, few neurons code an action value; QL-coding neurons are 6, 8 and 7% of NAc neurons and 11, 18 and 21% of VP neurons in phases 1 to 3, and QR-coding neurons 7, 8 and 5% (NAc) and 11, 9 and 11% (VP).

Last 20 choice trials of each block (all blocks, including a session's last, unfinished one); blocks of the same type in a session pooled; Mann-Whitney at p < 0.01. Each count judged within its 10% tolerance or ±2 neurons.

In [43]:
EXP_AV = {("NAc", "QL1"): 9, ("VP", "QL1"): 7, ("NAc", "QR1"): 11, ("VP", "QR1"): 7, ("NAc", "QL2"): 12, ("VP", "QL2"): 12,
          ("NAc", "QR2"): 12, ("VP", "QR2"): 6, ("NAc", "QL3"): 11, ("VP", "QL3"): 14, ("NAc", "QR3"): 8, ("VP", "QR3"): 7}
rows = [dict(area=a, var=v, count=count(v, a), pct=100 * count(v, a) / NREG[a], expected=e,
             ok=abs(count(v, a) - e) <= max(2, 0.1 * e)) for (a, v), e in EXP_AV.items()]
AV = pd.DataFrame(rows)
print(AV.round(1).to_string(index=False))
print("matching:", int(AV.ok.sum()), "of 12; every count below 25% of its region:", bool((AV.pct < 25).all()))
area var  count  pct  expected    ok
 NAc QL1     13  8.8         9 False
  VP QL1      9 13.6         7  True
 NAc QR1     16 10.8        11 False
  VP QR1      7 10.6         7  True
 NAc QL2     15 10.1        12 False
  VP QL2     11 16.7        12  True
 NAc QR2     12  8.1        12  True
  VP QR2      8 12.1         6  True
 NAc QL3     11  7.4        11  True
  VP QL3     13 19.7        14  True
 NAc QR3     10  6.8         8  True
  VP QR3      8 12.1         7  True
matching: 9 of 12; every count below 25% of its region: True

Result: partially reproduced. 9 of the 12 counts are within ±2 neurons (or 10%), and every population is under 25% of its region (largest 19.7%). The NAc QL in phases 1 and 2 (13 and 15 against 9 and 12) and NAc QR in phase 1 (16 against 11) are higher than reported.

fig8b-action-command-coding, fig8b-action-coding, fig8b-reward-coding¶

Before action initiation (phase 3), 11% of NAc neurons (17 of 148) and 18% of VP neurons (12 of 66) code the action to be chosen.

After action onset (phase 4), 41% of NAc neurons (61 of 148) and 39% of VP neurons (26 of 66) code the selected action.

After the reward or no-reward tone (phase 5), 63% of NAc neurons (93 of 148) and 68% of VP neurons (45 of 66) code reward availability.

In [44]:
def show(col, exp):
    for a in ["NAc", "VP"]:
        n = int((D.loc[D.area == a, col] < 0.01).sum())
        print(f"  {a}: {n} of {NREG[a]} ({100 * n / NREG[a]:.0f}%), expected {exp[a]} ± {0.1 * exp[a]:.1f}: {abs(n - exp[a]) <= 0.1 * exp[a]}")
    print("  by rat:", D.assign(sig=D[col] < 0.01).groupby(["subject", "area"]).sig.sum().to_dict())
print("action command, phase 3:"); show("p_ac", {"NAc": 17, "VP": 12})
action command, phase 3:
  NAc: 15 of 148 (10%), expected 17 ± 1.7: False
  VP: 14 of 66 (21%), expected 12 ± 1.2: False
  by rat: {('31', 'NAc'): 6, ('31', 'VP'): 7, ('32', 'NAc'): 3, ('32', 'VP'): 0, ('34', 'NAc'): 2, ('34', 'VP'): 3, ('35', 'NAc'): 3, ('42', 'NAc'): 0, ('42', 'VP'): 4, ('44', 'NAc'): 1}

Result: not reproduced. 15 of 148 NAc units (expected 17 ± 1.7) and 14 of 66 VP units (expected 12 ± 1.2) code the upcoming action in phase 3; both differ from the expected count by 2, more than the tolerance, the NAc low and the VP high.

In [45]:
print("action, phase 4:"); show("p_act", {"NAc": 61, "VP": 26})
action, phase 4:
  NAc: 63 of 148 (43%), expected 61 ± 6.1: True
  VP: 26 of 66 (39%), expected 26 ± 2.6: True
  by rat: {('31', 'NAc'): 21, ('31', 'VP'): 13, ('32', 'NAc'): 6, ('32', 'VP'): 0, ('34', 'NAc'): 17, ('34', 'VP'): 4, ('35', 'NAc'): 15, ('42', 'NAc'): 4, ('42', 'VP'): 9, ('44', 'NAc'): 0}

Result: reproduced. 63 of 148 NAc units and 26 of 66 VP units code the chosen action in phase 4 (expected 61 and 26).

In [46]:
print("reward, phase 5:"); show("p_rew", {"NAc": 93, "VP": 45})
reward, phase 5:
  NAc: 96 of 148 (65%), expected 93 ± 9.3: True
  VP: 44 of 66 (67%), expected 45 ± 4.5: True
  by rat: {('31', 'NAc'): 30, ('31', 'VP'): 18, ('32', 'NAc'): 14, ('32', 'VP'): 2, ('34', 'NAc'): 18, ('34', 'VP'): 10, ('35', 'NAc'): 27, ('42', 'NAc'): 6, ('42', 'VP'): 14, ('44', 'NAc'): 1}

Result: reproduced. 96 of 148 NAc units and 44 of 66 VP units code reward in phase 5 (expected 93 and 45).

fig8b-nac-vp-same-event-coding, fig8b-ql-vp-higher, fig8b-qr-no-region-difference¶

Mann-Whitney U tests on per-neuron 0/1 coding indicators, NAc against VP (reading O9). The reading reproduces the paper's own p-values from the paper's counts (shown first).

In [47]:
print("O9 on the paper's counts: QL2 12/148 vs 12/66 p =", round(I.mw_indicator_p(12, 148, 12, 66), 3),
      "; QL3 11/148 vs 14/66 p =", round(I.mw_indicator_p(11, 148, 14, 66), 4), "; state 80/148 vs 33/66 p =", round(I.mw_indicator_p(80, 148, 33, 66), 2))
rows = []
for lab, col in [("state (O14 a)", "p_state"), ("state (O14 b)", "p_state_all"), ("action command", "p_ac"), ("action", "p_act"), ("reward", "p_rew")]:
    kN, kV = int((D.loc[D.area == "NAc", col] < 0.01).sum()), int((D.loc[D.area == "VP", col] < 0.01).sum())
    rows.append(dict(type=lab, NAc=f"{kN}/148", VP=f"{kV}/66", pct_diff_VP_minus_NAc=100 * (kV / 66 - kN / 148),
                     p=I.mw_indicator_p(kN, 148, kV, 66)))
RG = pd.DataFrame(rows); RG["difference found (p < 0.05)"] = RG.p < 0.05
print(RG.round(3).to_string(index=False))
O9 on the paper's counts: QL2 12/148 vs 12/66 p = 0.031 ; QL3 11/148 vs 14/66 p = 0.0038 ; state 80/148 vs 33/66 p = 0.58
          type    NAc    VP  pct_diff_VP_minus_NAc     p  difference found (p < 0.05)
 state (O14 a) 80/148 33/66                 -4.054 0.584                        False
 state (O14 b) 83/148 37/66                 -0.020 0.998                        False
action command 15/148 14/66                 11.077 0.029                         True
        action 63/148 26/66                 -3.174 0.664                        False
        reward 96/148 44/66                  1.802 0.798                        False

Result: not reproduced. The test as O9 reads it reproduces the paper's p-values from the paper's counts (0.031, 0.0038, 0.58). On the dataset's counts it finds no difference for state (p = 0.58), action (0.66) or reward (0.80), but finds one for action command (10.1% against 21.2%, p = 0.029), where the paper reports p = 0.19.

In [48]:
for v in ["QL1", "QL2", "QL3"]:
    kN, kV = count(v, "NAc"), count(v, "VP")
    print(f"{v}: NAc {kN}/148 ({100*kN/148:.1f}%), VP {kV}/66 ({100*kV/66:.1f}%), p = {I.mw_indicator_p(kN, 148, kV, 66):.4f}")
QL1: NAc 13/148 (8.8%), VP 9/66 (13.6%), p = 0.2815
QL2: NAc 15/148 (10.1%), VP 11/66 (16.7%), p = 0.1778
QL3: NAc 11/148 (7.4%), VP 13/66 (19.7%), p = 0.0088

Result: partially reproduced. QL-coding units are a larger share of VP than of NAc units in phase 3 (19.7% against 7.4%, p = 0.0088), but not significantly in phase 2 (16.7% against 10.1%, p = 0.18).

In [49]:
for v in ["QR1", "QR2", "QR3"]:
    kN, kV = count(v, "NAc"), count(v, "VP")
    print(f"{v}: NAc {kN}/148 ({100*kN/148:.1f}%), VP {kV}/66 ({100*kV/66:.1f}%), difference {100*(kV/66-kN/148):.1f} points, p = {I.mw_indicator_p(kN, 148, kV, 66):.3f}")
QR1: NAc 16/148 (10.8%), VP 7/66 (10.6%), difference -0.2 points, p = 0.964
QR2: NAc 12/148 (8.1%), VP 8/66 (12.1%), difference 4.0 points, p = 0.353
QR3: NAc 10/148 (6.8%), VP 8/66 (12.1%), difference 5.4 points, p = 0.193

Result: reproduced. The test finds no difference in QR-coding shares in phase 2 (NAc 8.1%, VP 12.1%, p = 0.35) or phase 3 (6.8% and 12.1%, p = 0.19).

preference-balance and nac-noreward-preference¶

Preference is the sign of the difference of mean spike counts in the coding bin. Reading O11: (a) the Wilcoxon signed-rank test, across the coding neurons of a type, of each neuron's difference; (b) the sign test on the signs alone (binomial, two-sided). Both two-sided.

In [50]:
def pref(col_p, col_d, area, positive_is):
    g = D[(D.area == area) & (D[col_p] < 0.01)]
    d = g[col_d].values
    k = int((d > 0).sum()) if positive_is == "pos" else int((d < 0).sum())
    pa = ss.wilcoxon(d).pvalue if len(d) > 1 else np.nan
    pb = ss.binomtest(int((d > 0).sum()), len(d), 0.5).pvalue if len(d) else np.nan
    return dict(n=len(d), k=k, pct=100 * k / max(len(d), 1), p_signed_rank=pa, p_sign_test=pb)

rows = []
for typ, cp, cd, exp in [("state, prefer tone A", "p_state", "d_state", {"NAc": 48, "VP": 36}),
                         ("action command, prefer left", "p_ac", "d_ac", {"NAc": 53, "VP": 50}),
                         ("action, prefer left", "p_act", "d_act", {"NAc": 57, "VP": 50})]:
    for a in ["NAc", "VP"]:
        r = pref(cp, cd, a, "pos"); r.update(type=typ, area=a, expected=exp[a], ok=abs(r["pct"] - exp[a]) <= 0.1 * exp[a])
        rows.append(r)
PB = pd.DataFrame(rows)[["type", "area", "n", "k", "pct", "expected", "ok", "p_signed_rank", "p_sign_test"]]
PB["departure found O11 (a)"] = PB.p_signed_rank < 0.05
print(PB.round(4).to_string(index=False))
print("state with O14 (b):", [pref("p_state_all", "d_state_all", a, "pos") for a in ["NAc", "VP"]])
                       type area  n  k     pct  expected    ok  p_signed_rank  p_sign_test  departure found O11 (a)
       state, prefer tone A  NAc 80 38 47.5000        48  True         0.4315       0.7376                    False
       state, prefer tone A   VP 33 12 36.3636        36  True         0.4368       0.1628                    False
action command, prefer left  NAc 15  7 46.6667        53 False         0.8469       1.0000                    False
action command, prefer left   VP 14  7 50.0000        50  True         0.8077       1.0000                    False
        action, prefer left  NAc 63 34 53.9683        57  True         0.8106       0.6147                    False
        action, prefer left   VP 26 13 50.0000        50  True         0.9007       1.0000                    False
state with O14 (b): [{'n': 83, 'k': 44, 'pct': 53.01204819277108, 'p_signed_rank': np.float64(0.8952501455769576), 'p_sign_test': np.float64(0.6608836477612154)}, {'n': 37, 'k': 16, 'pct': 43.24324324324324, 'p_signed_rank': np.float64(0.7769683328515384), 'p_sign_test': np.float64(0.5113757815852296)}]

Result: reproduced. None of the six signed-rank tests finds a departure from 50% (p 0.43 to 0.90), nor the sign tests (p 0.16 to 1.0). Five of the six percentages are within tolerance (47.5, 36.4, 50.0, 54.0 and 50.0%); NAc action command is 46.7% against 53%.

In [51]:
rows = []
for a, e in [("NAc", 73), ("VP", 56)]:
    r = pref("p_rew", "d_rew", a, "neg"); r.update(area=a, expected=e, ok=abs(r["pct"] - e) <= 0.1 * e); rows.append(r)
NR = pd.DataFrame(rows)
print(NR.round(6).to_string(index=False))
print("(k = neurons with a larger response to the no-reward tone)")
 n  k       pct  p_signed_rank  p_sign_test area  expected   ok
96 70 72.916667       0.003150     0.000008  NAc        73 True
44 23 52.272727       0.299441     0.880396   VP        56 True
(k = neurons with a larger response to the no-reward tone)

Result: partially reproduced. 70 of 96 NAc reward-coding units (72.9%) respond more to the no-reward tone, against 73%; the sign test gives p = 8e-06, but the signed-rank test of O11 (a) gives p = 0.0032, not p < 0.0001, so the NAc part does not hold under every reading. The VP part holds: 23 of 44 (52.3%, expected 56%) and no departure from 50% (signed-rank p = 0.30).

core-shell-no-difference¶

Splitting NAc neurons into tentative core and shell groups by electrode position, the same analyses find no difference between core and shell neurons.

The units carry only Area (NAc or VP) and an electrode number; the electrode table's location is NAc or VP, and no field gives the core or shell, the bundle's coordinates or the depth of each session.

In [52]:
locs = set()
for s in S:
    locs |= set(s["units"].area.unique())
print("unit Area values in the dataset:", sorted(locs))
print("units per electrode number in the NAc (1-16):", UN[UN.area == "NAc"].merge(
    pd.concat([s["units"].assign(sess=k)[["sess", "unit_name", "electrode"]] for k, s in enumerate(S)]),
    left_on=["sess", "unit"], right_on=["sess", "unit_name"]).electrode.value_counts().sort_index().to_dict())
unit Area values in the dataset: ['NAc', 'VP']
units per electrode number in the NAc (1-16): {1: 4, 2: 19, 3: 4, 4: 4, 5: 8, 6: 7, 7: 10, 8: 2, 9: 14, 10: 13, 11: 13, 12: 12, 13: 9, 14: 15, 15: 13, 16: 1}

Result: blocked (metadata insufficient). The dataset labels units only NAc or VP; nothing assigns NAc units to core or shell, and the bundle positions of Fig. 6 and the per-session depths are not in the files, so the groups cannot be formed.

Regression (Fig. 8C, 8D)¶

By regression on the block reward probabilities, QL-coding neurons are 9, 10 and 7% of NAc neurons and 15, 24 and 26% of VP neurons in phases 1 to 3, and QR-coding neurons 11, 9 and 6% (NAc) and 9, 17 and 14% (VP).

y = b0 + b1 QL + b2 QR (and, for Fig. 8D, b1 (QL + QR) + b2 (QL - QR)), QL and QR the block's reward probabilities as fractions, the last 20 choice trials of each block, t test at p < 0.01.

In [53]:
def pct_table(exp):
    rows = []
    for (a, v), e in exp.items():
        k = count(v, a); n = NREG[a]
        rows.append(dict(area=a, var=v, count=k, pct=100 * k / n, expected_pct=e,
                         ok=abs(100 * k / n - e) <= max(0.1 * e, 100 * 2 / n)))
    return pd.DataFrame(rows)
EXP_R = {("NAc", "rQL1"): 9, ("NAc", "rQL2"): 10, ("NAc", "rQL3"): 7, ("VP", "rQL1"): 15, ("VP", "rQL2"): 24, ("VP", "rQL3"): 26,
         ("NAc", "rQR1"): 11, ("NAc", "rQR2"): 9, ("NAc", "rQR3"): 6, ("VP", "rQR1"): 9, ("VP", "rQR2"): 17, ("VP", "rQR3"): 14}
RA = pct_table(EXP_R)
print(RA.round(1).to_string(index=False)); print("matching:", int(RA.ok.sum()), "of 12")
area  var  count  pct  expected_pct    ok
 NAc rQL1     18 12.2             9 False
 NAc rQL2     17 11.5            10 False
 NAc rQL3     14  9.5             7 False
  VP rQL1     12 18.2            15 False
  VP rQL2     17 25.8            24  True
  VP rQL3     16 24.2            26  True
 NAc rQR1     17 11.5            11  True
 NAc rQR2     12  8.1             9  True
 NAc rQR3     15 10.1             6 False
  VP rQR1      7 10.6             9  True
  VP rQR2      9 13.6            17 False
  VP rQR3     11 16.7            14  True
matching: 6 of 12

Result: not reproduced. 6 of the 12 percentages are within tolerance (±2 neurons or 10%). NAc QL is 12.2, 11.5 and 9.5% against 9, 10 and 7%, VP QL in phase 1 18.2% against 15%, NAc QR in phase 3 10.1% against 6%, and VP QR in phase 2 13.6% against 17%.

In [54]:
for v in ["rQL1", "rQL2", "rQL3"]:
    kN, kV = count(v, "NAc"), count(v, "VP")
    print(f"{v}: NAc {100*kN/148:.1f}%, VP {100*kV/66:.1f}%, p = {I.mw_indicator_p(kN, 148, kV, 66):.4f}")
rQL1: NAc 12.2%, VP 18.2%, p = 0.2425
rQL2: NAc 11.5%, VP 25.8%, p = 0.0085
rQL3: NAc 9.5%, VP 24.2%, p = 0.0041

Result: reproduced. In the regression analysis QL-coding units are a larger share of VP than of NAc units in phase 2 (25.8% against 11.5%, p = 0.0085) and phase 3 (24.2% against 9.5%, p = 0.0041), both p < 0.01.

In [55]:
tot_reg = sum(count(f"r{q}{ph}", a) for q in ["QL", "QR"] for ph in [1, 2, 3] for a in ["NAc", "VP"])
tot_blk = sum(count(f"{q}{ph}", a) for q in ["QL", "QR"] for ph in [1, 2, 3] for a in ["NAc", "VP"])
print("QL + QR coding, phases 1-3, both regions: regression", tot_reg, " block comparison", tot_blk)
for ph in [2, 3]:
    print(f"phase {ph}: QL share VP - NAc, regression {100*(count(f'rQL{ph}','VP')/66 - count(f'rQL{ph}','NAc')/148):.1f} points,"
          f" block comparison {100*(count(f'QL{ph}','VP')/66 - count(f'QL{ph}','NAc')/148):.1f} points")
print("paper, regression total (percent to counts): ", round(sum(np.array([9, 10, 7, 11, 9, 6]) * 1.48) + sum(np.array([15, 24, 26, 9, 17, 14]) * 0.66)),
      " block comparison: ", 9 + 7 + 11 + 7 + 12 + 12 + 12 + 6 + 11 + 14 + 8 + 7)
QL + QR coding, phases 1-3, both regions: regression 165  block comparison 133
phase 2: QL share VP - NAc, regression 14.3 points, block comparison 6.5 points
phase 3: QL share VP - NAc, regression 14.8 points, block comparison 12.3 points
paper, regression total (percent to counts):  146  block comparison:  116

Result: reproduced. The regression finds 165 QL- and QR-coding units over phases 1 to 3 and both regions, the block comparison 133; in both analyses the VP has the larger QL share in phases 2 and 3 (by 14.3 and 14.8 points in the regression, 6.5 and 12.3 in the block comparison).

In [56]:
EXP_V = {("NAc", "V1"): 12, ("NAc", "V2"): 8, ("NAc", "V3"): 8, ("VP", "V1"): 18, ("VP", "V2"): 20, ("VP", "V3"): 20}
RV = pct_table(EXP_V)
RV["p NAc vs VP"] = [I.mw_indicator_p(count(v, "NAc"), 148, count(v, "VP"), 66) for v in RV["var"]]
print(RV.round(4).to_string(index=False)); print("matching:", int(RV.ok.sum()), "of 6")
area var  count     pct  expected_pct    ok  p NAc vs VP
 NAc  V1     19 12.8378            12  True       0.8732
 NAc  V2     16 10.8108             8 False       0.5532
 NAc  V3     16 10.8108             8 False       0.0801
  VP  V1      9 13.6364            18 False       0.8732
  VP  V2      9 13.6364            20 False       0.5532
  VP  V3     13 19.6970            20  True       0.0801
matching: 2 of 6

Result: not reproduced. 2 of the 6 percentages match (NAc phase 1, 12.8%; VP phase 3, 19.7%), and the VP share is not significantly higher in phase 2 (13.6% against 10.8%, p = 0.55) or phase 3 (19.7% against 10.8%, p = 0.080).

In [57]:
EXP_P = {("NAc", "P1"): 10, ("NAc", "P2"): 9, ("NAc", "P3"): 7, ("VP", "P1"): 11, ("VP", "P2"): 15, ("VP", "P3"): 14}
RP = pct_table(EXP_P)
print(RP.round(1).to_string(index=False)); print("matching:", int(RP.ok.sum()), "of 6")
area var  count  pct  expected_pct    ok
 NAc  P1     11  7.4            10 False
 NAc  P2     13  8.8             9  True
 NAc  P3     11  7.4             7  True
  VP  P1      9 13.6            11  True
  VP  P2     11 16.7            15  True
  VP  P3     11 16.7            14  True
matching: 5 of 6

Result: partially reproduced. 5 of the 6 percentages match (NAc 8.8 and 7.4% in phases 2 and 3; VP 13.6, 16.7 and 16.7%); NAc phase 1 is 7.4% against 10%.

fig8-above-chance¶

Every coding population of Figure 8 is larger than expected by chance.

One-sided binomial test of each count against the chance level O10: (a) 0.01, the test level; (b) for the action-value, state-value and policy populations, 0.01 x 0.99 (one comparison significant and the other not).

In [58]:
pops = [("state", "p_state"), ("action command", "p_ac"), ("action", "p_act"), ("reward", "p_rew")]
rows = []
for a in ["NAc", "VP"]:
    for lab, col in pops:
        k = int((D.loc[D.area == a, col] < 0.01).sum())
        rows.append(dict(area=a, pop=lab, k=k, chance_a=0.01, chance_b=0.01))
    for v in [f"{q}{ph}" for q in ["QL", "QR", "rQL", "rQR", "V", "P"] for ph in [1, 2, 3]]:
        rows.append(dict(area=a, pop=v, k=count(v, a), chance_a=0.01, chance_b=0.0099))
CH = pd.DataFrame(rows)
CH["n"] = CH.area.map(NREG)
CH["p_a"] = [ss.binomtest(k, n, c, alternative="greater").pvalue for k, n, c in zip(CH.k, CH.n, CH.chance_a)]
CH["p_b"] = [ss.binomtest(k, n, c, alternative="greater").pvalue for k, n, c in zip(CH.k, CH.n, CH.chance_b)]
print(CH.to_string(index=False, float_format=lambda v: f"{v:.3g}"))
for r in ["a", "b"]:
    print(f"O10 ({r}): {int((CH['p_' + r] < 0.01).sum())} of {len(CH)} populations with p < 0.01 ({100 * (CH['p_' + r] < 0.01).mean():.0f}%)")
area            pop  k  chance_a  chance_b   n       p_a       p_b
 NAc          state 80      0.01      0.01 148 7.33e-118 7.33e-118
 NAc action command 15      0.01      0.01 148  3.77e-11  3.77e-11
 NAc         action 63      0.01      0.01 148  1.97e-84  1.97e-84
 NAc         reward 96      0.01      0.01 148 1.91e-152 1.91e-152
 NAc            QL1 13      0.01    0.0099 148  4.35e-09  3.86e-09
 NAc            QL2 15      0.01    0.0099 148  3.77e-11  3.28e-11
 NAc            QL3 11      0.01    0.0099 148  3.64e-07   3.3e-07
 NAc            QR1 16      0.01    0.0099 148  3.14e-12  2.71e-12
 NAc            QR2 12      0.01    0.0099 148  4.15e-08  3.73e-08
 NAc            QR3 10      0.01    0.0099 148  2.91e-06  2.66e-06
 NAc           rQL1 18      0.01    0.0099 148   1.8e-14  1.52e-14
 NAc           rQL2 17      0.01    0.0099 148  2.45e-13  2.09e-13
 NAc           rQL3 14      0.01    0.0099 148   4.2e-10   3.7e-10
 NAc           rQR1 17      0.01    0.0099 148  2.45e-13  2.09e-13
 NAc           rQR2 12      0.01    0.0099 148  4.15e-08  3.73e-08
 NAc           rQR3 15      0.01    0.0099 148  3.77e-11  3.28e-11
 NAc             V1 19      0.01    0.0099 148  1.24e-15  1.03e-15
 NAc             V2 16      0.01    0.0099 148  3.14e-12  2.71e-12
 NAc             V3 16      0.01    0.0099 148  3.14e-12  2.71e-12
 NAc             P1 11      0.01    0.0099 148  3.64e-07   3.3e-07
 NAc             P2 13      0.01    0.0099 148  4.35e-09  3.86e-09
 NAc             P3 11      0.01    0.0099 148  3.64e-07   3.3e-07
  VP          state 33      0.01      0.01  66  5.23e-48  5.23e-48
  VP action command 14      0.01      0.01  66  4.76e-15  4.76e-15
  VP         action 26      0.01      0.01  66  1.12e-34  1.12e-34
  VP         reward 44      0.01      0.01  66  1.47e-71  1.47e-71
  VP            QL1  9      0.01    0.0099  66  2.21e-08  2.03e-08
  VP            QL2 11      0.01    0.0099  66  6.48e-11  5.83e-11
  VP            QL3 13      0.01    0.0099  66  1.25e-13   1.1e-13
  VP            QR1  7      0.01    0.0099  66  4.65e-06  4.35e-06
  VP            QR2  8      0.01    0.0099  66  3.43e-07  3.18e-07
  VP            QR3  8      0.01    0.0099  66  3.43e-07  3.18e-07
  VP           rQL1 12      0.01    0.0099  66  2.99e-12  2.66e-12
  VP           rQL2 17      0.01    0.0099  66  1.58e-19  1.34e-19
  VP           rQL3 16      0.01    0.0099  66  5.33e-18  4.56e-18
  VP           rQR1  7      0.01    0.0099  66  4.65e-06  4.35e-06
  VP           rQR2  9      0.01    0.0099  66  2.21e-08  2.03e-08
  VP           rQR3 11      0.01    0.0099  66  6.48e-11  5.83e-11
  VP             V1  9      0.01    0.0099  66  2.21e-08  2.03e-08
  VP             V2  9      0.01    0.0099  66  2.21e-08  2.03e-08
  VP             V3 13      0.01    0.0099  66  1.25e-13   1.1e-13
  VP             P1  9      0.01    0.0099  66  2.21e-08  2.03e-08
  VP             P2 11      0.01    0.0099  66  6.48e-11  5.83e-11
  VP             P3 11      0.01    0.0099  66  6.48e-11  5.83e-11
O10 (a): 44 of 44 populations with p < 0.01 (100%)
O10 (b): 44 of 44 populations with p < 0.01 (100%)

Result: reproduced. All 44 populations of Fig. 8B to 8D are larger than chance under both chance levels (largest p = 4.7e-06).

Mutual information (Fig. 9)¶

MI between spike-count class and each binary event, 500 ms windows every 100 ms, aligned to cue onset (Fig. 9A, -1 to 3 s) and to center-hole exit (Fig. 9B, -2 to 4 s), per second, averaged over the neurons of a region. Events: state (tone A or B, choice and no-choice trials), action and reward (choice trials), previous reward (the outcome of the previous choice trial, choice trials after the first), QL and QR from F-Q with time-varying parameters (Table 2 sigmas, O1 a, O5 a) binarized at the median (O13: predictive or posterior mean; median per session or over all sessions). Window placement O12: (a) centred on each time point, (b) ending at it, (c) starting at it. Threshold: the second largest of 100 region averages with random binary events, drawn (O12) with probability 0.5 or with the frequency of the real event in the session (one seeded generator per alignment and placement).

In [59]:
TIMES = {"cue": np.round(np.arange(-1.0, 3.0001, 0.1), 2), "exit": np.round(np.arange(-2.0, 4.0001, 0.1), 2),
         "entry": np.round(np.arange(-2.0, 1.0001, 0.1), 2)}   # entry: reward only, aligned to each trial's L/R entry
# QL and QR from the F-Q (variable) runs with the Table 2 sigmas under every reading of O1 and O5; the
# O1 (a), O5 (a) run keeps the short names ("QL a session"), the others carry the reading ("QL a session O1b O5a").
qvals = {}
for form in [0, 1]:
    for clip in [0, 1]:
        fqrun = tab2runs[("FQ", form, clip)]
        tag = () if (form, clip) == (0, 0) else (f"O1{'ab'[form]} O5{'ab'[clip]}",)
        for o13, idx in [("a", 1), ("b", 2)]:
            for med in ["session", "all"]:
                for j, q in [(0, "QL"), (1, "QR")]:
                    allv = np.concatenate([x[:, j] for x in fqrun[idx]])
                    qvals[(q, o13, med) + tag] = [(x[:, j] > (np.median(x[:, j]) if med == "session" else np.median(allv))).astype(np.int64)
                                                  for x in fqrun[idx]]
sess_of_seq = {int(s.sess.values[0]): n for n, s in enumerate(seqs)}

MI, THR = {}, {}
t0 = time.time()
for ai, align in enumerate(["cue", "exit", "entry"]):
    for pi, place in enumerate(["centre", "end", "start"]):
        rng = np.random.default_rng(100 + 10 * ai + pi)
        acc = {}      # (event, area) -> list of curves
        racc = {}     # (event, rand reading, area) -> (100, n_windows) sums
        nun = {"NAc": 0, "VP": 0}
        for k, s in enumerate(S):
            if len(s["units"]) == 0:
                continue
            t = T[T.sess == k].sort_values("start_time").reset_index(drop=True)
            sset = (t.choice | t.nochoice).values
            cset = t.choice.values
            al = {"cue": t.tone_on_time, "exit": t.pokeC_off_time, "entry": t.action_on_time}[align].values
            if align == "entry":
                cset = cset & np.isfinite(al)
                ev = {"reward": (cset, (t.reward.values[cset] == 1).astype(np.int64))}
            else:
                ev = {"state": (sset, (t.state.values[sset] == 2).astype(np.int64)),
                      "action": (cset, (t.action.values[cset] == 2).astype(np.int64)),
                      "reward": (cset, (t.reward.values[cset] == 1).astype(np.int64))}
                n = sess_of_seq[k]
                prev = np.r_[0, seqs[n].r.values[:-1]].astype(np.int64)
                ev["prev_reward"] = (cset, prev)
                for key, v in qvals.items():
                    ev[" ".join(key)] = (cset, v[n])
            for _, u in s["units"].iterrows():
                st = np.sort(u.spike_times)
                Call = I.window_counts_matrix(st, al, TIMES[align], place)
                K = {"s": I.classes_matrix(Call[sset]), "c": I.classes_matrix(Call[cset])}
                Kp = I.classes_matrix(Call[cset][1:])
                for e, (m, x) in ev.items():
                    if e == "prev_reward":
                        curve = I.mi_curve(Kp, x[1:])
                    else:
                        curve = I.mi_curve(K["s" if m is sset else "c"], x)
                    acc.setdefault((e, u.area), []).append(curve)
                nun[u.area] += 1
                # random events
                for rep in range(100):
                    us = rng.random(sset.sum()); uc = rng.random(cset.sum())
                    for e, (m, x) in ev.items():
                        if e.startswith("QR") or (e.startswith("QL") and e != "QL a session"):
                            continue
                        uu = us if m is sset else uc
                        for rr, p in [("half", 0.5), ("freq", x.mean())]:
                            if rr == "half" and e not in ("state", "action", "prev_reward") and align != "entry":
                                continue  # p = 0.5 threshold is shared by all events of a trial set
                            xr = (uu < p).astype(np.int64)
                            c = I.mi_curve(Kp, xr[1:]) if e == "prev_reward" else I.mi_curve(K["s" if m is sset else "c"], xr)
                            key = (e, rr, u.area)
                            if key not in racc:
                                racc[key] = np.zeros((100, len(c)))
                            racc[key][rep] += c
        for (e, area), curves in acc.items():
            MI[(align, place, e, area)] = np.mean(curves, axis=0)
        for (e, rr, area), sums in racc.items():
            THR[(align, place, e, rr, area)] = np.sort(sums / nun[area], axis=0)[-2]
        print(f"{align} {place}: {nun} units, {time.time() - t0:.0f} s")

def thr(align, place, e, rr, area):
    """Threshold for event e: the p = 0.5 reading uses the curves of the event's trial set."""
    if rr == "half":
        base = "state" if e == "state" else ("prev_reward" if e == "prev_reward" else "action")
        if align == "entry":
            base = "reward"
        return THR[(align, place, base, "half", area)]
    if e.startswith("Q"):
        return THR[(align, place, "QL a session", "freq", area)]
    return THR[(align, place, e, "freq", area)]

fig, axs = plt.subplots(2, 2, figsize=(11, 6), sharey=True)
for i, area in enumerate(["NAc", "VP"]):
    for j, align in enumerate(["cue", "exit"]):
        a_ = axs[i, j]
        for e in ["state", "action", "reward", "prev_reward", "QL a session", "QR a session"]:
            a_.plot(TIMES[align], MI[(align, "centre", e, area)], label=e)
        a_.plot(TIMES[align], thr(align, "centre", "action", "half", area), "k", lw=0.8, label="threshold")
        a_.set(title=f"{area}, aligned to {align}", xlabel="time (s)", ylabel="MI (bits/s)")
axs[0, 0].legend(fontsize=7)
plt.tight_layout(); plt.show()
print("range of all MI curves (plotted and not):", min(v.min() for v in MI.values()).round(4), "to", max(v.max() for v in MI.values()).round(4), "bits/s")
cue centre: {'NAc': 148, 'VP': 66} units, 12 s
cue end: {'NAc': 148, 'VP': 66} units, 20 s
cue start: {'NAc': 148, 'VP': 66} units, 29 s
exit centre: {'NAc': 148, 'VP': 66} units, 41 s
exit end: {'NAc': 148, 'VP': 66} units, 53 s
exit start: {'NAc': 148, 'VP': 66} units, 65 s
entry centre: {'NAc': 148, 'VP': 66} units, 67 s
entry end: {'NAc': 148, 'VP': 66} units, 69 s
entry start: {'NAc': 148, 'VP': 66} units, 71 s
No description has been provided for this image
range of all MI curves (plotted and not): -0.0012 to 0.1404 bits/s

fig9-state-information¶

Information about the trial type (state) in the NAc and VP rises right after cue onset and again after center-hole exit.

In [60]:
rows = []
for place in ["centre", "end", "start"]:
    for rr in ["half", "freq"]:
        for area in ["NAc", "VP"]:
            tc = TIMES["cue"]; mc = MI[("cue", place, "state", area)]; thc = thr("cue", place, "state", rr, area)
            after = (tc > 0) & (tc <= 0.5); before = (tc >= -0.5) & (tc < 0)
            te_ = TIMES["exit"]; me = MI[("exit", place, "state", area)]; the = thr("exit", place, "state", rr, area)
            at0 = me[np.argmin(np.abs(te_))]
            post = te_ > 0
            locmax = [i for i in np.where(post)[0][1:-1] if me[i] >= me[i - 1] and me[i] >= me[i + 1] and me[i] > the[i] and me[i] > at0]
            rows.append(dict(O12_window=place, O12_random=rr, area=area, cue_max_after=mc[after].max(),
                             cue_above_thr=bool((mc[after] > thc[after]).any()), cue_max_before=mc[before].max(),
                             rises=bool(mc[after].max() > mc[before].max()), exit_at0=at0,
                             exit_peak_after=me[post].max(), exit_peak_time=te_[post][me[post].argmax()],
                             exit_local_max_ok=len(locmax) > 0))
F9s = pd.DataFrame(rows)
F9s["holds"] = F9s.cue_above_thr & F9s.rises & F9s.exit_local_max_ok
print(F9s.round(4).to_string(index=False))
O12_window O12_random area  cue_max_after  cue_above_thr  cue_max_before  rises  exit_at0  exit_peak_after  exit_peak_time  exit_local_max_ok  holds
    centre       half  NAc         0.0565           True          0.0023   True    0.0341           0.1185             1.8               True   True
    centre       half   VP         0.0369           True          0.0039   True    0.0379           0.1095             1.1               True   True
    centre       freq  NAc         0.0565           True          0.0023   True    0.0341           0.1185             1.8               True   True
    centre       freq   VP         0.0369           True          0.0039   True    0.0379           0.1095             1.1               True   True
       end       half  NAc         0.0395           True          0.0007   True    0.0403           0.1207             2.1               True   True
       end       half   VP         0.0299           True          0.0003   True    0.0330           0.1084             1.3               True   True
       end       freq  NAc         0.0395           True          0.0007   True    0.0403           0.1207             2.1               True   True
       end       freq   VP         0.0299           True          0.0003   True    0.0330           0.1084             1.3               True   True
     start       half  NAc         0.0572           True          0.0267   True    0.0383           0.1207             1.6               True   True
     start       half   VP         0.0377           True          0.0217   True    0.0388           0.1084             0.8               True   True
     start       freq  NAc         0.0572           True          0.0267   True    0.0383           0.1207             1.6               True   True
     start       freq   VP         0.0377           True          0.0217   True    0.0388           0.1084             0.8               True   True

Result: reproduced. Under all 12 readings, in both regions, state information within 0.5 s after cue onset (0.030 to 0.057 bits/s) is above threshold and above its level before the cue (0.0003 to 0.027), and the curve aligned to center-hole exit has a later local maximum above threshold (peak 0.108 to 0.121 bits/s at 0.8 to 2.1 s) that exceeds its value at the exit (0.033 to 0.040).

fig9-action-information¶

Information about the chosen action is very weak before center-hole exit, rises rapidly after it, and peaks around entry to the L or R hole.

In [61]:
med_rt = float(np.median(rt))
rows = []
for place in ["centre", "end", "start"]:
    for area in ["NAc", "VP"]:
        te_ = TIMES["exit"]; m = MI[("exit", place, "action", area)]
        pk = te_[m.argmax()]
        rows.append(dict(O12_window=place, area=area, mean_before_exit=m[te_ < 0].mean(), peak=m.max(), peak_time=pk,
                         weak_before=m[te_ < 0].mean() < m.max() / 5, peak_near_entry=(pk > 0) and abs(pk - med_rt) <= 0.5))
F9a = pd.DataFrame(rows); F9a["holds"] = F9a.weak_before & F9a.peak_near_entry
print(f"median reaction time {med_rt:.3f} s (the random-event reading does not enter this criterion)")
print(F9a.round(4).to_string(index=False))
median reaction time 0.754 s (the random-event reading does not enter this criterion)
O12_window area  mean_before_exit   peak  peak_time  weak_before  peak_near_entry  holds
    centre  NAc            0.0031 0.0584        0.5         True             True   True
    centre   VP            0.0049 0.0480        0.9         True             True   True
       end  NAc            0.0031 0.0589        0.8         True             True   True
       end   VP            0.0044 0.0478        1.1         True             True   True
     start  NAc            0.0054 0.0589        0.3         True             True   True
     start   VP            0.0085 0.0478        0.6         True             True   True

Result: reproduced. Under all three window placements and in both regions, action information before center exit averages 0.003 to 0.009 bits/s, under a fifth of the peak (0.048 to 0.059), and peaks 0.3 to 1.1 s after the exit, within 0.5 s of the median reaction time of 0.754 s.

fig9-reward-information¶

Information about reward rises when the reward or no-reward tone is presented at L or R entry, then decreases gradually but lasts until the next trial.

"Before the L or R entry" is read as the windows that end before the median reaction time; "around the next cue onset" as the time points within 0.5 s of cue onset (cue-aligned curve of the previous reward).

In [62]:
rows = []
for place in ["centre", "end", "start"]:
    w0 = I.window_starts(TIMES["exit"], place)
    for rr in ["half", "freq"]:
        for area in ["NAc", "VP"]:
            te_ = TIMES["exit"]; m = MI[("exit", place, "reward", area)]; th = thr("exit", place, "reward", rr, area)
            pre = w0 + I.MI_WIDTH <= med_rt; postw = w0 >= med_rt
            tc = TIMES["cue"]; mp = MI[("cue", place, "prev_reward", area)]; thp = thr("cue", place, "prev_reward", rr, area)
            near = np.abs(tc) <= 0.5
            rows.append(dict(O12_window=place, O12_random=rr, area=area, below_before=bool((m[pre] <= th[pre]).all()),
                             max_before=m[pre].max(), thr_max_before=th[pre].max(),
                             n_pre_windows_above=int((m[pre] > th[pre]).sum()), n_pre_windows=int(pre.sum()), above_after=bool((m[postw] > th[postw]).any()), peak=m.max(),
                             peak_time=te_[m.argmax()], value_at_4s=m[-1], prev_reward_near_cue=mp[near].max(),
                             prev_reward_above=bool((mp[near] > thp[near]).any())))
F9r = pd.DataFrame(rows); F9r["holds"] = F9r.below_before & F9r.above_after & F9r.prev_reward_above
print(F9r.round(4).to_string(index=False))

# Variant: reward MI aligned to each trial's own L/R entry (not the median reaction time); windows that end
# at or before the entry are "before entry".
rows = []
for place in ["centre", "end", "start"]:
    w0 = I.window_starts(TIMES["entry"], place)
    pre = w0 + I.MI_WIDTH <= 0
    for rr in ["half", "freq"]:
        for area in ["NAc", "VP"]:
            m = MI[("entry", place, "reward", area)]; th = thr("entry", place, "reward", rr, area)
            rows.append(dict(O12_window=place, O12_random=rr, area=area, n_pre_windows=int(pre.sum()),
                             n_pre_windows_above=int((m[pre] > th[pre]).sum()), max_before=m[pre].max(), thr_max_before=th[pre].max(),
                             max_after_entry=m[TIMES["entry"] > 0].max(), ratio_max_before_to_peak_after_exit=m[pre].max() / MI[("exit", place, "reward", area)].max()))
F9e = pd.DataFrame(rows); F9e["below_before"] = F9e.n_pre_windows_above == 0
print("\nreward MI aligned to each trial's L/R entry:")
print(F9e.round(4).to_string(index=False))
O12_window O12_random area  below_before  max_before  thr_max_before  n_pre_windows_above  n_pre_windows  above_after   peak  peak_time  value_at_4s  prev_reward_near_cue  prev_reward_above  holds
    centre       half  NAc         False      0.0044          0.0023                   20             26         True 0.0932        1.6       0.0667                0.0160               True  False
    centre       half   VP         False      0.0070          0.0026                   26             26         True 0.1060        1.5       0.0397                0.0190               True  False
    centre       freq  NAc         False      0.0044          0.0023                   19             26         True 0.0932        1.6       0.0667                0.0160               True  False
    centre       freq   VP         False      0.0070          0.0030                   26             26         True 0.1060        1.5       0.0397                0.0190               True  False
       end       half  NAc         False      0.0039          0.0023                   20             28         True 0.0935        1.9       0.0737                0.0163               True  False
       end       half   VP         False      0.0069          0.0033                   28             28         True 0.1060        1.8       0.0372                0.0190               True  False
       end       freq  NAc         False      0.0039          0.0022                   20             28         True 0.0935        1.9       0.0737                0.0163               True  False
       end       freq   VP         False      0.0069          0.0031                   28             28         True 0.1060        1.8       0.0372                0.0190               True  False
     start       half  NAc         False      0.0039          0.0023                   16             23         True 0.0935        1.4       0.0634                0.0146               True  False
     start       half   VP         False      0.0064          0.0031                   23             23         True 0.1060        1.3       0.0438                0.0150               True  False
     start       freq  NAc         False      0.0039          0.0023                   17             23         True 0.0935        1.4       0.0634                0.0146               True  False
     start       freq   VP         False      0.0064          0.0025                   23             23         True 0.1060        1.3       0.0438                0.0150               True  False

reward MI aligned to each trial's L/R entry:
O12_window O12_random area  n_pre_windows  n_pre_windows_above  max_before  thr_max_before  max_after_entry  ratio_max_before_to_peak_after_exit  below_before
    centre       half  NAc             18                   14      0.0053          0.0025           0.1391                               0.0565         False
    centre       half   VP             18                   18      0.0060          0.0026           0.1291                               0.0564         False
    centre       freq  NAc             18                   15      0.0053          0.0022           0.1391                               0.0565         False
    centre       freq   VP             18                   18      0.0060          0.0029           0.1291                               0.0564         False
       end       half  NAc             21                   17      0.0063          0.0025           0.1404                               0.0673         False
       end       half   VP             21                   21      0.0067          0.0026           0.1270                               0.0633         False
       end       freq  NAc             21                   16      0.0063          0.0023           0.1404                               0.0673         False
       end       freq   VP             21                   21      0.0067          0.0028           0.1270                               0.0633         False
     start       half  NAc             16                   12      0.0063          0.0023           0.1404                               0.0673         False
     start       half   VP             16                   16      0.0063          0.0026           0.1276                               0.0599         False
     start       freq  NAc             16                   12      0.0063          0.0024           0.1404                               0.0673         False
     start       freq   VP             16                   16      0.0063          0.0029           0.1276                               0.0599         False

Result: not reproduced. Reward information rises after L or R entry to a peak of 0.093 (NAc) and 0.106 (VP) bits/s at 1.3 to 1.9 s after center exit, decreases, and the previous trial's reward is above threshold around the next cue onset (0.015 to 0.019 bits/s) under all 12 readings. It is not below threshold before L or R entry, as the criterion asks: in 16 to 28 of the 23 to 28 windows before the median entry, reward information (up to 0.0044 NAc and 0.0070 VP) exceeds the threshold (up to 0.0023 and 0.0033), though it is under a tenth of the peak. Aligned to each trial's own entry, 12 to 21 of 16 to 21 windows before entry are above threshold (up to 0.0063 and 0.0067 bits/s, 5.6 to 6.7% of the peak). The criterion gives no partial rule. Whether the paper says the information is absent before the tone is asked of a reader (questions/001641.yaml).

fig9-action-value-information-low¶

Information about the action values QL and QR is above the significance threshold in the NAc and VP but low and without clear peaks, while state, action and reward information are robust.

In [63]:
RUNS = {"O1 a, O5 a": "", "O1 a, O5 b": " O1a O5b", "O1 b, O5 a": " O1b O5a", "O1 b, O5 b": " O1b O5b"}
rows = []
for run, suf in RUNS.items():
    for place in ["centre", "end", "start"]:
        for rr in ["half", "freq"]:
            for o13 in ["a", "b"]:
                for med in ["session", "all"]:
                    for area in ["NAc", "VP"]:
                        r = dict(run=run, O12_window=place, O12_random=rr, O13=o13, median=med, area=area)
                        others = max(MI[(al, place, e, area)].max() for al in ["cue", "exit"] for e in ["state", "action", "reward"])
                        oks = []
                        for q in ["QL", "QR"]:
                            cur = np.concatenate([MI[(al, place, f"{q} {o13} {med}{suf}", area)] for al in ["cue", "exit"]])
                            th = np.concatenate([thr(al, place, f"{q} {o13} {med}{suf}", rr, area) for al in ["cue", "exit"]])
                            frac = (cur > th).mean()
                            r[f"{q} frac above"] = frac; r[f"{q} max"] = cur.max(); r[f"{q} max/median"] = cur.max() / np.median(cur)
                            oks.append((frac > 0.5, cur.max() < others, cur.max() < 2 * np.median(cur)))
                        r["peak of state/action/reward"] = others
                        r["above (most windows)"] = all(o[0] for o in oks); r["below others"] = all(o[1] for o in oks); r["flat"] = all(o[2] for o in oks)
                        rows.append(r)
F9q = pd.DataFrame(rows)
F9q["holds"] = F9q["above (most windows)"] & F9q["below others"] & F9q["flat"]
print(F9q[F9q.run == "O1 a, O5 a"].round(4).to_string(index=False))
print("\nby run of F-Q (O1, O5):")
print(F9q.groupby("run").agg(readings=("holds", "size"), holds=("holds", "sum"), min_frac_QL=("QL frac above", "min"),
                             min_frac_QR=("QR frac above", "min"), max_QL=("QL max", "max"), max_QR=("QR max", "max"),
                             max_ratio_QL=("QL max/median", "max"), max_ratio_QR=("QR max/median", "max")).round(4).to_string())
print("readings where it holds, by run and O13:", F9q.groupby(["run", "O13"]).holds.sum().to_dict(), "of 24 each")
print("readings where it holds:", int(F9q.holds.sum()), "of", len(F9q), "| comparison with other events holds in", int(F9q["below others"].sum()))
       run O12_window O12_random O13  median area  QL frac above  QL max  QL max/median  QR frac above  QR max  QR max/median  peak of state/action/reward  above (most windows)  below others  flat  holds
O1 a, O5 a     centre       half   a session  NAc            1.0  0.0126         1.6549            1.0  0.0170         1.7626                       0.1185                  True          True  True   True
O1 a, O5 a     centre       half   a session   VP            1.0  0.0262         1.2393            1.0  0.0243         1.4070                       0.1095                  True          True  True   True
O1 a, O5 a     centre       half   a     all  NAc            1.0  0.0129         1.6472            1.0  0.0153         1.7271                       0.1185                  True          True  True   True
O1 a, O5 a     centre       half   a     all   VP            1.0  0.0291         1.1342            1.0  0.0271         1.3376                       0.1095                  True          True  True   True
O1 a, O5 a     centre       half   b session  NAc            1.0  0.0215         2.6758            1.0  0.0312         3.1521                       0.1185                  True          True False  False
O1 a, O5 a     centre       half   b session   VP            1.0  0.0336         1.6135            1.0  0.0336         1.9405                       0.1095                  True          True  True   True
O1 a, O5 a     centre       half   b     all  NAc            1.0  0.0206         2.6852            1.0  0.0240         2.7542                       0.1185                  True          True False  False
O1 a, O5 a     centre       half   b     all   VP            1.0  0.0338         1.3035            1.0  0.0327         1.6114                       0.1095                  True          True  True   True
O1 a, O5 a     centre       freq   a session  NAc            1.0  0.0126         1.6549            1.0  0.0170         1.7626                       0.1185                  True          True  True   True
O1 a, O5 a     centre       freq   a session   VP            1.0  0.0262         1.2393            1.0  0.0243         1.4070                       0.1095                  True          True  True   True
O1 a, O5 a     centre       freq   a     all  NAc            1.0  0.0129         1.6472            1.0  0.0153         1.7271                       0.1185                  True          True  True   True
O1 a, O5 a     centre       freq   a     all   VP            1.0  0.0291         1.1342            1.0  0.0271         1.3376                       0.1095                  True          True  True   True
O1 a, O5 a     centre       freq   b session  NAc            1.0  0.0215         2.6758            1.0  0.0312         3.1521                       0.1185                  True          True False  False
O1 a, O5 a     centre       freq   b session   VP            1.0  0.0336         1.6135            1.0  0.0336         1.9405                       0.1095                  True          True  True   True
O1 a, O5 a     centre       freq   b     all  NAc            1.0  0.0206         2.6852            1.0  0.0240         2.7542                       0.1185                  True          True False  False
O1 a, O5 a     centre       freq   b     all   VP            1.0  0.0338         1.3035            1.0  0.0327         1.6114                       0.1095                  True          True  True   True
O1 a, O5 a        end       half   a session  NAc            1.0  0.0127         1.6689            1.0  0.0168         1.7237                       0.1207                  True          True  True   True
O1 a, O5 a        end       half   a session   VP            1.0  0.0264         1.2460            1.0  0.0234         1.3448                       0.1084                  True          True  True   True
O1 a, O5 a        end       half   a     all  NAc            1.0  0.0126         1.5484            1.0  0.0153         1.6812                       0.1207                  True          True  True   True
O1 a, O5 a        end       half   a     all   VP            1.0  0.0292         1.1348            1.0  0.0264         1.3133                       0.1084                  True          True  True   True
O1 a, O5 a        end       half   b session  NAc            1.0  0.0215         2.7800            1.0  0.0320         3.4306                       0.1207                  True          True False  False
O1 a, O5 a        end       half   b session   VP            1.0  0.0359         1.7432            1.0  0.0324         1.8748                       0.1084                  True          True  True   True
O1 a, O5 a        end       half   b     all  NAc            1.0  0.0203         2.8157            1.0  0.0245         2.9605                       0.1207                  True          True False  False
O1 a, O5 a        end       half   b     all   VP            1.0  0.0347         1.3311            1.0  0.0322         1.5578                       0.1084                  True          True  True   True
O1 a, O5 a        end       freq   a session  NAc            1.0  0.0127         1.6689            1.0  0.0168         1.7237                       0.1207                  True          True  True   True
O1 a, O5 a        end       freq   a session   VP            1.0  0.0264         1.2460            1.0  0.0234         1.3448                       0.1084                  True          True  True   True
O1 a, O5 a        end       freq   a     all  NAc            1.0  0.0126         1.5484            1.0  0.0153         1.6812                       0.1207                  True          True  True   True
O1 a, O5 a        end       freq   a     all   VP            1.0  0.0292         1.1348            1.0  0.0264         1.3133                       0.1084                  True          True  True   True
O1 a, O5 a        end       freq   b session  NAc            1.0  0.0215         2.7800            1.0  0.0320         3.4306                       0.1207                  True          True False  False
O1 a, O5 a        end       freq   b session   VP            1.0  0.0359         1.7432            1.0  0.0324         1.8748                       0.1084                  True          True  True   True
O1 a, O5 a        end       freq   b     all  NAc            1.0  0.0203         2.8157            1.0  0.0245         2.9605                       0.1207                  True          True False  False
O1 a, O5 a        end       freq   b     all   VP            1.0  0.0347         1.3311            1.0  0.0322         1.5578                       0.1084                  True          True  True   True
O1 a, O5 a      start       half   a session  NAc            1.0  0.0127         1.6627            1.0  0.0168         1.7289                       0.1207                  True          True  True   True
O1 a, O5 a      start       half   a session   VP            1.0  0.0264         1.2416            1.0  0.0234         1.3900                       0.1084                  True          True  True   True
O1 a, O5 a      start       half   a     all  NAc            1.0  0.0126         1.5822            1.0  0.0153         1.7546                       0.1207                  True          True  True   True
O1 a, O5 a      start       half   a     all   VP            1.0  0.0292         1.1350            1.0  0.0264         1.3325                       0.1084                  True          True  True   True
O1 a, O5 a      start       half   b session  NAc            1.0  0.0215         2.5086            1.0  0.0320         2.9540                       0.1207                  True          True False  False
O1 a, O5 a      start       half   b session   VP            1.0  0.0359         1.7114            1.0  0.0324         1.8694                       0.1084                  True          True  True   True
O1 a, O5 a      start       half   b     all  NAc            1.0  0.0203         2.3648            1.0  0.0245         2.5053                       0.1207                  True          True False  False
O1 a, O5 a      start       half   b     all   VP            1.0  0.0347         1.3219            1.0  0.0322         1.5522                       0.1084                  True          True  True   True
O1 a, O5 a      start       freq   a session  NAc            1.0  0.0127         1.6627            1.0  0.0168         1.7289                       0.1207                  True          True  True   True
O1 a, O5 a      start       freq   a session   VP            1.0  0.0264         1.2416            1.0  0.0234         1.3900                       0.1084                  True          True  True   True
O1 a, O5 a      start       freq   a     all  NAc            1.0  0.0126         1.5822            1.0  0.0153         1.7546                       0.1207                  True          True  True   True
O1 a, O5 a      start       freq   a     all   VP            1.0  0.0292         1.1350            1.0  0.0264         1.3325                       0.1084                  True          True  True   True
O1 a, O5 a      start       freq   b session  NAc            1.0  0.0215         2.5086            1.0  0.0320         2.9540                       0.1207                  True          True False  False
O1 a, O5 a      start       freq   b session   VP            1.0  0.0359         1.7114            1.0  0.0324         1.8694                       0.1084                  True          True  True   True
O1 a, O5 a      start       freq   b     all  NAc            1.0  0.0203         2.3648            1.0  0.0245         2.5053                       0.1207                  True          True False  False
O1 a, O5 a      start       freq   b     all   VP            1.0  0.0347         1.3219            1.0  0.0322         1.5522                       0.1084                  True          True  True   True

by run of F-Q (O1, O5):
            readings  holds  min_frac_QL  min_frac_QR  max_QL  max_QR  max_ratio_QL  max_ratio_QR
run                                                                                              
O1 a, O5 a        48     36          1.0          1.0  0.0359  0.0336        2.8157        3.4306
O1 a, O5 b        48     36          1.0          1.0  0.0380  0.0352        2.8819        3.2549
O1 b, O5 a        48     42          1.0          1.0  0.0410  0.0416        2.4321        2.3292
O1 b, O5 b        48     30          1.0          1.0  0.0311  0.0332        2.9097        2.5224
readings where it holds, by run and O13: {('O1 a, O5 a', 'a'): 24, ('O1 a, O5 a', 'b'): 12, ('O1 a, O5 b', 'a'): 24, ('O1 a, O5 b', 'b'): 12, ('O1 b, O5 a', 'a'): 24, ('O1 b, O5 a', 'b'): 18, ('O1 b, O5 b', 'a'): 24, ('O1 b, O5 b', 'b'): 6} of 24 each
readings where it holds: 144 of 192 | comparison with other events holds in 192

Result: partially reproduced. Across the four F-Q runs (O1 and O5) and all 192 readings, QL and QR information exceeds the threshold in every window and peaks at up to 0.042 bits/s, under the peaks of state, action and reward information (0.108 to 0.121). With the predictive mean (O13 a) it has no clear peak in all 96 readings (in the O1 a, O5 a run the maximum is at most 1.76 times the median). With the posterior mean after e(t) (O13 b), which includes trial t's choice and reward, the largest maximum in each run is 2.4 to 3.4 times the median and the flatness part fails in 48 of 96 readings (in the O1 a, O5 a run, all 12 failures are NAc). The comparison with the other events holds under every reading, which is the criterion's partial rule. Under O13 (a) all three parts hold, which alone would be reproduced; as for fig5-variable-models-best, reading the partial rule as holding when its condition holds under every reading, instead of blocking because readings give different outcomes, is an assumption (attempt record).

action-information-outlasts-reward-peak¶

Information about the chosen action in the NAc and VP lasts beyond the peak of reward information.

In [64]:
rows = []
for place in ["centre", "end", "start"]:
    for rr in ["half", "freq"]:
        for area in ["NAc", "VP"]:
            te_ = TIMES["exit"]; ma = MI[("exit", place, "action", area)]; mr = MI[("exit", place, "reward", area)]
            th = thr("exit", place, "action", rr, area)
            ip = int(mr.argmax()); i5 = int(np.argmin(np.abs(te_ - (te_[ip] + 0.5))))
            rows.append(dict(O12_window=place, O12_random=rr, area=area, reward_peak_time=te_[ip], action_at_peak=ma[ip],
                             thr_at_peak=th[ip], action_at_peak_plus_0_5=ma[i5], thr_plus_0_5=th[i5],
                             holds=bool(ma[ip] > th[ip] and ma[i5] > th[i5])))
F9o = pd.DataFrame(rows)
print(F9o.round(4).to_string(index=False))
O12_window O12_random area  reward_peak_time  action_at_peak  thr_at_peak  action_at_peak_plus_0_5  thr_plus_0_5  holds
    centre       half  NAc               1.6          0.0298       0.0019                   0.0193        0.0020   True
    centre       half   VP               1.5          0.0320       0.0025                   0.0263        0.0019   True
    centre       freq  NAc               1.6          0.0298       0.0020                   0.0193        0.0020   True
    centre       freq   VP               1.5          0.0320       0.0020                   0.0263        0.0020   True
       end       half  NAc               1.9          0.0272       0.0019                   0.0203        0.0017   True
       end       half   VP               1.8          0.0310       0.0019                   0.0238        0.0022   True
       end       freq  NAc               1.9          0.0272       0.0019                   0.0203        0.0015   True
       end       freq   VP               1.8          0.0310       0.0019                   0.0238        0.0021   True
     start       half  NAc               1.4          0.0272       0.0022                   0.0203        0.0018   True
     start       half   VP               1.3          0.0310       0.0024                   0.0238        0.0026   True
     start       freq  NAc               1.4          0.0272       0.0021                   0.0203        0.0017   True
     start       freq   VP               1.3          0.0310       0.0027                   0.0238        0.0027   True

Result: reproduced. Under all 12 readings, in both regions, action information at the time of the reward peak (0.027 to 0.032 bits/s) and 0.5 s later (0.019 to 0.026) is above its threshold (at most 0.0027).

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
trial-counts reproduced
block-structure reproduced
reaction-time reproduced
tone-discrimination-errors not reproduced
fig2b-reward-stronger-than-noreward reproduced
fig2b-two-back-history blocked (methods underspecified: O8 readings disagree)
fig2c-sequence-frequencies reproduced
fig2c-reward-effects-fade reproduced
fig2d-switching reproduced
fig2e-persevering reproduced
fig3-lsq-switching partially reproduced
table1-lsq-parameters not reproduced
fig5-markov-accuracy blocked (methods underspecified: O3 readings disagree)
fig5-constant-models blocked (methods underspecified: the local matching law with Qi(1) = 0 is degenerate)
fig5-variable-models-best partially reproduced
fig5-fq-dfq-beat-all-models blocked (methods underspecified: readings disagree)
fig5-fq-dfq-no-difference blocked (methods underspecified: readings disagree)
binary-prediction-accuracy reproduced
table2-ml-parameters not reproduced
table3-parameter-averages blocked (methods underspecified: O1 readings disagree; asked of a reader)
fig4-strategy-tracking reproduced
suppdata1-choice-vs-q-difference reproduced
neuron-counts reproduced
firing-rates reproduced
fig8b-state-coding blocked (methods underspecified: O14 readings disagree)
fig8b-action-value-psth partially reproduced
fig8b-action-command-coding not reproduced
fig8b-action-coding reproduced
fig8b-reward-coding reproduced
fig8b-nac-vp-same-event-coding not reproduced
fig8b-ql-vp-higher partially reproduced
fig8b-qr-no-region-difference reproduced
preference-balance reproduced
nac-noreward-preference partially reproduced
core-shell-no-difference blocked (metadata insufficient)
fig8c-regression-action-value not reproduced
fig8c-ql-vp-higher reproduced
fig8c-regression-detects-more reproduced
fig8d-state-value-vp-higher not reproduced
fig8d-policy partially reproduced
fig8-above-chance reproduced
fig9-state-information reproduced
fig9-action-information reproduced
fig9-reward-information not reproduced (asked of a reader)
fig9-action-value-information-low partially reproduced
action-information-outlasts-reward-peak reproduced

How the analysis differs from the paper's. The paper links no code and its display equations are missing from the text, so the Q update (O1), the training split (O3), the parameter search (O4), the drift bounds (O5) and other details were run under every reading the claims file lists. As the claims file directs, a claim whose method readings give different outcomes is blocked as methods underspecified, with every reading shown; the readings best supported by the paper are the split whose training set has the paper's 19,986 choice trials (O3 a) and the update form under which Table 2's values are near the optimum (O1 a). The sigma search used 1000 particles and a 4 x 4 grid, and the chosen sigmas were run with 5000 particles; a 5000-particle search on a wider grid (main split, O1 a) and six seeds of the filter were run as checks. The local matching law is degenerate with the Methods' Qi(1) = 0 and was also run with non-zero initial values, which the paper does not give. Two claims (fig5-variable-models-best, fig9-action-value-information-low) are partially reproduced on a reading of their partial rule: its condition holds under every reading, though some readings alone would give reproduced; this is marked as an assumption. The resampling scheme of the particle filter (systematic) and the class borders for ties in the MI analysis are standard choices.

What was found about the dataset. The dataset holds what the paper describes: 70 sessions, 6 rats, 39,175 choice, 12,707 no-choice and 8329 error trials (exactly as reported; the paper's total of 60,221 is 10 more than its parts and than the 60,211 trials here), and 148 NAc and 66 VP units (18 files have no units table). The trial result codes are not described in the files, so the error types cannot be told apart with certainty; the no-reward tone is stored in the SpTone Err series with the error tone, and the error tone lasts about 2 s where the paper says 1000 ms. Some cue tones are shorter than the task's 1000 to 2000 ms, probably because the tone stops when the rat leaves the center hole early; cue duration marks some such trials, but not a cue cut short after 1 s. Three choice trials have a negative reaction time. The units are labelled only NAc or VP, without the core or shell assignment the paper uses. No recording is deposited twice.