Reproducing van Dijk and Fenton (2018) from CRCNS hc-17¶

Paper: van Dijk MT, Fenton AA (2018) On how the dentate gyrus contributes to memory discrimination. Neuron 98, 832-845, doi:10.1016/j.neuron.2018.04.018. The claims file (claims/dijk-2018.yaml) was written from the version of record with its STAR Methods and Supplemental Information.

Dataset: CRCNS hc-17 (doi:10.6080/K0Q23XDV), streamed from the public S3 bucket crcnsarchive at hc-17/live/data.zip. CRCNS data sets are not versioned, so the version is recorded as unversioned, with the MD5 sum of the one file read, data.zip, from the data set's checksums.md5: b577c885e9daf70a7a0af4ff67d11c51. The bucket holds this one published copy under live/ (no old/ folder), so it is the version pinned; the paper cites the data set's DOI and no version.

What the data set holds: TS files (spike times with the position sample of each spike) for every sorted unit and session, in the room and arena frames; the paper's lists of place cells and putative interneurons (Excel files); Tracker files of the place avoidance sessions, with shock zone and shock state in the shock-on sessions. It holds no waveforms, no LFP and none of the optogenetic experiments.

Choices the claims file leaves open, and what this notebook does (each reading is run where it could change an outcome):

  • Spatial grid: 32 x 32 bins of 8 tracker pixels, the grid of the data set's own maps (checked below). The paper's 1.5 cm/pixel is about 1.4 cm in the arena and 2 cm in the environment boxes on this grid.
  • Rate maps for place fields (M2 is open on smoothing): fields, field masks and field rates use smoothed maps, the data set's own smoothed maps (RmSm) in the environment experiment and our smoothing (a 3 x 3 kernel close to the authors') in the place avoidance task, where four sessions have deposited maps on another grid; the unsmoothed readings (a) and (b) are shown. Stability, rates, information and coherence use the unsmoothed maps.
  • M11 session pairs: reading (b) is adopted (all pretraining-training pairs for addition, both training sessions against conflict for relocation), as the Results say that "analysis of the shock addition and the shock replication manipulations used data collected during both the training 1 and training 2 sessions"; reading (a) is shown beside it.
  • M6 location size for Ipos: 8-pixel bins adopted (the paper's stated analysis resolution); 16-pixel blocks shown.
  • M10 episodes: consecutive 5-s windows adopted (STAR Methods, Overdispersion: "computing z for each 5 s episode, during which exp was greater than the average firing of the cell"); field-entry windows shown.
  • Pair classes: Kendall's own test on both pretraining sessions joined, reading (a)(iii), adopted for the class-dependent claims; every reading shown.
Claim Tested or blocked
fig1-single-field-proportion, fig1-field-number-scaling, fig1b-stability-dg-below-ca-removal, fig1-rate-remapping-no-difference, fig1c-field-rate-change-no-difference, tables1-dg-ca-similar tested
fig2c-cfos-reduced, fig2d-conflict-deficit, fig2-quadrant-preference, fig2e-shock-off-deficit blocked, data missing (optogenetic mice not in the data set)
fig3b-avoidance-learning, fig3b-shock-off-avoidance, speed-no-difference, tables2-firing-quality-similar tested
fig3c-stability-no-difference, fig3c-replication-vs-relocation, fig3c-stability-vs-environment, fig3d-rate-remapping-task, interneuron-rate-remapping tested
ipos-speed-correlation, fig4b-room-preference-pretraining, fig4c-ipos-before-avoidance, fig4d-room-maps-uncorrelated, fig4d-room-ipos-near-active-zone tested
figs2a-pc-pairs-no-change, standardized-rates-no-difference, overdispersion-similar, network-consistency-overall, fig5b-network-consistency-zones tested
fig5d1-pc-int-tau-no-difference, fig5d2-pc-int-change-relocation, pc-int-fraction-increased, figs2bc-other-timescales, pc-int-pair-classes, fig5d3-independent-pairs-increase, fig5d4-positive-pairs-decrease, negative-pairs-no-change tested
fig5e1-correlation-near-zone, fig5e2-e4-change-near-zone, correlation-not-speed, fig5e1-inset-rate-change-near-zone, fig6b-correlation-before-avoidance, fig6c-no-increase-before-errors, fig6-inset-rate-changes tested
In [1]:
import re, time, resource, warnings
import numpy as np, pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import hc17 as H
warnings.filterwarnings("ignore")
pd.set_option("display.width", 200); pd.set_option("display.max_columns", 40); pd.set_option("display.max_rows", 200)
T0 = time.time()
idx = H.ts_index()
ses_av, cells_av, AV = H.load_avoidance(idx)
ses_env, cells_env, ENV = H.load_environment(idx)
print(f"loaded in {time.time()-T0:.0f} s; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1e6:.2f} GB")
loaded in 59 s; peak memory 0.31 GB

Data check¶

In [2]:
print("TS unit files by task and frame:", idx.groupby(["env", "frame"]).size().to_dict())
print("\nPaper's class lists (data/*.xlsx):")
print("  environment task: DG place cells", (cells_env.region == "DG").sum(), "on days", sorted(cells_env[cells_env.region == "DG"].day.unique()))
print("                    CA place cells", (cells_env.region == "CA").sum(), "on days", sorted(cells_env[cells_env.region == "CA"].day.unique()))
print("  mice, DG:", sorted(set(d.split("_")[1] for d in cells_env[cells_env.region == "DG"].day)),
      " CA:", sorted(set(d.split("_")[1] for d in cells_env[cells_env.region == "CA"].day)))
print("  place avoidance: place cells", (cells_av.cls == "pc").sum(), "interneurons", (cells_av.cls == "int").sum())
print(cells_av.groupby(["mouse", "cls"]).size().unstack())
print("\nPlace avoidance sessions holding TS files (kind, units of the lists found, samples, fs):")
rows = []
for s, v in AV.items():
    p = v["pos"]
    rows.append(dict(session=s, mouse=v["meta"]["mouse"], kind=v["meta"]["kind"], units=len(v["units"]),
                     samples=len(p["rx"]), fs=round(p["fs"], 3), minutes=round(len(p["rx"]) / p["fs"] / 60, 1),
                     tracked=round(H.tracked(p["rx"], p["ry"]).mean(), 3),
                     room_xy_range=(int(p["rx"][p["rx"] > 0].min()), int(p["rx"].max()), int(p["ry"][p["ry"] > 0].min()), int(p["ry"].max())),
                     same_spikes_room_arena=p["n_ar_spikes_equal"], pos_mismatch=len(p.get("mismatch", []))))
SAV = pd.DataFrame(rows); print(SAV.to_string())
print("\nsessions per mouse and kind:"); print(SAV.groupby(["mouse", "kind"]).size().unstack(fill_value=0))
print("\nEnvironment sessions on the listed days (condition, units, minutes):")
rows = []
for s, v in ENV.items():
    p = v["pos"]
    rows.append(dict(session=s, day=v["meta"]["day"], condition=v["meta"]["condition"], units=len(v["units"]),
                     minutes=round(len(p["rx"]) / p["fs"] / 60, 1), fs=round(p["fs"], 3),
                     x_range=(int(p["rx"][p["rx"] > 0].min()), int(p["rx"].max())),
                     y_range=(int(p["ry"][p["ry"] > 0].min()), int(p["ry"].max())), pos_mismatch=len(p.get("mismatch", []))))
SENV = pd.DataFrame(rows); print(SENV.to_string())
print("\ncondition counts:", SENV.condition.value_counts().to_dict())
TS unit files by task and frame: {(False, 'Ar'): 649, (False, 'Rm'): 649, (True, 'Rm'): 1235}

Paper's class lists (data/*.xlsx):
  environment task: DG place cells 45 on days ['140731_WT15', '140801_WT15', '140803_WT15', '140803_WT16', '140829_WT15', '140831_WT15', '140831_WT16', '150716_WT19', '151211_WT26', '151211_WT27']
                    CA place cells 20 on days ['140731_WT15', '140803_WT15', '140829_WT15', '140831_WT13', '140831_WT15', '150709_WT18']
  mice, DG: ['WT15', 'WT16', 'WT19', 'WT26', 'WT27']  CA: ['WT13', 'WT15', 'WT18']
  place avoidance: place cells 42 interneurons 21
cls    int  pc
mouse         
WT15     3   6
WT16     2   5
WT19     3   7
WT20     5   7
WT26     4  10
WT27     4   7

Place avoidance sessions holding TS files (kind, units of the lists found, samples, fs):
                        session mouse         kind  units  samples     fs  minutes  tracked       room_xy_range  same_spikes_room_arena  pos_mismatch
0                      WT15Hab1  WT15  pretraining      9    36000  30.02     20.0    1.000  (36, 209, 41, 212)                    True             0
1                    WT15Ini1_2  WT15    training1      9    35996  30.02     20.0    1.000  (13, 239, 15, 237)                    True             0
2                    WT15Ini2_1  WT15    training2      9    35994  30.02     20.0    0.999  (26, 236, 19, 233)                    True             0
3                   WT16Conf1_1  WT16     conflict      7    36000  30.02     20.0    1.000  (16, 235, 20, 197)                    True             0
4                      WT16Hab1  WT16  pretraining      7    36002  30.02     20.0    1.000  (39, 209, 40, 213)                    True             0
5                    WT16Ini2_1  WT16    training2      7    36002  30.02     20.0    1.000  (12, 238, 16, 235)                    True             0
6            150720_WT19Conf1_2  WT19     conflict     10    35994  30.02     20.0    0.999  (40, 207, 42, 212)                    True             0
7               150720_WT19Hab1  WT19  pretraining     10    35979  30.02     20.0    0.999  (23, 233, 18, 238)                    True             0
8             150720_WT19Ini1_2  WT19    training1     10    35999  30.02     20.0    0.997  (48, 208, 43, 212)                    True             0
9             150720_WT19Ini2_2  WT19    training2     10    35993  30.02     20.0    0.998  (24, 233, 20, 237)                    True             0
10     150929_PIC_WT20_2Hab2_DG  WT20  pretraining     12    36000  30.02     20.0    0.999  (11, 240, 13, 243)                    True             0
11     150929_PIC_WT20_3Hab3_DG  WT20  pretraining     12    36002  30.02     20.0    0.999  (11, 240, 12, 243)                    True             0
12   150929_PIC_WT20_4Ini1_2_DG  WT20    training1     12    35992  30.02     20.0    0.977  (20, 240, 19, 244)                    True             0
13   150929_PIC_WT20_5Ini2_2_DG  WT20    training2     12    35996  29.96     20.0    0.992  (11, 239, 26, 244)                    True             0
14  150929_PIC_WT20_6Conf1_2_DG  WT20     conflict     12    36002  30.02     20.0    0.985  (11, 241, 14, 243)                    True             0
15           151215_WT26Conf1_2  WT26     conflict     14    35992  29.96     20.0    0.999  (15, 241, 13, 243)                    True             0
16              151215_WT26Hab1  WT26  pretraining     14    36002  30.02     20.0    0.996  (13, 242, 13, 242)                    True             0
17              151215_WT26Hab2  WT26  pretraining     14    35998  30.02     20.0    0.999  (13, 241, 14, 242)                    True             0
18            151215_WT26Ini1_2  WT26    training1     14    35988  30.02     20.0    0.999  (12, 242, 13, 243)                    True             0
19            151215_WT26Ini2_2  WT26    training2     14    35996  29.96     20.0    1.000  (13, 242, 15, 244)                    True             0
20           151215_WT27Conf1_2  WT27     conflict     11    36000  30.02     20.0    1.000  (11, 241, 13, 243)                    True             0
21              151215_WT27Hab1  WT27  pretraining     11    35988  30.02     20.0    1.000  (12, 241, 13, 244)                    True             0
22              151215_WT27Hab2  WT27  pretraining     11    35998  30.02     20.0    1.000  (13, 240, 15, 244)                    True             0
23            151215_WT27Ini1_2  WT27    training1     11    36000  30.02     20.0    0.999  (12, 239, 13, 243)                    True             0
24            151215_WT27Ini2_2  WT27    training2     11    35999  30.02     20.0    1.000  (13, 241, 14, 241)                    True             0

sessions per mouse and kind:
kind   conflict  pretraining  training1  training2
mouse                                             
WT15          0            1          1          1
WT16          1            1          0          1
WT19          1            1          1          1
WT20          1            2          1          1
WT26          1            2          1          1
WT27          1            2          1          1

Environment sessions on the listed days (condition, units, minutes):
                                   session          day condition  units  minutes      fs    x_range    y_range  pos_mismatch
0             140731_WT15_circleintestbox1  140731_WT15  standard      4     20.0  30.020  (75, 237)  (57, 211)             0
1                     140731_WT15_testbox1  140731_WT15   removed      4     20.0  30.020  (52, 254)  (43, 225)             0
2                     140731_WT15_testbox2  140731_WT15   removed      4     20.0  30.020  (52, 254)  (43, 225)             0
3             140801_WT15_circleintestbox1  140801_WT15  standard      6     20.0  30.020  (77, 230)  (59, 216)             0
4             140801_WT15_circleintestbox2  140801_WT15  standard      6     20.0  30.020  (80, 236)  (60, 211)             0
5             140801_WT15_circleintestbox3  140801_WT15  standard      6     20.0  30.020  (66, 217)  (47, 185)             0
6                  140801_WT15_diffcircle1  140801_WT15     other      6     20.0  30.020  (62, 207)  (43, 185)             0
7                     140801_WT15_testbox1  140801_WT15   removed      6     30.0  30.020  (52, 241)  (41, 223)             0
8                     140801_WT15_testbox2  140801_WT15   removed      6     30.0  30.020  (56, 245)  (38, 225)             0
9             140803_WT15_circleintestbox1  140803_WT15  standard      8     20.0  30.020  (63, 224)  (34, 192)             0
10            140803_WT15_circleintestbox2  140803_WT15  standard      8     20.0  30.020  (51, 214)  (34, 188)             0
11  140803_WT15_rotated90dcircleintestbox1  140803_WT15   rotated      8     20.0  30.020  (62, 219)  (45, 196)             0
12  140803_WT15_rotated90dcircleintestbox2  140803_WT15   rotated      8     20.0  30.020  (70, 220)  (51, 190)             0
13                    140803_WT15_testbox1  140803_WT15   removed      8     30.0  30.020  (40, 240)  (16, 213)             0
14            140803_WT16_circleintestbox1  140803_WT16  standard      4     20.0  30.020  (66, 225)  (35, 192)             0
15            140803_WT16_circleintestbox2  140803_WT16  standard      4     20.0  30.020  (57, 213)  (34, 188)             0
16  140803_WT16_rotated90dcircleintestbox1  140803_WT16   rotated      4     20.0  29.959  (62, 220)  (44, 196)             0
17  140803_WT16_rotated90dcircleintestbox2  140803_WT16   rotated      4     20.0  30.020  (60, 221)  (43, 194)             0
18                    140803_WT16_testbox1  140803_WT16   removed      4     30.0  30.020  (40, 242)  (19, 215)             0
19       140829_WT15_90drotcircleintestbox  140829_WT15   rotated      3     10.0  30.020  (69, 221)  (42, 201)             0
20      140829_WT15_90drotcircleintestbox2  140829_WT15   rotated      3     20.0  30.020  (69, 225)  (40, 196)             0
21             140829_WT15_circleintestbox  140829_WT15  standard      3     20.0  30.020  (64, 227)  (49, 199)             0
22             140831_WT13_circleintestbox  140831_WT13  standard      2     20.0  30.020  (56, 224)  (47, 191)             0
23                     140831_WT13_testbox  140831_WT13   removed      2     10.0  30.020  (43, 251)  (17, 222)             0
24       140831_WT15_90drotcircleintestbox  140831_WT15   rotated      6     20.0  30.020  (66, 219)  (46, 203)             0
25            140831_WT15_circleintestbox1  140831_WT15  standard      6     20.0  30.020  (62, 230)  (48, 192)             0
26            140831_WT15_circleintestbox2  140831_WT15  standard      6     20.0  30.020  (60, 227)  (49, 193)             0
27                    140831_WT15_testbox1  140831_WT15   removed      6     20.0  29.960  (47, 245)  (18, 219)             0
28                    140831_WT15_testbox2  140831_WT15   removed      6     20.0  30.020  (44, 245)  (17, 222)             0
29       140831_WT16_90drotcircleintestbox  140831_WT16   rotated      4     20.0  30.020  (66, 220)  (47, 204)             0
30            140831_WT16_circleintestbox1  140831_WT16  standard      4     20.0  30.020  (62, 230)  (48, 191)             0
31            140831_WT16_circleintestbox2  140831_WT16  standard      4     20.0  29.960  (59, 227)  (48, 193)             0
32                    140831_WT16_testbox1  140831_WT16   removed      4     20.0  30.020  (46, 247)  (19, 223)             0
33                    140831_WT16_testbox2  140831_WT16   removed      4     20.0  30.020  (43, 249)  (17, 221)             0
34      150709_WT18_90drotcircleintestbox1  150709_WT18   rotated     13     20.0  29.960  (48, 216)  (52, 196)             0
35      150709_WT18_90drotcircleintestbox2  150709_WT18   rotated     13     20.0  30.020  (49, 215)  (52, 198)             0
36            150709_WT18_circleintestbox1  150709_WT18  standard     13     20.0  30.020  (58, 211)  (45, 203)             0
37            150709_WT18_circleintestbox3  150709_WT18  standard     13     20.0  30.020  (58, 210)  (45, 203)             0
38            150709_WT18_circleintestbox4  150709_WT18  standard     13     20.0  30.020  (58, 209)  (45, 206)             0
39            150709_WT18_circleintestbox5  150709_WT18  standard     13     20.0  30.020  (58, 208)  (45, 205)             0
40                    150709_WT18_testbox1  150709_WT18   removed     13     20.0  29.960  (36, 241)  (16, 216)             0
41      150716_WT19_90drotcircleintestbox1  150716_WT19   rotated      8     20.0  30.020  (52, 220)  (53, 200)             0
42            150716_WT19_circleintestbox3  150716_WT19  standard      8     20.0  30.020  (58, 208)  (47, 207)             0
43            150716_WT19_circleintestbox4  150716_WT19  standard      8     20.0  30.020  (61, 212)  (46, 206)             0
44            150716_WT19_circleintestbox5  150716_WT19  standard      8     20.0  30.020  (61, 212)  (47, 206)             0
45                    150716_WT19_testbox1  150716_WT19   removed      8     20.0  30.020  (40, 245)  (16, 216)             0
46      151211_WT26_90drotcircleintestbox1  151211_WT26   rotated      4     20.0  30.020  (49, 204)  (43, 206)             0
47            151211_WT26_circleintestbox1  151211_WT26  standard      4     20.0  30.020  (42, 209)  (49, 199)             0
48            151211_WT26_circleintestbox2  151211_WT26  standard      4     20.0  30.020  (42, 208)  (48, 200)             0
49                    151211_WT26_testbox1  151211_WT26   removed      4     20.0  30.020  (26, 228)  (25, 228)             0
50                151211_WT26_transferbin1  151211_WT26     other      4     20.0  30.020  (68, 190)  (64, 186)             0
51                151211_WT26_transferbin2  151211_WT26     other      4     20.0  30.020  (67, 189)  (63, 184)             0
52      151211_WT27_90drotcircleintestbox1  151211_WT27   rotated      3     20.0  30.020  (49, 203)  (43, 206)             0
53            151211_WT27_circleintestbox1  151211_WT27  standard      3     20.0  30.020  (42, 209)  (48, 199)             0
54            151211_WT27_circleintestbox2  151211_WT27  standard      3     20.0  30.020  (42, 208)  (49, 200)             0
55                    151211_WT27_testbox1  151211_WT27   removed      3     20.0  30.020  (26, 228)  (25, 229)             0
56                151211_WT27_transferbin1  151211_WT27     other      3     20.0  30.020  (68, 189)  (64, 186)             0
57                151211_WT27_transferbin2  151211_WT27     other      3     20.0  30.020  (67, 189)  (64, 185)             0

condition counts: {'standard': 25, 'removed': 15, 'rotated': 13, 'other': 5}
In [3]:
# Units and clocks. Spike times are in 100-us units; each spike is filed under a position sample.
# Check that spike times fall in their sample, i.e. that position and spikes share a clock.
rows = []
for s, v in list(AV.items()) + list(ENV.items()):
    p = v["pos"]
    for u, d in list(v["units"].items())[:1]:
        k, t = d["spike_sample"], d["spike_times"]
        if len(k) < 20:
            continue
        fit = np.polyfit(k, t, 1)
        resid = t - np.polyval(fit, k)
        rows.append(dict(session=s, fs_header=p["fs"], fs_from_spikes=1e4 / fit[0],
                         resid_ms_p1=np.percentile(resid, 1) / 10, resid_ms_p99=np.percentile(resid, 99) / 10,
                         monotonic=bool(np.all(np.diff(t) >= 0))))
CLK = pd.DataFrame(rows)
print(CLK.describe().round(3).to_string())
print("sessions where spike times are not sorted:", CLK[~CLK.monotonic].session.tolist())
       fs_header  fs_from_spikes  resid_ms_p1  resid_ms_p99
count     83.000          83.000       83.000        83.000
mean      30.014          30.004      -47.766        46.819
std        0.018           0.003       30.184        24.698
min       29.959          29.991     -198.400        14.947
25%       30.020          30.002      -58.443        30.289
50%       30.020          30.004      -44.642        43.173
75%       30.020          30.006      -27.237        61.805
max       30.020          30.007      -15.447       130.532
sessions where spike times are not sorted: []
In [4]:
# Scale of the spatial grid. Tracker headers give 6.4 pixels/cm for the 40-cm arena; the data
# set's own maps (data/TIME, data/SPIKE) hold 1024 values, a 32 x 32 grid of 8 tracker pixels.
for name in ["data/TIME/ROOM/151215_WT26Hab1_spikes_cl-fix", "data/TIME/ROOM/EnvironmentalTask/151211_WT26_circleintestbox1_spikes_cl-fix"]:
    v = np.array(H.read(name).split(), float)
    print(name, "values:", len(v), "sum (s):", round(v.sum(), 1))
# compare the deposited dwell map with ours on the 8-pixel grid
p = AV["151215_WT26Hab1"]["pos"]
occ = H.occupancy(p["rx"], p["ry"], p["fs"])
dep = np.array(H.read("data/TIME/ROOM/151215_WT26Hab1_spikes_cl-fix").split(), float)
best = max(((np.corrcoef(occ.ravel(order=o), dep)[0, 1], o) for o in "CF"))
print("our 32x32 dwell map vs deposited TIME map: r =", round(best[0], 4), "order", best[1], "; total s ours", round(occ.sum(), 1))
for lab, sel in [("arena (place avoidance)", SAV), ("environment, circle", SENV[SENV.condition != "removed"]), ("environment, box", SENV[SENV.condition == "removed"])]:
    w = np.array([r[1] - r[0] for r in (sel.room_xy_range.map(lambda q: (q[0], q[1])) if "room_xy_range" in sel else sel.x_range)])
    print(f"{lab}: x extent in tracker px median {np.median(w):.0f} (range {w.min()}-{w.max()})")
print("40 cm at 6.4 px/cm =", 40 * 6.4, "px")
data/TIME/ROOM/151215_WT26Hab1_spikes_cl-fix values: 1024 sum (s): 1195.0
data/TIME/ROOM/EnvironmentalTask/151211_WT26_circleintestbox1_spikes_cl-fix values: 1024 sum (s): 1195.9
our 32x32 dwell map vs deposited TIME map: r = 1.0 order C ; total s ours 1194.5
arena (place avoidance): x extent in tracker px median 227 (range 160-230)
environment, circle: x extent in tracker px median 156 (range 121-168)
environment, box: x extent in tracker px median 202 (range 189-208)
40 cm at 6.4 px/cm = 256.0 px
In [5]:
# The data set's own maps (data/SPIKE, data/TIME). Plain maps: our spike-count maps on the
# 8-pixel grid against the deposited ones, every listed unit and session. Smoothed maps (RmSm,
# ArSm): their kernel is not described; a least-squares fit of the smoothed dwell map on the
# plain one, over 5 x 5 neighbours, shows what the smoothing does.
rows = []
for task, D_ in [("environment", ENV), ("place avoidance", AV)]:
    for s, v in D_.items():
        p = v["pos"]
        for u, d in v["units"].items():
            S0, _ = H.deposited_maps(s, u[1], u[2], "room", env=task == "environment", smoothed=False)
            if S0 is None or S0.shape != (H.NBIN, H.NBIN):
                rows.append(dict(task=task, session=s, unit=u, found=S0 is not None, grid=None if S0 is None else S0.shape[0])); continue
            ours = H.spike_map(p["rx"], p["ry"], d["spike_sample"])
            rows.append(dict(task=task, session=s, unit=u, found=True, r=np.corrcoef(ours.ravel(), S0.ravel())[0, 1] if ours.std() > 0 and S0.std() > 0 else np.nan,
                             n_ours=ours.sum(), n_dep=S0.sum(), same=bool(np.array_equal(ours, S0)), grid=H.NBIN))
MAPCHK = pd.DataFrame(rows)
print("plain SPIKE maps found:", MAPCHK.groupby("task").found.agg(["sum", "size"]).to_dict("index"), "; grid sizes:", MAPCHK.groupby(["task", "grid"]).size().to_dict())
print("sessions whose deposited maps are not on the 32 x 32 grid:", sorted(MAPCHK[MAPCHK.grid != H.NBIN].session.unique()))
print("our spike maps vs deposited, r:", MAPCHK.groupby("task").r.describe()[["count", "min", "25%", "50%", "max"]].round(3).to_string())
print("identical maps:", MAPCHK.groupby("task").same.mean().round(3).to_dict(), "; spike totals, deposited/ours median",
      round((MAPCHK.n_dep / MAPCHK.n_ours).median(), 4), "range", round((MAPCHK.n_dep / MAPCHK.n_ours).min(), 3), round((MAPCHK.n_dep / MAPCHK.n_ours).max(), 3))
Tpl = H._read_map("data/TIME/ROOM/151215_WT26Hab1_spikes_cl-fix"); Ts = H._read_map("data/TIME/ROOM/151215_WT26Hab1_spikes_cl-fixRmSm")
Pd = np.pad(Tpl, 2); X = np.array([Pd[i:i + 32, j:j + 32].ravel() for i in range(5) for j in range(5)]).T
w = np.linalg.lstsq(X, Ts.ravel(), rcond=None)[0].reshape(5, 5)
print("smoothed / plain dwell time, total:", round(Ts.sum() / Tpl.sum(), 2), "; least-squares weights on the 5 x 5 neighbours (row, column offset -2..2):")
print(np.round(w, 2))
print("so the smoothed maps sum roughly a 2 x 2 block of bins, shifted by half a bin; rate = smoothed spikes / smoothed time")
plain SPIKE maps found: {'environment': {'sum': 344, 'size': 344}, 'place avoidance': {'sum': 273, 'size': 273}} ; grid sizes: {('environment', 32): 344, ('place avoidance', 32): 237, ('place avoidance', 41): 36}
sessions whose deposited maps are not on the 32 x 32 grid: ['150720_WT19Conf1_2', '150720_WT19Ini1_2', 'WT15Hab1', 'WT16Hab1']
our spike maps vs deposited, r:                  count    min    25%    50%  max
task                                            
environment      344.0  0.900  0.978  0.988  1.0
place avoidance  237.0  0.895  0.966  0.985  1.0
identical maps: {'environment': 0.0, 'place avoidance': 0.008} ; spike totals, deposited/ours median 1.0 range 0.982 1.042
smoothed / plain dwell time, total: 4.51 ; least-squares weights on the 5 x 5 neighbours (row, column offset -2..2):
[[ 0.04 -0.09 -0.   -0.04  0.04]
 [-0.1   0.82  1.11  0.1  -0.12]
 [ 0.03  1.11  1.18  0.19  0.02]
 [-0.03  0.15  0.12 -0.01  0.02]
 [-0.01 -0.03  0.03  0.01 -0.  ]]
so the smoothed maps sum roughly a 2 x 2 block of bins, shifted by half a bin; rate = smoothed spikes / smoothed time

Duplicates. The Tracker files of WT15's training 2 recording are deposited twice, once in recordingDAT and once among the shock-on files (identical CRC). The TS spike trains are checked for identical trains across sessions below. The environment sessions 140731_WT15_testbox1 and testbox2 have the same positions, and three of four listed units' spike trains begin with the same spike times; they look like two sortings of one recording, and the later one is dropped. The copy kept, testbox1, fails the clock check below, so the environment claims are also shown without the two sessions that fail it.

In [6]:
import collections
crc = collections.defaultdict(list)
for i in H.archive().infolist():
    if i.filename.endswith(".dat"):
        crc[(i.CRC, i.file_size)].append(i.filename)
print("identical Tracker files:", [v for v in crc.values() if len(v) > 1])
sig = collections.defaultdict(list)
for s, v in list(AV.items()) + list(ENV.items()):
    for u, d in v["units"].items():
        if len(d["spike_times"]) > 10:
            sig[(len(d["spike_times"]), int(d["spike_times"][:10].sum()))].append((s, u))
print("identical spike trains across sessions or units:", [v for v in sig.values() if len(v) > 1])
# sessions whose position series are identical to an earlier session's: deposited twice
DUP = []
allpos = [(s, v["pos"]) for s, v in list(AV.items()) + list(ENV.items())]
for i, (s1, p1) in enumerate(allpos):
    for s2, p2 in allpos[i + 1:]:
        if len(p1["rx"]) == len(p2["rx"]) and np.array_equal(p1["rx"], p2["rx"]) and np.array_equal(p1["ry"], p2["ry"]):
            same = all(np.array_equal(AV.get(s1, ENV.get(s1))["units"][u]["spike_times"], d["spike_times"])
                       for u, d in AV.get(s2, ENV.get(s2))["units"].items())
            print(f"identical positions: {s1} and {s2}; all listed units' spike trains identical: {same}")
            for s_ in (s1, s2):
                v_ = AV.get(s_, ENV.get(s_))
                print(f"   {s_}: FIRST_TIMESTAMP {v_['pos']['t0']}; spikes per listed unit",
                      {u[1:]: len(d["spike_times"]) for u, d in v_["units"].items()},
                      "; first 20 spike times equal to the other copy's:",
                      {u[1:]: bool(np.array_equal(d["spike_times"][:20], AV.get(s2 if s_ == s1 else s1, ENV.get(s2 if s_ == s1 else s1))["units"][u]["spike_times"][:20]))
                       for u, d in v_["units"].items()})
            DUP.append(s2)
for s in DUP:  # count each recording once: drop the later copy
    ENV.pop(s, None); AV.pop(s, None)
print("dropped as duplicates:", DUP)
identical Tracker files: [['data/behavior/recordingDAT/WT15Ini2_1_Arena.dat', 'data/behavior/DATfilesPlaceAvoidanceShockON/WT15Ini2.1_Arena.dat'], ['data/behavior/recordingDAT/WT15Ini2_1_Room.dat', 'data/behavior/DATfilesPlaceAvoidanceShockON/WT15Ini2.1_Room.dat']]
identical spike trains across sessions or units: [[('140731_WT15_testbox1', ('140731_WT15', 2, 5)), ('140731_WT15_testbox2', ('140731_WT15', 2, 5))], [('140731_WT15_testbox1', ('140731_WT15', 2, 6)), ('140731_WT15_testbox2', ('140731_WT15', 2, 6))]]
identical positions: 140731_WT15_testbox1 and 140731_WT15_testbox2; all listed units' spike trains identical: False
   140731_WT15_testbox1: FIRST_TIMESTAMP 11095; spikes per listed unit {(2, 5): 180, (2, 6): 835, (3, 1): 4371, (0, 1): 2615} ; first 20 spike times equal to the other copy's: {(2, 5): True, (2, 6): True, (3, 1): True, (0, 1): False}
   140731_WT15_testbox2: FIRST_TIMESTAMP 15235; spikes per listed unit {(2, 5): 180, (2, 6): 835, (3, 1): 4308, (0, 1): 2745} ; first 20 spike times equal to the other copy's: {(2, 5): True, (2, 6): True, (3, 1): True, (0, 1): False}
dropped as duplicates: ['140731_WT15_testbox2']
In [7]:
# Tracker files of the place avoidance task: shock zones, shocks and path length.
dat_rows = []
for f in [m for m in H.members() if "/behavior/" in m and m.endswith("_Room.dat") and "Environmental" not in m]:
    m, d = H.read_dat(f)
    st = d.State.values
    dat_rows.append(dict(folder=f.split("/")[-2], file=f.split("/")[-1], minutes=round(float(m["ElapsedTime_ms"]) / 6e4, 1),
                         time=m.get("Time"), sector=m.get("ReinforcedSector"),
                         shocks=int(((st[1:] == 2) & (st[:-1] != 2)).sum()),
                         entries_state=int(((st[1:] == 1) & (st[:-1] == 0)).sum()),
                         max_current=float(np.nanmax(d.CurrentLevel.values)), path_m=float(m["ElapsedPath_m"])))
DAT = pd.DataFrame(dat_rows).sort_values("file")
DAT["mouse"] = DAT.file.str.extract(r"(WT\d+)")[0]
print(DAT.to_string())
                           folder                                  file  minutes      time                   sector  shocks  entries_state  max_current  path_m mouse
29  DATfilesPlaceAvoidanceShockON          150720_WT19Conf1_12_Room.dat     20.0   6:06 PM  305 60 25.5000 127.5000      30             34          2.0   33.07  WT19
0                    recordingDAT           150720_WT19Conf1_2_Room.dat     20.0   6:30 PM                      NaN       0              0          0.0   33.90  WT19
19                   recordingDAT              150720_WT19Hab1_Room.dat     30.0  11:56 AM                      NaN       0              0          0.0  109.48  WT19
28  DATfilesPlaceAvoidanceShockON            150720_WT19Ini2_1_Room.dat     10.0   3:58 PM  135 60 25.5000 127.5000       6              9          2.0   15.74  WT19
13                   recordingDAT            150720_WT19Ini2_2_Room.dat     20.0   4:12 PM                      NaN       0              0          0.0   63.45  WT19
6                    recordingDAT     150929_PIC_WT20_2Hab2_DG_Room.dat     20.0   1:34 PM                      NaN       0              0          0.0  101.48  WT20
20                   recordingDAT     150929_PIC_WT20_2Hab3_DG_Room.dat     20.0   3:06 PM                      NaN       0              0          0.0   96.63  WT20
8                    recordingDAT   150929_PIC_WT20_4Ini1_2_DG_Room.dat     20.0   5:26 PM                      NaN       0              0          0.0   47.12  WT20
38  DATfilesPlaceAvoidanceShockON     150929_PIC_WT20_4Ini1_DG_Room.dat     20.0   5:01 PM  135 60 25.5000 127.5000       7             15          2.0   32.95  WT20
10                   recordingDAT   150929_PIC_WT20_5Ini2_2_DG_Room.dat     20.0   7:14 PM                      NaN       0              0          0.0   40.83  WT20
37  DATfilesPlaceAvoidanceShockON     150929_PIC_WT20_5Ini2_DG_Room.dat     10.0   6:59 PM  135 60 25.5000 127.5000       2              2          2.0   15.32  WT20
3                    recordingDAT  150929_PIC_WT20_6Conf1_2_DG_Room.dat     20.0   9:24 PM                      NaN       0              0          0.0   39.14  WT20
35  DATfilesPlaceAvoidanceShockON    150929_PIC_WT20_6Conf1_DG_Room.dat     20.0   9:00 PM  315 60 25.5000 127.5000      12              9          2.0   26.00  WT20
12                   recordingDAT           151215_WT26Conf1_2_Room.dat     20.0   5:25 PM                      NaN       0              0          0.0   44.19  WT26
26  DATfilesPlaceAvoidanceShockON             151215_WT26Conf1_Room.dat     20.0   4:56 PM   45 60 25.5000 127.5000      26             37          3.0   49.24  WT26
4                    recordingDAT              151215_WT26Hab1_Room.dat     20.0  10:01 AM                      NaN       0              0          0.0   91.77  WT26
11                   recordingDAT              151215_WT26Hab2_Room.dat     20.0  11:16 AM                      NaN       0              0          0.0   74.82  WT26
15                   recordingDAT            151215_WT26Ini1_2_Room.dat     20.0   1:41 PM                      NaN       0              0          0.0   64.63  WT26
42  DATfilesPlaceAvoidanceShockON              151215_WT26Ini1_Room.dat     20.0   1:19 PM  225 60 25.5000 127.5000      18             26          4.0   40.79  WT26
5                    recordingDAT            151215_WT26Ini2_2_Room.dat     20.0   3:21 PM                      NaN       0              0          0.0   56.64  WT26
32  DATfilesPlaceAvoidanceShockON              151215_WT26Ini2_Room.dat     10.0   3:09 PM  225 60 25.5000 127.5000       4              7          3.0   19.10  WT26
24                   recordingDAT           151215_WT27Conf1_2_Room.dat     20.0   4:31 PM                      NaN       0              0          0.0   53.57  WT27
41  DATfilesPlaceAvoidanceShockON             151215_WT27Conf1_Room.dat     20.0   4:08 PM   45 60 25.5000 127.5000      14             23          3.0   32.49  WT27
1                    recordingDAT              151215_WT27Hab1_Room.dat     20.0   9:33 AM                      NaN       0              0          0.0   96.45  WT27
17                   recordingDAT              151215_WT27Hab2_Room.dat     20.0  10:52 AM                      NaN       0              0          0.0   81.79  WT27
14                   recordingDAT            151215_WT27Ini1_2_Room.dat     20.0  12:48 PM                      NaN       0              0          0.0   66.26  WT27
40  DATfilesPlaceAvoidanceShockON              151215_WT27Ini1_Room.dat     20.0  12:25 PM  225 60 25.5000 127.5000       9              9          3.0   32.15  WT27
7                    recordingDAT            151215_WT27Ini2_2_Room.dat     20.0   2:45 PM                      NaN       0              0          0.0   53.80  WT27
34  DATfilesPlaceAvoidanceShockON              151215_WT27Ini2_Room.dat     10.0   2:21 PM  225 60 25.5000 127.5000       1              1          2.0   15.02  WT27
30  DATfilesPlaceAvoidanceShockON                   WT15Conf1__Room.dat     14.3   7:23 PM  305 60 25.5000 127.5000       7             10          2.0   24.20  WT15
21                   recordingDAT                     WT15Hab1_Room.dat     20.0   1:49 PM                      NaN       0              0          0.0   45.87  WT15
18                   recordingDAT                   WT15Ini1_2_Room.dat     20.0   4:41 PM  135 60 25.5000 127.5000      33             26          2.0   52.91  WT15
25  DATfilesPlaceAvoidanceShockON                     WT15Ini1_Room.dat     20.0   4:05 PM  135 60 25.5000 127.5000      14             17          2.0   42.70  WT15
27  DATfilesPlaceAvoidanceShockON                   WT15Ini2.1_Room.dat     20.0   6:02 PM  135 60 25.5000 127.5000       1              1          2.0   42.38  WT15
22                   recordingDAT                   WT15Ini2_1_Room.dat     20.0   6:02 PM  135 60 25.5000 127.5000       1              1          2.0   42.38  WT15
9                    recordingDAT                  WT16Conf1_2_Room.dat     20.0   6:58 PM  300 60 25.5000 127.5000       5              8          2.0   42.65  WT16
31  DATfilesPlaceAvoidanceShockON                    WT16Conf1_Room.dat     15.0   6:32 PM  305 60 25.5000 127.5000       1              1          2.0   17.31  WT16
2                    recordingDAT                     WT16Hab1_Room.dat     20.0   1:13 PM                      NaN       0              0          0.0   41.05  WT16
39  DATfilesPlaceAvoidanceShockON                     WT16Ini1_Room.dat     20.0   3:08 PM  135 60 25.5000 127.5000       8              9          2.0   23.42  WT16
16                   recordingDAT                   WT16Ini2_1_Room.dat     20.0   5:24 PM  135 60 25.5000 127.5000      20             13          2.0   52.47  WT16
36  DATfilesPlaceAvoidanceShockON                     WT16Ini2_Room.dat     10.0   5:12 PM  135 60 25.5000 127.5000       3              6          2.0   10.37  WT16
23                   recordingDAT                   WT19Ini1_2_Room.dat     20.0   2:17 PM                      NaN       0              0          0.0   41.17  WT19
33  DATfilesPlaceAvoidanceShockON                     WT19Ini1_Room.dat     20.0   1:52 PM  135 60 25.5000 127.5000       8              8          2.0   31.84  WT19
In [8]:
# Sector geometry: our angle convention reproduces the Tracker's own in-sector flag.
for f in ["DATfilesPlaceAvoidanceShockON/151215_WT26Ini1_Room.dat", "DATfilesPlaceAvoidanceShockON/WT15Ini1_Room.dat",
          "DATfilesPlaceAvoidanceShockON/151215_WT26Conf1_Room.dat"]:
    m, d = H.read_dat("data/behavior/" + f)
    sec = H.sector_of(m); v = H.tracked(d.RoomX.values, d.RoomY.values)
    ins = H.in_sector(d.RoomX.values, d.RoomY.values, sec)
    print(f, sec, "agreement with Tracker flag:", round((ins[v] == (d.Sectors.values[v] == 1)).mean(), 4),
          "| entries: Tracker state", int(((d.State.values[1:] == 1) & (d.State.values[:-1] == 0)).sum()),
          "geometric", H.count_entries(ins, v))
DATfilesPlaceAvoidanceShockON/151215_WT26Ini1_Room.dat (225.0, 60.0, 25.5, 127.5) agreement with Tracker flag: 0.9994 | entries: Tracker state 26 geometric 30
DATfilesPlaceAvoidanceShockON/WT15Ini1_Room.dat (135.0, 60.0, 25.5, 127.5) agreement with Tracker flag: 0.9996 | entries: Tracker state 17 geometric 21
DATfilesPlaceAvoidanceShockON/151215_WT26Conf1_Room.dat (45.0, 60.0, 25.5, 127.5) agreement with Tracker flag: 0.9994 | entries: Tracker state 37 geometric 36
In [9]:
# Position and spikes share a clock: split-half rate-map correlation of the place cells with the
# spikes at their samples, against the same with positions shifted circularly by 60 s.
def split_half(p, d, shift=0):
    n = len(p["rx"]); h = n // 2
    x = np.roll(p["rx"], shift); y = np.roll(p["ry"], shift)
    k = d["spike_sample"]
    out = []
    for lo, hi in [(0, h), (h, n)]:
        v = np.zeros(n, bool); v[lo:hi] = True; v &= H.tracked(x, y)
        out.append(H.rate_map(H.spike_map(x, y, k, v), H.occupancy(x, y, p["fs"], v)))
    a, b = out; ok = np.isfinite(a) & np.isfinite(b)
    return np.corrcoef(a[ok], b[ok])[0, 1] if ok.sum() > 10 else np.nan
rows = []
for s, v in AV.items():
    for u, d in v["units"].items():
        if d["cls"] == "pc":
            rows.append(dict(session=s, mouse=v["meta"]["mouse"], r0=split_half(v["pos"], d), r60=split_half(v["pos"], d, int(60 * v["pos"]["fs"]))))
for s, v in ENV.items():
    for u, d in v["units"].items():
        rows.append(dict(session=s, mouse=s.split("_")[1], r0=split_half(v["pos"], d), r60=split_half(v["pos"], d, int(60 * v["pos"]["fs"]))))
SH = pd.DataFrame(rows)
g = SH.groupby("session")[["r0", "r60"]].median()
print("median split-half map r per session, aligned vs positions shifted 60 s:")
print(g.describe().round(3).to_string())
BAD_ALIGN = g[g.r0 <= g.r60].index.tolist()
print("sessions where aligned median r is not above shifted:", BAD_ALIGN, "(the environment claims are also shown without them)")
median split-half map r per session, aligned vs positions shifted 60 s:
           r0     r60
count  82.000  82.000
mean    0.174  -0.006
std     0.120   0.029
min    -0.006  -0.073
25%     0.083  -0.022
50%     0.138  -0.013
75%     0.260  -0.000
max     0.436   0.108
sessions where aligned median r is not above shifted: ['140731_WT15_testbox1', '140803_WT16_rotated90dcircleintestbox2'] (the environment claims are also shown without them)

Environment manipulation experiment (Figure 1, Table S1)¶

Each listed cell is measured in every session of its day. The conditions come from the session names: circleintestbox is standard, rot/rotated is rotated, testbox alone is removed; diffcircle and transferbin sessions are none of the paper's three versions and are left out. The first standard session of a day is the lowest-numbered circleintestbox session.

Place fields (M5) are found on smoothed maps, the reading adopted in reply to the verifier: on the unsmoothed maps of M2 one-spike bins set the 20%-of-peak threshold, and many cells had no field. The paper does not say whether its maps were smoothed; the data set holds the authors' smoothed maps (RmSm), on the common grid for every environment session, and these are used (reading "s"). Our own smoothing (H.smooth_maps, reading "t") and the unsmoothed readings (a) and (b) are shown beside it. Stability, rates and the Table S1 measures stay on the unsmoothed maps.

In [10]:
def cell_session_measures(p, d, min_occ=0.0, sm=None):
    x, y, fs = p["rx"], p["ry"], p["fs"]
    v = H.tracked(x, y)
    occ = H.occupancy(x, y, fs, v)
    spk = H.spike_map(x, y, d["spike_sample"], v)
    rm = H.rate_map(spk, occ, min_occ)
    dur = len(x) / fs
    st = d["spike_times"]
    isi = np.diff(st) / 10.0  # ms
    bits_spk, bits_s = H.info_content(rm, occ)
    # Fields on smoothed maps (M2 reading "s", adopted for fields): the data set's own smoothed
    # maps where they are on the common 32 x 32 grid, else our smoothing (H.smooth_maps); our
    # smoothing is also kept for every session as reading "t". M5 (a) is "sa"/"ta", (b) "sb"/"tb".
    Tsp, Toc = H.smooth_maps(spk, occ)
    dep = sm is not None and sm[0] is not None and sm[0].shape == spk.shape
    S_, T_ = (sm if dep else (Tsp, Toc))
    sm_cols = dict(sm_src="deposited" if dep else "own", sspk=S_, socc=T_, tspk=Tsp, tocc=Toc)
    for key, (Sx, Tx) in [("s", (S_, T_)), ("t", (Tsp, Toc))]:
        with np.errstate(invalid="ignore", divide="ignore"):
            rs = Sx / Tx
        rs[Tx <= 0] = np.nan
        fa, fb = H.place_fields(rs, "a"), H.place_fields(rs, "b")
        sm_cols.update({f"fields_{key}a": len(fa), f"fields_{key}b": len(fb), f"fieldmask_{key}a": (fa or [None])[0],
                        f"fieldmask_{key}b": (fb or [None])[0], f"fieldunion_{key}a": np.any(fa, axis=0) if fa else None})
    return dict(rmap=rm, occ=occ, rate=len(st) / dur, n_spikes=len(st), **sm_cols,
                fields_a=len(H.place_fields(rm, "a")), fields_b=len(H.place_fields(rm, "b")),
                fieldmask_a=(H.place_fields(rm, "a") or [None])[0], fieldmask_b=(H.place_fields(rm, "b") or [None])[0],
                info_bits_spike=bits_spk, info_bits_s=bits_s, coherence=H.coherence(rm),
                mean_isi_ms=isi.mean() if len(isi) else np.nan,
                pct_isi_10=100 * (isi < 10).mean() if len(isi) else np.nan, spk=spk)

EM = {}  # (min_occ reading) -> rows
for rd, mo in [("a", 0.0), ("b", 0.67)]:
    rows = []
    for s, v in ENV.items():
        cond = v["meta"]["condition"]
        if cond == "other":
            continue
        for u, d in v["units"].items():
            m = cell_session_measures(v["pos"], d, mo, H.deposited_maps(s, u[1], u[2], "room", env=True))
            m.update(session=s, day=v["meta"]["day"], cond=cond, rank=v["meta"]["rank"], cell=u, region=d["region"])
            rows.append(m)
    EM[rd] = pd.DataFrame(rows)
# Reading "s" (adopted for fields): fields, field masks and field rates from the data set's
# smoothed maps; stability, rates and the other measures as in reading (a).
# Reading "t": the same with our own smoothing.
for key in "st":
    Es = EM["a"].copy()
    for k in "ab":
        Es[f"fields_{k}"] = Es[f"fields_{key}{k}"]; Es[f"fieldmask_{k}"] = Es[f"fieldmask_{key}{k}"]
    Es["spk"], Es["occ"] = Es[f"{key}spk"], Es[f"{key}occ"]
    EM[key] = Es
E = EM["a"]
print("M2 readings: a unsmoothed; b unsmoothed, bins under 0.67 s left out; s fields on the data set's smoothed maps (adopted); t fields on our smoothing")
print("source of the smoothed maps, environment sessions:", EM["a"].sm_src.value_counts().to_dict())
print("cell-session measures:", len(E), "rows;", E.cell.nunique(), "cells;", E.groupby(["region", "cond"]).size().unstack().to_string())
print("rates (AP/s) range", E.rate.min().round(3), E.rate.max().round(2), "; cells with no spikes in a session:", int((E.n_spikes == 0).sum()))
M2 readings: a unsmoothed; b unsmoothed, bins under 0.67 s left out; s fields on the data set's smoothed maps (adopted); t fields on our smoothing
source of the smoothed maps, environment sessions: {'deposited': 320}
cell-session measures: 320 rows; 65 cells; cond    removed  rotated  standard
region                            
CA           21       32        62
DG           57       49        99
rates (AP/s) range 0.016 5.71 ; cells with no spikes in a session: 0

fig1-single-field-proportion¶

Most place cells had a single place field in the first standard session (64% of DG and 75% of CA place cells), with no significant difference between the regions.

In [11]:
first_std = E[E.cond == "standard"].sort_values("rank").groupby("cell").head(1).session.unique()
res = []
for m2, Ed in EM.items():
    F = Ed[Ed.session.isin(first_std)]
    F = F[F.session.isin(F.sort_values("rank").groupby("day").session.first())]
    for m5 in "ab":
        col = f"fields_{m5}"
        dg = F[F.region == "DG"][col]; ca = F[F.region == "CA"][col]
        k1, n1, k2, n2 = int((dg == 1).sum()), len(dg), int((ca == 1).sum()), len(ca)
        z, pz = H.prop_ztest(k1, n1, k2, n2)
        res.append(dict(M2=m2, M5=m5, DG_single_pct=100 * k1 / n1, DG_n=n1, CA_single_pct=100 * k2 / n2, CA_n=n2,
                        DG_zero_fields=int((dg == 0).sum()), CA_zero_fields=int((ca == 0).sum()), z=z, p=pz))
R_single = pd.DataFrame(res); print(R_single.round(3).to_string())
print("expected: DG 64 +/- 6.4 %, CA 75 +/- 7.5 %, test p >= 0.05")
R_single["match"] = (R_single.DG_single_pct.sub(64).abs() <= 6.4) & (R_single.CA_single_pct.sub(75).abs() <= 7.5) & (R_single.p >= 0.05)
print("readings that match:", R_single[R_single.match][["M2", "M5"]].values.tolist())
# by animal
F = E[E.session.isin(first_std)]
Fs = EM["s"][EM["s"].session.isin(first_std)]
print("\nsingle-field fraction by day (M2 a, M5 a; smoothed maps, M5 a and b):")
print(pd.concat([F.groupby(["region", "day"]).fields_a.agg(n="size", single_a=lambda s: (s == 1).mean()),
                 Fs.groupby(["region", "day"]).fields_a.agg(single_s_a=lambda s: (s == 1).mean()),
                 Fs.groupby(["region", "day"]).fields_b.agg(single_s_b=lambda s: (s == 1).mean())], axis=1).round(2).to_string())
print("\nfields per cell, first standard session, smoothed maps M5 a:", Fs.groupby("region").fields_a.value_counts().unstack(fill_value=0).to_string())
  M2 M5  DG_single_pct  DG_n  CA_single_pct  CA_n  DG_zero_fields  CA_zero_fields      z      p
0  a  a         44.444    45           50.0    20              19               4 -0.415  0.678
1  a  b         57.778    45           50.0    20               7               2  0.582  0.560
2  b  a         62.222    45           55.0    20              11               2  0.549  0.583
3  b  b         57.778    45           45.0    20               8               3  0.954  0.340
4  s  a         57.778    45           45.0    20               2               1  0.954  0.340
5  s  b         66.667    45           55.0    20               7               2  0.900  0.368
6  t  a         62.222    45           35.0    20               9               2  2.032  0.042
7  t  b         55.556    45           45.0    20               6               2  0.786  0.432
expected: DG 64 +/- 6.4 %, CA 75 +/- 7.5 %, test p >= 0.05
readings that match: []

single-field fraction by day (M2 a, M5 a; smoothed maps, M5 a and b):
                     n  single_a  single_s_a  single_s_b
region day                                              
CA     140731_WT15   1      0.00        0.00        1.00
       140803_WT15   1      0.00        0.00        0.00
       140829_WT15   1      1.00        1.00        1.00
       140831_WT13   2      0.50        0.50        0.50
       140831_WT15   2      0.50        1.00        1.00
       150709_WT18  13      0.54        0.38        0.46
DG     140731_WT15   3      0.00        0.33        0.33
       140801_WT15   6      0.00        0.83        1.00
       140803_WT15   7      0.57        0.86        1.00
       140803_WT16   4      0.75        0.50        0.75
       140829_WT15   2      0.50        1.00        0.50
       140831_WT15   4      0.25        0.50        0.50
       140831_WT16   4      0.25        0.25        0.75
       150716_WT19   8      0.62        0.50        0.38
       151211_WT26   4      0.75        0.25        0.50
       151211_WT27   3      0.67        0.67        0.67

fields per cell, first standard session, smoothed maps M5 a: fields_a  0   1  2  3  4
region                  
CA        1   9  6  4  0
DG        2  26  9  6  2

Result: Not reproduced, resting on the M2 and M5 assumptions. Under every reading of the rate map (unsmoothed M2 (a) and (b), the data set's smoothed maps, adopted, and our smoothing) and of the field rule (M5), the share of place cells with one field in the first standard session is 44 to 67% in DG and 35 to 55% in CA, against 64 and 75%; no reading puts both within tolerance, as CA stays below 67.5%. On the data set's smoothed maps, few cells have no field (2 of 45 DG and 1 of 20 CA cells under M5 (a)); DG is then 57.8% (M5 a) or 66.7% (M5 b), within tolerance, and CA 45.0 or 55.0%. The regions do not differ (p 0.34 to 0.68) except with our smoothing and M5 (a) (p = 0.042).

fig1-field-number-scaling¶

The number of place fields rose from the circular environments to the twice larger box after wall removal, more in DG (1.48 to 2.70) than in CA (1.19 to 2.0), with a condition effect, a region effect at p = 0.05 and no interaction; post hoc, removed DG exceeded circular DG and CA, and CA did not change.

In [12]:
out = []
for m2, Ed in EM.items():
    for m5 in "ab":
        col = f"fields_{m5}"
        Ed = Ed.copy(); Ed["circ"] = np.where(Ed.cond == "removed", "removed", "circular")
        pc = Ed.groupby(["cell", "region", "circ"])[col].mean().reset_index()
        pc["mouse"] = pc.cell.map(lambda c: c[0].split("_")[1]); pc["cid"] = pc.cell.map(str)
        means = pc.groupby(["region", "circ"])[col].agg(["mean", "sem", "size"])
        tab, mod = H.mixed_terms(pc.rename(columns={col: "nf"}), "nf ~ C(region, Sum) * C(circ, Sum)", "cid",
                                 {"region": "region", "condition": "circ", "interaction": "region&circ"})
        tab_m, _ = H.mixed_terms(pc.rename(columns={col: "nf"}), "nf ~ C(region, Sum) * C(circ, Sum)", "mouse",
                                 {"region": "region", "condition": "circ", "interaction": "region&circ"})
        t3, _ = H.anova2(pc.rename(columns={col: "nf"}), "nf", "region", "circ")
        piv = pc.pivot_table(index=["cid", "region"], columns="circ", values=col).reset_index()
        dgc, dgr = piv[piv.region == "DG"].circular, piv[piv.region == "DG"].removed
        cac, car = piv[piv.region == "CA"].circular, piv[piv.region == "CA"].removed
        ph = dict(rDG_vs_cDG=stats.ttest_rel(dgr, dgc, nan_policy="omit").pvalue,
                  rDG_vs_cCA=stats.ttest_ind(dgr.dropna(), cac.dropna()).pvalue,
                  rCA_vs_cCA=stats.ttest_rel(car, cac, nan_policy="omit").pvalue)
        # Fisher's LSD with the cell-random mixed model's pooled error (M12), the four region x condition means
        pc["grp"] = pc.region + "_" + pc.circ
        L4 = H.mixed_lsd(pc, col, "grp", "cid", ["DG_removed", "DG_circular", "CA_circular", "CA_removed"]).set_index(["a", "b"]).p
        ph_lsd = dict(rDG_vs_cDG=L4[("DG_removed", "DG_circular")], rDG_vs_cCA=L4[("DG_removed", "CA_circular")],
                      rCA_vs_cCA=L4[("CA_circular", "CA_removed")])
        m = means["mean"]
        out.append(dict(M2=m2, M5=m5, DG_circ=m[("DG", "circular")], DG_rem=m[("DG", "removed")], CA_circ=m[("CA", "circular")],
                        CA_rem=m[("CA", "removed")], n_cells=pc.cid.nunique(),
                        F_region=tab.F[0], p_region=tab.p[0], F_cond=tab.F[1], p_cond=tab.p[1], F_int=tab.F[2], p_int=tab.p[2],
                        p_cond_mouse=tab_m.p[1], p_cond_ols=t3["PR(>F)"].iloc[1], **{f"posthoc_{k}": v for k, v in ph.items()}, **{f"lsd_{k}": v for k, v in ph_lsd.items()}))
        if m2 == "a" and m5 == "a":
            print("M2 a, M5 a: means, SEM, n"); print(means.round(3).to_string())
            print("cell random:"); print(tab.round(4).to_string()); print("mouse random:"); print(tab_m.round(4).to_string())
            print("ordinary two-way ANOVA:"); print(t3.round(4).to_string())
R_nf = pd.DataFrame(out); print(R_nf.drop(columns=[c for c in R_nf if c.startswith("lsd_")]).round(3).to_string())
print("post hoc as Fisher's LSD with the mixed model's pooled error:"); print(R_nf[["M2", "M5"] + [c for c in R_nf if c.startswith("lsd_")]].round(4).to_string())
Ed = EM["s"][~EM["s"].session.isin(BAD_ALIGN)].copy(); Ed["circ"] = np.where(Ed.cond == "removed", "removed", "circular")
pc = Ed.groupby(["cell", "region", "circ"]).fields_a.mean().reset_index(); pc["cid"] = pc.cell.map(str)
tab, _ = H.mixed_terms(pc.rename(columns={"fields_a": "nf"}), "nf ~ C(region, Sum) * C(circ, Sum)", "cid", {"region": "region", "condition": "circ", "interaction": "region&circ"})
print("variant, smoothed maps M5 a, without", BAD_ALIGN, ": means", pc.groupby(["region", "circ"]).fields_a.mean().round(2).to_dict(), "p =", tab.p.round(4).tolist())
exp = dict(DG_circ=(1.48, .37), DG_rem=(2.7, .39), CA_circ=(1.19, .55), CA_rem=(2.0, .59))
R_nf["means_ok"] = np.all([(R_nf[k] - v).abs() <= t for k, (v, t) in exp.items()], axis=0)
R_nf["match"] = R_nf.means_ok & (R_nf.p_cond < 0.05) & (R_nf.DG_rem > R_nf.DG_circ) & (R_nf.posthoc_rDG_vs_cDG < .05) & (R_nf.DG_rem > R_nf.CA_circ) & (R_nf.posthoc_rDG_vs_cCA < .05) & (R_nf.posthoc_rCA_vs_cCA >= .05)
R_nf["match_lsd"] = R_nf.means_ok & (R_nf.p_cond < 0.05) & (R_nf.DG_rem > R_nf.DG_circ) & (R_nf.lsd_rDG_vs_cDG < .05) & (R_nf.DG_rem > R_nf.CA_circ) & (R_nf.lsd_rDG_vs_cCA < .05) & (R_nf.lsd_rCA_vs_cCA >= .05)
print(R_nf[["M2", "M5", "means_ok", "match", "match_lsd"]].to_string())
M2 a, M5 a: means, SEM, n
                  mean    sem  size
region circ                        
CA     circular  0.771  0.107    20
       removed   1.237  0.266    19
DG     circular  0.707  0.076    45
       removed   0.744  0.111    43
cell random:
          term       F  df1    df2       p
0       region  3.0640    1  123.0  0.0825
1    condition  5.2633    1  123.0  0.0235
2  interaction  4.0602    1  123.0  0.0461
mouse random:
          term       F  df1    df2       p
0       region  0.0924    1  123.0  0.7617
1    condition  3.3462    1  123.0  0.0698
2  interaction  2.4623    1  123.0  0.1192
ordinary two-way ANOVA:
                sum_sq     df       F  PR(>F)
region          2.0878    1.0  4.1270  0.0444
circ            1.7068    1.0  3.3739  0.0687
region x circ   1.2439    1.0  2.4589  0.1194
Residual       62.2244  123.0     NaN     NaN
  M2 M5  DG_circ  DG_rem  CA_circ  CA_rem  n_cells  F_region  p_region  F_cond  p_cond  F_int  p_int  p_cond_mouse  p_cond_ols  posthoc_rDG_vs_cDG  posthoc_rDG_vs_cCA  posthoc_rCA_vs_cCA
0  a  a    0.707   0.744    0.771   1.237       65     3.064     0.083   5.263   0.023  4.060  0.046         0.070       0.069               0.851               0.882               0.063
1  a  b    1.202   1.465    1.200   1.763       65     0.389     0.534   7.961   0.006  1.106  0.295         0.032       0.040               0.134               0.362               0.036
2  b  a    0.950   0.965    1.117   1.395       65     3.190     0.077   1.837   0.178  1.606  0.207         0.249       0.299               0.987               0.460               0.102
3  b  b    1.141   1.465    1.088   1.842       65     0.385     0.536  10.718   0.001  1.769  0.186         0.011       0.015               0.096               0.243               0.019
4  s  a    1.506   2.093    1.450   1.684       65     0.914     0.341   5.071   0.026  0.964  0.328         0.040       0.056               0.011               0.071               0.448
5  s  b    1.185   1.721    1.300   1.658       65     0.010     0.920   9.356   0.003  0.395  0.531         0.020       0.026               0.003               0.186               0.158
6  t  a    1.231   2.093    1.317   1.632       65     0.603     0.439   6.021   0.016  1.299  0.257         0.011       0.016               0.005               0.067               0.388
7  t  b    1.361   1.907    1.529   2.263       65     0.768     0.382  19.631   0.000  0.380  0.539         0.003       0.007               0.002               0.284               0.004
post hoc as Fisher's LSD with the mixed model's pooled error:
  M2 M5  lsd_rDG_vs_cDG  lsd_rDG_vs_cCA  lsd_rCA_vs_cCA
0  a  a          0.8014          0.8624          0.0108
1  a  b          0.1126          0.3585          0.0217
2  b  a          0.9368          0.4259          0.1178
3  b  b          0.0818          0.2313          0.0066
4  s  a          0.0042          0.0361          0.4469
5  s  b          0.0012          0.1373          0.1470
6  t  a          0.0015          0.0237          0.4315
7  t  b          0.0008          0.2431          0.0030
variant, smoothed maps M5 a, without ['140731_WT15_testbox1', '140803_WT16_rotated90dcircleintestbox2'] : means {('CA', 'circular'): 1.45, ('CA', 'removed'): 1.61, ('DG', 'circular'): 1.5, ('DG', 'removed'): 2.0} p = [0.4076, 0.0668, 0.3927]
  M2 M5  means_ok  match  match_lsd
0  a  a     False  False      False
1  a  b     False  False      False
2  b  a     False  False      False
3  b  b     False  False      False
4  s  a     False  False      False
5  s  b     False  False      False
6  t  a     False  False      False
7  t  b     False  False      False

Result: Not reproduced, resting on the M2 and M5 assumptions. On the data set's smoothed maps with M5 (a), the adopted reading, mean fields per cell are 1.51 (DG, circular), 2.09 (DG, removed), 1.45 and 1.68 (CA), against 1.48, 2.70, 1.19 and 2.0: three are within tolerance, but removed DG is below 2.70 ± 0.39, and no reading of M2 and M5 puts it within tolerance (at most 2.09). Under that reading the condition effect is p = 0.026 (cell as random term). Fisher's LSD with the mixed model's pooled error puts removed DG above circular DG (p = 0.0042) and above circular CA (p = 0.036), and finds no difference between circular and removed CA (p = 0.45), the paper's pattern; paired and unpaired t tests, the earlier post hoc test, put removed DG above circular DG (p = 0.011) but not above circular CA (p = 0.071). Across readings the pooled-error LSD puts removed DG above circular CA only with M5 (a) on smoothed maps (p = 0.036 on the data set's, 0.024 on ours; elsewhere p 0.14 to 0.86). The outcome fails on the removed DG mean. Without the two sessions that fail the clock check the means are 1.50, 2.00, 1.45 and 1.61 and the condition effect is p = 0.067.

fig1b-stability-dg-below-ca-removal¶

Rate map stability was lower in DG than in CA place cells, and lower for wall removal than for replication and cue relocation, with no region by manipulation interaction.

Pairs of sessions of a day: replication = same condition (standard-standard, rotated-rotated, removed-removed), relocation = standard-rotated, removal = standard-removed and rotated-removed; every pair of the day enters and a cell's pairs within a manipulation are averaged (STAR Methods, Behavioral Procedures and Firing rate stability: "If there were multiple trial correlations for a given manipulation ... the average correlation was used").

In [13]:
def manip_env(c1, c2):
    if c1 == c2:
        return "replication"
    if {c1, c2} == {"standard", "rotated"}:
        return "relocation"
    return "removal"

def env_pairs(Ed, maskcol="fieldmask_a"):
    rows = []
    for (cell, region), g in Ed.groupby(["cell", "region"]):
        g = g.sort_values(["cond", "rank"]).reset_index(drop=True)
        day_first = g.sort_values("rank")
        # field mask: the largest field in the first standard session of the day [claims M4]
        fs_ = g[g.cond == "standard"].sort_values("rank")
        mask = fs_[maskcol].iloc[0] if len(fs_) else None
        for i in range(len(g)):
            for j in range(i + 1, len(g)):
                a, b = g.iloc[i], g.iloc[j]
                fr = np.nan
                if mask is not None:
                    ra = a.spk[mask].sum() / max(a.occ[mask].sum(), 1e-9); rb = b.spk[mask].sum() / max(b.occ[mask].sum(), 1e-9)
                    fr = H.rate_change(ra, rb)
                    fra, frb = ra, rb
                rows.append(dict(cell=cell, region=region, manip=manip_env(a.cond, b.cond),
                                 stab=H.map_stability(a.rmap, b.rmap), rr=H.rate_change(a.rate, b.rate), fr=fr))
    P = pd.DataFrame(rows)
    P["arr"] = P.rr.abs(); P["afr"] = P.fr.abs()
    return P

EP = {rd: env_pairs(Ed) for rd, Ed in EM.items()}
EP_b = env_pairs(EM["a"], "fieldmask_b")
EP_sb = env_pairs(EM["s"], "fieldmask_b")  # EM["s"] holds the smoothed-map masks under these names
# variants without the two sessions that fail the clock check (BAD_ALIGN)
EP_al = env_pairs(EM["a"][~EM["a"].session.isin(BAD_ALIGN)]); EP_s_al = env_pairs(EM["s"][~EM["s"].session.isin(BAD_ALIGN)])
PC_env_al = EP_al.groupby(["cell", "region", "manip"])[["stab", "rr", "arr"]].mean().reset_index()
PC_env = {rd: P.groupby(["cell", "region", "manip"])[["stab", "rr", "arr", "fr", "afr"]].mean().reset_index() for rd, P in EP.items()}
for rd, P in PC_env.items():
    P["mouse"] = P.cell.map(lambda c: c[0].split("_")[1])
print("pairs per manipulation:", EP["a"].groupby(["region", "manip"]).size().unstack().to_string())
print("cell x manipulation values:", len(PC_env["a"]), "(the paper's df 172 imply 178)")
pairs per manipulation: manip   relocation  removal  replication
region                                  
CA             114       97           98
DG             102      184           95
cell x manipulation values: 174 (the paper's df 172 imply 178)
In [14]:
for rd in "ab":
    P = PC_env[rd]
    t, m = H.anova2(P, "stab", "region", "manip")
    print(f"M2 reading {rd}: two-way ANOVA on stability (z)"); print(t.round(4).to_string())
    print(P.groupby(["region", "manip"]).stab.agg(["mean", "sem", "size"]).round(3).to_string())
    mse = m.mse_resid; dfr = m.df_resid
    g = [P[P.manip == k].stab.values for k in ["removal", "replication", "relocation"]]
    print("Fisher's LSD, manipulation (pooled over region):"); print(H.lsd(g, ["removal", "replication", "relocation"], mse, dfr).round(4).to_string())
    print("region means: DG", P[P.region == "DG"].stab.mean().round(3), "CA", P[P.region == "CA"].stab.mean().round(3))
    print("by mouse (mean z):"); print(P.groupby(["region", "mouse"]).stab.mean().round(3).to_string()); print()
t, m = H.anova2(PC_env_al, "stab", "region", "manip")
g = [PC_env_al[PC_env_al.manip == k].stab.values for k in ["removal", "replication", "relocation"]]
print("variant, M2 a without", BAD_ALIGN, ": n =", len(PC_env_al), "p (region, manipulation, interaction) =", t["PR(>F)"].iloc[:3].round(4).tolist(),
      "; region means DG", PC_env_al[PC_env_al.region == "DG"].stab.mean().round(3), "CA", PC_env_al[PC_env_al.region == "CA"].stab.mean().round(3),
      "; LSD removal vs replication, relocation p =", H.lsd(g, ["removal", "replication", "relocation"], m.mse_resid, m.df_resid).p.iloc[:2].round(4).tolist())
M2 reading a: two-way ANOVA on stability (z)
                sum_sq     df       F  PR(>F)
region          0.4387    1.0  8.7273  0.0036
manip           1.0033    2.0  9.9793  0.0001
region x manip  0.0279    2.0  0.2771  0.7583
Residual        8.4450  168.0     NaN     NaN
                     mean    sem  size
region manip                          
CA     relocation   0.498  0.052    17
       removal      0.295  0.045    19
       replication  0.480  0.056    17
DG     relocation   0.351  0.044    36
       removal      0.215  0.022    43
       replication  0.378  0.040    42
Fisher's LSD, manipulation (pooled over region):
             a            b    diff       t       p
0      removal  replication -0.1681 -4.1216  0.0001
1      removal   relocation -0.1592 -3.7955  0.0002
2  replication   relocation  0.0089  0.2091  0.8346
region means: DG 0.312 CA 0.419
by mouse (mean z):
region  mouse
CA      WT13     0.092
        WT15     0.283
        WT18     0.478
DG      WT15     0.245
        WT16     0.309
        WT19     0.421
        WT26     0.422
        WT27     0.272

M2 reading b: two-way ANOVA on stability (z)
                sum_sq     df        F  PR(>F)
region          0.6344    1.0  10.9469  0.0011
manip           0.9507    2.0   8.2017  0.0004
region x manip  0.0100    2.0   0.0865  0.9172
Residual        9.7365  168.0      NaN     NaN
                     mean    sem  size
region manip                          
CA     relocation   0.551  0.059    17
       removal      0.365  0.049    19
       replication  0.533  0.062    17
DG     relocation   0.396  0.047    36
       removal      0.246  0.022    43
       replication  0.413  0.044    42
Fisher's LSD, manipulation (pooled over region):
             a            b    diff       t       p
0      removal  replication -0.1649 -3.7657  0.0002
1      removal   relocation -0.1634 -3.6292  0.0004
2  replication   relocation  0.0014  0.0314  0.9750
region means: DG 0.349 CA 0.479
by mouse (mean z):
region  mouse
CA      WT13     0.202
        WT15     0.337
        WT18     0.536
DG      WT15     0.281
        WT16     0.367
        WT19     0.442
        WT26     0.454
        WT27     0.298

variant, M2 a without ['140731_WT15_testbox1', '140803_WT16_rotated90dcircleintestbox2'] : n = 170 p (region, manipulation, interaction) = [0.0034, 0.0004, 0.7992] ; region means DG 0.316 CA 0.427 ; LSD removal vs replication, relocation p = [0.0002, 0.0008]

Result: Reproduced. With one value per cell and manipulation (174 values), stability is higher in CA than in DG (mean z 0.42 against 0.31; region F = 8.73, p = 0.0036), differs by manipulation (F = 9.98, p = 0.0001), and Fisher's LSD puts removal below replication (p = 0.0001) and relocation (p = 0.0002); the interaction is p = 0.76 (paper 0.77). Reading (b) of M2 gives the same (region p = 0.0011, manipulation p = 0.0004), and so does leaving out the two sessions that fail the clock check (170 values; region p = 0.0034, manipulation p = 0.0004, LSD p = 0.0002 and 0.0008).

fig1-rate-remapping-no-difference¶

Rate remapping did not differ between DG and CA place cells or across the three environment manipulations.

In [15]:
P = PC_env["a"]
for col, lab in [("arr", "absolute ratio (main)"), ("rr", "signed ratio (variant)")]:
    t, m = H.anova2(P, col, "region", "manip")
    print(lab); print(t.round(4).to_string())
    print(P.groupby(["region", "manip"])[col].agg(["mean", "sem", "size"]).round(3).to_string()); print()
t, _ = H.anova2(PC_env_al, "arr", "region", "manip")
print("variant, absolute ratio without", BAD_ALIGN, ": n =", len(PC_env_al), "p (region, manipulation, interaction) =", t["PR(>F)"].iloc[:3].round(4).tolist())
absolute ratio (main)
                sum_sq     df       F  PR(>F)
region          0.0128    1.0  0.3731  0.5422
manip           0.0367    2.0  0.5347  0.5868
region x manip  0.0241    2.0  0.3504  0.7049
Residual        5.7676  168.0     NaN     NaN
                     mean    sem  size
region manip                          
CA     relocation   0.373  0.042    17
       removal      0.357  0.052    19
       replication  0.328  0.043    17
DG     relocation   0.320  0.033    36
       removal      0.365  0.028    43
       replication  0.318  0.025    42

signed ratio (variant)
                 sum_sq     df       F  PR(>F)
region           0.0401    1.0  0.3893  0.5335
manip            0.2690    2.0  1.3049  0.2739
region x manip   0.7125    2.0  3.4567  0.0338
Residual        17.3150  168.0     NaN     NaN
                     mean    sem  size
region manip                          
CA     relocation   0.138  0.076    17
       removal     -0.084  0.091    19
       replication -0.034  0.070    17
DG     relocation  -0.050  0.051    36
       removal      0.063  0.054    43
       replication -0.092  0.042    42

variant, absolute ratio without ['140731_WT15_testbox1', '140803_WT16_rotated90dcircleintestbox2'] : n = 170 p (region, manipulation, interaction) = [0.5243, 0.4061, 0.7736]

Result: Reproduced. The two-way ANOVA of the absolute rate change finds no region (p = 0.54), manipulation (p = 0.59) or interaction effect (p = 0.70), and none without the two sessions that fail the clock check (p = 0.52, 0.41 and 0.77). With the signed ratio, the variant, the interaction is p = 0.034, an effect the paper's test on magnitudes does not look at.

fig1c-field-rate-change-no-difference¶

The magnitude of firing rate change in the primary place field did not differ between manipulations or regions.

In [16]:
for lab, Pp in [("smoothed maps, M5 a field mask (adopted)", EP["s"]), ("smoothed maps, M5 b field mask", EP_sb),
                ("M2 a, M5 a field mask", EP["a"]), ("M2 a, M5 b field mask", EP_b)]:
    P = Pp.groupby(["cell", "region", "manip"])[["afr"]].mean().reset_index().dropna()
    P["log_afr"] = np.log10(P.afr + 0.01)
    for col in ["afr", "log_afr"]:
        t, m = H.anova2(P, col, "region", "manip")
        print(lab, col, "n =", len(P), "(paper df 164 imply 170)"); print(t.round(4).to_string())
    print(P.groupby(["region", "manip"]).afr.agg(["mean", "sem", "size"]).round(3).to_string()); print()
P = EP_s_al.groupby(["cell", "region", "manip"])[["afr"]].mean().reset_index().dropna()
t, _ = H.anova2(P, "afr", "region", "manip")
print("variant, smoothed maps M5 a, without", BAD_ALIGN, ": n =", len(P), "p =", t["PR(>F)"].iloc[:3].round(4).tolist())
smoothed maps, M5 a field mask (adopted) afr n = 167 (paper df 164 imply 170)
                sum_sq     df       F  PR(>F)
region          0.0490    1.0  0.9602  0.3286
manip           0.1654    2.0  1.6209  0.2009
region x manip  0.1664    2.0  1.6304  0.1991
Residual        8.2157  161.0     NaN     NaN
smoothed maps, M5 a field mask (adopted) log_afr n = 167 (paper df 164 imply 170)
                sum_sq     df       F  PR(>F)
region          0.0141    1.0  0.2571  0.6128
manip           0.1779    2.0  1.6233  0.2005
region x manip  0.1514    2.0  1.3821  0.2540
Residual        8.8200  161.0     NaN     NaN
                     mean    sem  size
region manip                          
CA     relocation   0.489  0.058    16
       removal      0.478  0.049    18
       replication  0.429  0.047    16
DG     relocation   0.432  0.040    35
       removal      0.586  0.036    41
       replication  0.490  0.036    41

smoothed maps, M5 b field mask afr n = 149 (paper df 164 imply 170)
                sum_sq     df       F  PR(>F)
region          0.1717    1.0  3.0610  0.0823
manip           0.0014    2.0  0.0128  0.9873
region x manip  0.0841    2.0  0.7499  0.4743
Residual        8.0230  143.0     NaN     NaN
smoothed maps, M5 b field mask log_afr n = 149 (paper df 164 imply 170)
                 sum_sq     df       F  PR(>F)
region           0.1696    1.0  2.3962  0.1238
manip            0.0320    2.0  0.2261  0.7979
region x manip   0.1022    2.0  0.7220  0.4876
Residual        10.1240  143.0     NaN     NaN
                     mean    sem  size
region manip                          
CA     relocation   0.431  0.053    15
       removal      0.376  0.053    17
       replication  0.397  0.050    15
DG     relocation   0.436  0.039    30
       removal      0.506  0.045    36
       replication  0.483  0.042    36

M2 a, M5 a field mask afr n = 120 (paper df 164 imply 170)
                sum_sq     df       F  PR(>F)
region          0.0049    1.0  0.0970  0.7560
manip           0.0818    2.0  0.8095  0.4476
region x manip  0.0169    2.0  0.1678  0.8457
Residual        5.7567  114.0     NaN     NaN
M2 a, M5 a field mask log_afr n = 120 (paper df 164 imply 170)
                sum_sq     df       F  PR(>F)
region          0.0003    1.0  0.0059  0.9388
manip           0.0320    2.0  0.3389  0.7132
region x manip  0.0228    2.0  0.2419  0.7855
Residual        5.3817  114.0     NaN     NaN
                     mean    sem  size
region manip                          
CA     relocation   0.508  0.055    15
       removal      0.517  0.069    15
       replication  0.468  0.042    15
DG     relocation   0.492  0.044    25
       removal      0.561  0.048    25
       replication  0.478  0.044    25

M2 a, M5 b field mask afr n = 149 (paper df 164 imply 170)
                sum_sq     df       F  PR(>F)
region          0.0548    1.0  1.0902  0.2982
manip           0.0526    2.0  0.5229  0.5939
region x manip  0.0351    2.0  0.3492  0.7058
Residual        7.1939  143.0     NaN     NaN
M2 a, M5 b field mask log_afr n = 149 (paper df 164 imply 170)
                sum_sq     df       F  PR(>F)
region          0.0523    1.0  1.0679  0.3032
manip           0.0263    2.0  0.2687  0.7648
region x manip  0.0274    2.0  0.2801  0.7561
Residual        7.0035  143.0     NaN     NaN
                     mean    sem  size
region manip                          
CA     relocation   0.435  0.050    15
       removal      0.458  0.065    17
       replication  0.421  0.048    15
DG     relocation   0.431  0.036    30
       removal      0.507  0.041    36
       replication  0.499  0.037    36

variant, smoothed maps M5 a, without ['140731_WT15_testbox1', '140803_WT16_rotated90dcircleintestbox2'] : n = 164 p = [0.4003, 0.1909, 0.2877]

Result: Reproduced, resting on the M2 and M5 assumptions. With the field mask from the data set's smoothed maps (M5 a, adopted; 167 cell and manipulation values against the 170 the paper's df imply) no effect of region, manipulation or their interaction is significant, raw or log (smallest p 0.20). The other masks agree: smoothed maps with M5 (b) (149 values, smallest p 0.082) and unsmoothed maps with M5 (a) (120 values) or (b) (149 values), smallest p 0.30; so does leaving out the two sessions that fail the clock check (164 values, smallest p 0.19).

tables1-dg-ca-similar¶

The discharge properties of DG and CA place cells in the circular environment did not differ.

In [17]:
C = E[E.cond.isin(["standard", "rotated"])].groupby(["cell", "region"])[["rate", "info_bits_s", "info_bits_spike", "coherence", "mean_isi_ms", "pct_isi_10", "fields_a"]].mean().reset_index()
rows = []
for col in ["rate", "info_bits_s", "info_bits_spike", "coherence", "mean_isi_ms", "pct_isi_10", "fields_a"]:
    a = H.anova1([C[C.region == "DG"][col], C[C.region == "CA"][col]])
    rows.append(dict(prop=col, DG_mean=a["means"][0], DG_sem=C[C.region == "DG"][col].sem(), CA_mean=a["means"][1], CA_sem=C[C.region == "CA"][col].sem(),
                     p_anova=a["p"], p_welch=a["welch_p"], p_kw=a["kw_p"], levene_p=a["levene_p"],
                     shapiro_p=min(stats.shapiro(C[C.region == g][col].dropna()).pvalue for g in ["DG", "CA"])))
T1 = pd.DataFrame(rows); print("n cells:", C.region.value_counts().to_dict()); print(T1.round(4).to_string())
print("expected: rate DG 0.96+/-0.31, CA 0.86+/-0.25; info DG 1.31+/-0.22, CA 1.30+/-0.31 bits/s; coherence DG 0.46+/-0.06, CA 0.51+/-0.08")
T1i = T1.set_index("prop")
for col, lab in [("rate", "rate"), ("info_bits_s", "information, bits/s"), ("info_bits_spike", "information, bits/spike (variant)"), ("coherence", "coherence")]:
    for reg, e, tol in {"rate": [("DG", .96, .31), ("CA", .86, .25)], "info_bits_s": [("DG", 1.31, .22), ("CA", 1.30, .31)],
                        "info_bits_spike": [("DG", 1.31, .22), ("CA", 1.30, .31)], "coherence": [("DG", .46, .06), ("CA", .51, .08)]}[col]:
        v = T1i.loc[col, f"{reg}_mean"]
        print(f"   {reg} {lab}: {v:.3f} against {e} +/- {tol}: {'within' if abs(v - e) <= tol else 'outside'} tolerance")
Cs = EM["s"][EM["s"].cond.isin(["standard", "rotated"])].groupby(["cell", "region"]).fields_a.mean().reset_index()
a = H.anova1([Cs[Cs.region == "DG"].fields_a, Cs[Cs.region == "CA"].fields_a])
print(f"field number on the smoothed maps (M5 a), circular sessions: DG {a['means'][0]:.2f}, CA {a['means'][1]:.2f} (Table S1 1.48 and 1.19); ANOVA p = {a['p']:.3f}, Kruskal-Wallis p = {a['kw_p']:.3f}")
n cells: {'DG': 45, 'CA': 20}
              prop    DG_mean    DG_sem    CA_mean     CA_sem  p_anova  p_welch    p_kw  levene_p  shapiro_p
0             rate     0.9522    0.1572     0.8498     0.1264   0.6847   0.6134  0.5794    0.3340     0.0000
1      info_bits_s     0.8268    0.1057     0.7865     0.1056   0.8177   0.7887  0.7653    0.6102     0.0000
2  info_bits_spike     1.3191    0.1081     1.3377     0.1652   0.9250   0.9257  0.8982    0.6789     0.0032
3        coherence     0.5390    0.0460     0.6338     0.0663   0.2518   0.2475  0.2438    0.9496     0.0393
4      mean_isi_ms  3858.3819  772.0390  3909.1072  1366.5021   0.9726   0.9744  0.6595    0.9173     0.0000
5       pct_isi_10    11.5557    1.2353    14.6120     2.0847   0.1914   0.2161  0.1862    0.6010     0.0049
6         fields_a     0.7074    0.0761     0.7708     0.1073   0.6396   0.6324  0.5473    0.9103     0.0167
expected: rate DG 0.96+/-0.31, CA 0.86+/-0.25; info DG 1.31+/-0.22, CA 1.30+/-0.31 bits/s; coherence DG 0.46+/-0.06, CA 0.51+/-0.08
   DG rate: 0.952 against 0.96 +/- 0.31: within tolerance
   CA rate: 0.850 against 0.86 +/- 0.25: within tolerance
   DG information, bits/s: 0.827 against 1.31 +/- 0.22: outside tolerance
   CA information, bits/s: 0.787 against 1.3 +/- 0.31: outside tolerance
   DG information, bits/spike (variant): 1.319 against 1.31 +/- 0.22: within tolerance
   CA information, bits/spike (variant): 1.338 against 1.3 +/- 0.31: within tolerance
   DG coherence: 0.539 against 0.46 +/- 0.06: outside tolerance
   CA coherence: 0.634 against 0.51 +/- 0.08: outside tolerance
field number on the smoothed maps (M5 a), circular sessions: DG 1.51, CA 1.45 (Table S1 1.48 and 1.19); ANOVA p = 0.759, Kruskal-Wallis p = 0.671

Result: Partially reproduced. No property differs between DG and CA by ANOVA, Welch's ANOVA or Kruskal-Wallis (smallest p 0.19). Firing rates (DG 0.95, CA 0.85 AP/s) are within tolerance. Information content is outside tolerance as bits per second (0.83 and 0.79 against 1.31 and 1.30) and within it as bits per spike (1.32 and 1.34), the variant; Table S1 labels it bits/s (a question for a reader). Coherence (0.54 and 0.63) is outside the tolerance of 0.46 ± 0.06 and 0.51 ± 0.08. Field numbers on the data set's smoothed maps are 1.51 (DG) and 1.45 (CA), not different (p = 0.76). The mean ISI of the table (5.77 ms) is not what the files give for a mean ISI (3858 ms), so that row measures something else.

Place avoidance task: sessions and single-cell measures (Figure 3, Table S2)¶

Sessions of each mouse come from the TS names: Hab pretraining, Ini1 training 1, Ini2 training 2, Conf conflict. The cluster names (tetrode P, cluster C) are taken to be the same unit in every session of a day, as the paper's lists give one entry per cell for the whole day (an assumption: the files do not say how clusters were matched across sessions).

Place fields here use our own smoothing (reading "t", H.smooth_maps), adopted for this task because four of its sessions (WT15Hab1, WT16Hab1, 150720_WT19Ini1_2, 150720_WT19Conf1_2) have deposited maps on a 41 x 41 grid whose pixel mapping is not described, so the authors' smoothed maps cannot be used for every session of a mouse. Reading "s" (deposited smoothed maps where on the grid, our smoothing elsewhere) and the unsmoothed readings are shown beside it.

In [18]:
SESS = {}
for s, v in AV.items():
    m = v["meta"]; SESS.setdefault(m["mouse"], {}).setdefault(m["kind"], []).append(s)
for mo in SESS:
    for k in SESS[mo]:
        SESS[mo][k] = sorted(SESS[mo][k])
for mo, d in SESS.items():
    print(mo, {k: d.get(k) for k in ["pretraining", "training1", "training2", "conflict"]})

def av_measures(p, d, frame, sm=None, min_occ=0.0):
    x, y = (p["rx"], p["ry"]) if frame == "room" else (p["ax"], p["ay"])
    q = dict(rx=x, ry=y, fs=p["fs"])
    return cell_session_measures(q, d, min_occ, sm)

rows = []
for s, v in AV.items():
    for u, d in v["units"].items():
        for fr in ["room", "arena"]:
            m = av_measures(v["pos"], d, fr, H.deposited_maps(s, u[1], u[2], fr, env=False))
            m["sm_grid"] = None if H.deposited_maps(s, u[1], u[2], fr, env=False)[0] is None else H.deposited_maps(s, u[1], u[2], fr, env=False)[0].shape[0]
            m.update(session=s, mouse=v["meta"]["mouse"], kind=v["meta"]["kind"], cell=u, cls=d["cls"], frame=fr)
            rows.append(m)
A = pd.DataFrame(rows)
A["cond"] = A.kind.replace({"training1": "training", "training2": "training"})
print("smoothed maps, place avoidance: source by session (deposited 41 x 41 maps are replaced by our smoothing):")
print(A.groupby(["sm_src", "sm_grid"]).session.unique().map(sorted).to_string())
print("cell-session-frame rows:", len(A), "; place cells per condition:", A[(A.cls == "pc") & (A.frame == "room")].groupby("cond").cell.nunique().to_dict(),
      "; interneurons:", A[(A.cls == "int") & (A.frame == "room")].groupby("cond").cell.nunique().to_dict())
WT15 {'pretraining': ['WT15Hab1'], 'training1': ['WT15Ini1_2'], 'training2': ['WT15Ini2_1'], 'conflict': None}
WT16 {'pretraining': ['WT16Hab1'], 'training1': None, 'training2': ['WT16Ini2_1'], 'conflict': ['WT16Conf1_1']}
WT19 {'pretraining': ['150720_WT19Hab1'], 'training1': ['150720_WT19Ini1_2'], 'training2': ['150720_WT19Ini2_2'], 'conflict': ['150720_WT19Conf1_2']}
WT20 {'pretraining': ['150929_PIC_WT20_2Hab2_DG', '150929_PIC_WT20_3Hab3_DG'], 'training1': ['150929_PIC_WT20_4Ini1_2_DG'], 'training2': ['150929_PIC_WT20_5Ini2_2_DG'], 'conflict': ['150929_PIC_WT20_6Conf1_2_DG']}
WT26 {'pretraining': ['151215_WT26Hab1', '151215_WT26Hab2'], 'training1': ['151215_WT26Ini1_2'], 'training2': ['151215_WT26Ini2_2'], 'conflict': ['151215_WT26Conf1_2']}
WT27 {'pretraining': ['151215_WT27Hab1', '151215_WT27Hab2'], 'training1': ['151215_WT27Ini1_2'], 'training2': ['151215_WT27Ini2_2'], 'conflict': ['151215_WT27Conf1_2']}
smoothed maps, place avoidance: source by session (deposited 41 x 41 maps are replaced by our smoothing):
sm_src     sm_grid
deposited  32         [150720_WT19Hab1, 150720_WT19Ini2_2, 150929_PI...
own        41         [150720_WT19Conf1_2, 150720_WT19Ini1_2, WT15Ha...
cell-session-frame rows: 546 ; place cells per condition: {'conflict': 36, 'pretraining': 42, 'training': 42} ; interneurons: {'conflict': 18, 'pretraining': 21, 'training': 21}
In [19]:
def av_pairs(reading):
    """Session pairs per manipulation under the claims file's M11 readings."""
    out = {}
    for mo, d in SESS.items():
        pre = d.get("pretraining", []); t = d.get("training1", []) + d.get("training2", []); cf = d.get("conflict", [])
        rep = ([(pre[0], pre[1])] if len(pre) > 1 else []) + ([(t[0], t[1])] if len(t) > 1 else [])
        if reading == "a":
            add = [(pre[-1], t[0])] if pre and t else []
            rel = [(t[-1], cf[0])] if t and cf else []
        else:
            add = [(a, b) for a in pre for b in t]
            rel = [(a, cf[0]) for a in t] if cf else []
        out[mo] = dict(replication=rep, addition=add, relocation=rel)
    return out

def first_session(mo):
    d = SESS[mo]
    for k in ["pretraining", "training1", "training2", "conflict"]:
        if d.get(k):
            return d[k][0]

AR = A.set_index(["session", "cell", "frame"])
def field_change(a_r, b_r, mask, maskfield):
    """M4 field rate change; a mask from smoothed maps is applied to the same smoothed maps."""
    sp, oc = {"s": ("sspk", "socc"), "t": ("tspk", "tocc")}.get(maskfield[len("fieldmask_"):][:1] if len(maskfield) > len("fieldmask_a") else "", ("spk", "occ"))
    ra = a_r[sp][mask].sum() / max(a_r[oc][mask].sum(), 1e-9); rb = b_r[sp][mask].sum() / max(b_r[oc][mask].sum(), 1e-9)
    return H.rate_change(ra, rb)

def av_field_values(reading, maskfield, cls="pc"):
    """|M4 field rate change| per cell and manipulation, the mask from the first session of the day."""
    rows = []
    for mo, man in av_pairs(reading).items():
        f0 = first_session(mo)
        for c in A[(A.mouse == mo) & (A.cls == cls)].cell.unique():
            mask = AR.loc[(f0, c, "room"), maskfield]
            if mask is None:
                continue
            for mname, pairs in man.items():
                v = [abs(field_change(AR.loc[(s1, c, "room")], AR.loc[(s2, c, "room")], mask, maskfield)) for s1, s2 in pairs
                     if (s1, c, "room") in AR.index and (s2, c, "room") in AR.index]
                if v:
                    rows.append(dict(mouse=mo, cell=c, manip=mname, afr=np.nanmean(v)))
    return pd.DataFrame(rows)

def av_manip_values(reading, cls="pc", maskfield="fieldmask_a"):
    rows = []
    for mo, man in av_pairs(reading).items():
        cells_m = A[(A.mouse == mo) & (A.cls == cls)].cell.unique()
        f0 = first_session(mo)
        for c in cells_m:
            mask = AR.loc[(f0, c, "room"), maskfield]
            for mname, pairs in man.items():
                vals = []
                for s1, s2 in pairs:
                    if (s1, c, "room") not in AR.index or (s2, c, "room") not in AR.index:
                        continue
                    a_r, b_r = AR.loc[(s1, c, "room")], AR.loc[(s2, c, "room")]
                    a_a, b_a = AR.loc[(s1, c, "arena")], AR.loc[(s2, c, "arena")]
                    zr = H.map_stability(a_r.rmap, b_r.rmap); za = H.map_stability(a_a.rmap, b_a.rmap)
                    fr = np.nan
                    if mask is not None:
                        fr = field_change(a_r, b_r, mask, maskfield)
                    vals.append(dict(stab=np.nanmax([zr, za]), stab_room=zr, stab_arena=za, rr=H.rate_change(a_r.rate, b_r.rate), fr=fr))
                if vals:
                    v = pd.DataFrame(vals)
                    rows.append(dict(mouse=mo, cell=c, manip=mname, n_pairs=len(v), stab=v.stab.mean(), stab_room=v.stab_room.mean(),
                                     stab_arena=v.stab_arena.mean(), arr=v.rr.abs().mean(), rr=v.rr.mean(), afr=v.fr.abs().mean(), fr=v.fr.mean()))
    return pd.DataFrame(rows)

MV = {r: av_manip_values(r) for r in "ab"}
MVI = {r: av_manip_values(r, "int") for r in "ab"}
for r in "ab":
    print(f"M11 reading {r}: place cell values per manipulation", MV[r].groupby("manip").size().to_dict(),
          "total", len(MV[r]), "(paper H2,117 implies 120); interneurons", MVI[r].groupby("manip").size().to_dict(), "(paper H2,57 implies 60)")
print("place cells without a replication pair (no second pretraining or training session):",
      sorted(set(A[A.cls == "pc"].cell) - set(MV["a"][MV["a"].manip == "replication"].cell)))
M11 reading a: place cell values per manipulation {'addition': 42, 'relocation': 36, 'replication': 37} total 115 (paper H2,117 implies 120); interneurons {'addition': 21, 'relocation': 18, 'replication': 19} (paper H2,57 implies 60)
M11 reading b: place cell values per manipulation {'addition': 42, 'relocation': 36, 'replication': 37} total 115 (paper H2,117 implies 120); interneurons {'addition': 21, 'relocation': 18, 'replication': 19} (paper H2,57 implies 60)
place cells without a replication pair (no second pretraining or training session): [('WT16', 1, 1), ('WT16', 1, 2), ('WT16', 1, 3), ('WT16', 1, 5), ('WT16', 3, 2)]

tables2-firing-quality-similar¶

Measures of spatial firing quality of DG place cells did not differ across pretraining, training and conflict.

In [20]:
P = A[A.cls == "pc"]
props = ["rate", "pct_isi_10", "mean_isi_ms", "coherence", "info_bits_s", "info_bits_spike", "fields_a", "fields_ta", "fields_sa"]
Tc = P.pivot_table(index=["cell", "cond"], columns="frame", values=props, aggfunc="mean")
Tc.columns = [f"{a}_{b}" for a, b in Tc.columns]; Tc = Tc.reset_index()
use = ["rate_room", "pct_isi_10_room", "mean_isi_ms_room", "coherence_room", "info_bits_s_room", "info_bits_spike_room", "fields_a_room", "fields_ta_room", "fields_sa_room",
       "coherence_arena", "info_bits_s_arena", "info_bits_spike_arena", "fields_a_arena", "fields_ta_arena", "fields_sa_arena"]
rows = []
for col in use:
    g = [Tc[Tc.cond == k][col] for k in ["pretraining", "training", "conflict"]]
    a = H.anova1(g)
    rows.append(dict(prop=col, pre=a["means"][0], train=a["means"][1], conf=a["means"][2], n=a["n"], p_anova=a["p"], p_welch=a["welch_p"], p_kw=a["kw_p"], levene_p=a["levene_p"]))
T2 = pd.DataFrame(rows); print(T2.round(4).to_string())
print("expected: rate 0.99+/-0.33, 0.87+/-0.25, 0.82+/-0.31; room info pre 1.6+/-0.24, conflict 1.75+/-0.35 bits/s")
T2i = T2.set_index("prop")
chk = [("rate pretraining", T2i.loc["rate_room", "pre"], 0.99, 0.33), ("rate training", T2i.loc["rate_room", "train"], 0.87, 0.25),
       ("rate conflict", T2i.loc["rate_room", "conf"], 0.82, 0.31),
       ("room info pretraining, bits/s", T2i.loc["info_bits_s_room", "pre"], 1.6, 0.24), ("room info conflict, bits/s", T2i.loc["info_bits_s_room", "conf"], 1.75, 0.35),
       ("room info pretraining, bits/spike (variant)", T2i.loc["info_bits_spike_room", "pre"], 1.6, 0.24),
       ("room info conflict, bits/spike (variant)", T2i.loc["info_bits_spike_room", "conf"], 1.75, 0.35)]
for lab, v, e, tol in chk:
    print(f"   {lab}: {v:.3f} against {e} +/- {tol}: {'within' if abs(v - e) <= tol else 'outside'} tolerance")
print("properties with p < 0.05 in any test:", T2[(T2[["p_anova", "p_welch", "p_kw"]] < 0.05).any(axis=1)].prop.tolist())
print("by mouse, rate (AP/s):"); print(Tc.assign(mouse=Tc.cell.map(lambda c: c[0])).groupby(["mouse", "cond"]).rate_room.mean().unstack().round(2).to_string())
                     prop        pre      train       conf             n  p_anova  p_welch    p_kw  levene_p
0               rate_room     0.9842     0.8600     0.8242  [42, 42, 36]   0.7431   0.7752  0.5246    0.8268
1         pct_isi_10_room    13.1692    12.5445    11.6136  [42, 42, 36]   0.7026   0.6961  0.8281    0.7009
2        mean_isi_ms_room  2809.6597  4537.7711  5220.1060  [42, 42, 36]   0.3548   0.2176  0.5832    0.3660
3          coherence_room     0.4920     0.3849     0.3153  [42, 42, 36]   0.0109   0.0152  0.0101    0.6439
4        info_bits_s_room     1.1470     0.8551     0.7325  [42, 42, 36]   0.0771   0.1028  0.1427    0.2123
5    info_bits_spike_room     1.5890     1.4381     1.6037  [42, 42, 36]   0.6131   0.6031  0.5353    0.3250
6           fields_a_room     0.4881     0.3571     0.1944  [42, 42, 36]   0.0912   0.0715  0.0302    0.0912
7          fields_ta_room     0.9405     1.1786     1.1111  [42, 42, 36]   0.4238   0.3940  0.5663    0.9811
8          fields_sa_room     1.4286     1.3571     1.1389  [42, 42, 36]   0.4315   0.4257  0.5054    0.6336
9         coherence_arena     0.3337     0.3053     0.2829  [42, 42, 36]   0.5621   0.5372  0.4149    0.4150
10      info_bits_s_arena     0.8681     0.8051     0.7399  [42, 42, 36]   0.5973   0.6136  0.4354    0.8941
11  info_bits_spike_arena     1.3588     1.4237     1.5675  [42, 42, 36]   0.4898   0.5283  0.7552    0.2235
12         fields_a_arena     0.6667     0.2262     0.1389  [42, 42, 36]   0.0018   0.0108  0.0045    0.0018
13        fields_ta_arena     1.4286     1.4048     1.1667  [42, 42, 36]   0.6496   0.6954  0.2060    0.8848
14        fields_sa_arena     2.2381     2.0833     1.1111  [42, 42, 36]   0.0017   0.0005  0.0013    0.0756
expected: rate 0.99+/-0.33, 0.87+/-0.25, 0.82+/-0.31; room info pre 1.6+/-0.24, conflict 1.75+/-0.35 bits/s
   rate pretraining: 0.984 against 0.99 +/- 0.33: within tolerance
   rate training: 0.860 against 0.87 +/- 0.25: within tolerance
   rate conflict: 0.824 against 0.82 +/- 0.31: within tolerance
   room info pretraining, bits/s: 1.147 against 1.6 +/- 0.24: outside tolerance
   room info conflict, bits/s: 0.732 against 1.75 +/- 0.35: outside tolerance
   room info pretraining, bits/spike (variant): 1.589 against 1.6 +/- 0.24: within tolerance
   room info conflict, bits/spike (variant): 1.604 against 1.75 +/- 0.35: within tolerance
properties with p < 0.05 in any test: ['coherence_room', 'fields_a_room', 'fields_a_arena', 'fields_sa_arena']
by mouse, rate (AP/s):
cond   conflict  pretraining  training
mouse                                 
WT15        NaN         0.85      0.64
WT16       0.78         0.84      1.10
WT19       0.77         0.68      0.59
WT20       0.46         0.46      0.31
WT26       0.45         0.89      0.73
WT27       1.82         2.17      1.89

Result: Not reproduced. Firing rates are within tolerance (0.98, 0.86 and 0.82 AP/s) and do not differ (p = 0.74), but room-frame coherence differs across conditions (0.49, 0.38, 0.32; ANOVA p = 0.011, Kruskal-Wallis p = 0.010). Room information is 1.15 and 0.73 bits/s in pretraining and conflict, outside the tolerance of 1.6 and 1.75; as bits per spike, the variant, it is 1.59 and 1.60, within it. Arena-frame field counts differ on unsmoothed maps (p = 0.0018) and on the data set's smoothed maps (p = 0.0017), and room-frame field counts on unsmoothed maps differ by Kruskal-Wallis (p = 0.030; ANOVA p = 0.091), but neither differs with our smoothing, the reading adopted for this task (room p = 0.42, arena p = 0.65).

fig3c-stability-no-difference¶

DG rate map stability did not differ across the replication, shock addition and shock relocation manipulations.

In [21]:
names = ["replication", "addition", "relocation"]
for r in "ab":
    V = MV[r]
    g = [V[V.manip == k].stab for k in names]
    kw = stats.kruskal(*g)
    print(f"M11 reading {r}: n = {[len(x) for x in g]}, medians {[round(x.median(), 3) for x in g]}, means {[round(x.mean(), 3) for x in g]}; Kruskal-Wallis H = {kw.statistic:.2f}, p = {kw.pvalue:.3f}")
    print("   room frame only: H = %.2f, p = %.3f" % stats.kruskal(*[V[V.manip == k].stab_room for k in names]))
    print("   by mouse (mean z):", V.groupby(["mouse", "manip"]).stab.mean().unstack()[names].round(2).to_dict("index"))
print("stability range (z):", MV["a"].stab.min().round(2), MV["a"].stab.max().round(2))
M11 reading a: n = [37, 42, 36], medians [np.float64(0.338), np.float64(0.333), np.float64(0.271)], means [np.float64(0.37), np.float64(0.373), np.float64(0.301)]; Kruskal-Wallis H = 4.74, p = 0.093
   room frame only: H = 4.49, p = 0.106
   by mouse (mean z): {'WT15': {'replication': 0.28, 'addition': 0.19, 'relocation': nan}, 'WT16': {'replication': nan, 'addition': 0.33, 'relocation': 0.3}, 'WT19': {'replication': 0.27, 'addition': 0.28, 'relocation': 0.27}, 'WT20': {'replication': 0.52, 'addition': 0.46, 'relocation': 0.35}, 'WT26': {'replication': 0.39, 'addition': 0.41, 'relocation': 0.32}, 'WT27': {'replication': 0.38, 'addition': 0.51, 'relocation': 0.25}}
M11 reading b: n = [37, 42, 36], medians [np.float64(0.338), np.float64(0.292), np.float64(0.285)], means [np.float64(0.37), np.float64(0.317), np.float64(0.312)]; Kruskal-Wallis H = 3.51, p = 0.173
   room frame only: H = 6.13, p = 0.047
   by mouse (mean z): {'WT15': {'replication': 0.28, 'addition': 0.17, 'relocation': nan}, 'WT16': {'replication': nan, 'addition': 0.33, 'relocation': 0.3}, 'WT19': {'replication': 0.27, 'addition': 0.26, 'relocation': 0.43}, 'WT20': {'replication': 0.52, 'addition': 0.44, 'relocation': 0.31}, 'WT26': {'replication': 0.39, 'addition': 0.32, 'relocation': 0.28}, 'WT27': {'replication': 0.38, 'addition': 0.37, 'relocation': 0.25}}
stability range (z): 0.07 0.88

Result: Reproduced, resting on the M11 assumption. Stability (higher of room and arena frame) does not differ across replication, shock addition and shock relocation: Kruskal-Wallis p = 0.17 under the adopted reading (b) and p = 0.093 under reading (a), with 115 values against the paper's 120.

fig3c-replication-vs-relocation¶

DG rate map stability was the same for the replication and the shock relocation comparisons.

In [22]:
for r in "ab":
    V = MV[r]
    a, b = V[V.manip == "replication"].stab, V[V.manip == "relocation"].stab
    w = stats.ranksums(a, b); mw = stats.mannwhitneyu(a, b)
    print(f"M11 reading {r}: replication n={len(a)} median {a.median():.3f}; relocation n={len(b)} median {b.median():.3f}; rank-sum z = {w.statistic:.2f}, p = {w.pvalue:.3f}; rank sum of the smaller group = {stats.rankdata(np.r_[a, b])[:len(a)].sum() if len(a) <= len(b) else stats.rankdata(np.r_[a, b])[len(a):].sum():.0f}")
M11 reading a: replication n=37 median 0.338; relocation n=36 median 0.271; rank-sum z = 1.95, p = 0.051; rank sum of the smaller group = 1155
M11 reading b: replication n=37 median 0.338; relocation n=36 median 0.285; rank-sum z = 1.48, p = 0.139; rank sum of the smaller group = 1198

Result: Reproduced, resting on the M11 assumption. Replication and relocation stabilities do not differ by the rank-sum test (z = 1.48, p = 0.14 under reading (b); z = 1.95, p = 0.051 under reading (a)), with relocation lower in both.

fig3c-stability-vs-environment¶

DG stability in the place avoidance task was similar to DG stability in the replication condition of the environment experiment but weaker than CA stability there.

In [23]:
for r in "ab":
    V = MV[r]
    task = V[V.manip.isin(["replication", "relocation"])].stab
    for rd in "ab":
        Pe = PC_env[rd]
        dg = Pe[(Pe.region == "DG") & (Pe.manip == "replication")].stab
        ca = Pe[(Pe.region == "CA") & (Pe.manip == "replication")].stab
        w1 = stats.ranksums(task, dg); w2 = stats.ranksums(task, ca)
        print(f"task M11 {r}, env M2 {rd}: task n={len(task)} median {task.median():.3f}; env DG n={len(dg)} median {dg.median():.3f} (z={w1.statistic:.2f}, p={w1.pvalue:.3f}); env CA n={len(ca)} median {ca.median():.3f} (z={w2.statistic:.2f}, p={w2.pvalue:.4f})")
task M11 a, env M2 a: task n=73 median 0.303; env DG n=42 median 0.309 (z=-0.05, p=0.963); env CA n=17 median 0.506 (z=-2.74, p=0.0062)
task M11 a, env M2 b: task n=73 median 0.303; env DG n=42 median 0.352 (z=-0.80, p=0.423); env CA n=17 median 0.516 (z=-3.29, p=0.0010)
task M11 b, env M2 a: task n=73 median 0.305; env DG n=42 median 0.309 (z=0.06, p=0.954); env CA n=17 median 0.506 (z=-2.63, p=0.0084)
task M11 b, env M2 b: task n=73 median 0.305; env DG n=42 median 0.352 (z=-0.64, p=0.519); env CA n=17 median 0.516 (z=-3.12, p=0.0018)

Result: Reproduced. Task stability (replication and relocation pooled, median z 0.30) does not differ from DG replication stability in the environment experiment (p 0.42 to 0.96 across readings) and is below CA replication stability (median 0.51; p 0.0010 to 0.0084).

fig3d-rate-remapping-task¶

DG place cell rate changes, overall and in the primary field, were larger for shock addition and shock relocation than for replication.

In [24]:
for r in "ab":
    for col, lab in [("arr", "whole-cell |ratio|")]:
        V = MV[r].dropna(subset=[col])
        g = [V[V.manip == k][col] for k in names]
        kw = stats.kruskal(*g)
        l = H.lsd_ranks(g, names)
        print(f"M11 {r}, {lab}: n={[len(x) for x in g]}, means {[round(x.mean(), 3) for x in g]}, H = {kw.statistic:.2f}, p = {kw.pvalue:.4f}")
        print("   LSD on ranks:", [(a, b, round(d, 1), round(p, 4)) for a, b, d, p in l[["a", "b", "diff", "p"]].values])
# Field part under every field rule: M5 (a) and (b) on the unsmoothed maps (M2 a) and on the
# data set's smoothed maps (adopted), each under both M11 readings.
FR3D = []
for r in "ab":
    for mk, lab in [("fieldmask_ta", "own smoothing, M5 a (adopted)"), ("fieldmask_tb", "own smoothing, M5 b"), ("fieldmask_sa", "deposited smoothed where on the grid, M5 a"),
                    ("fieldmask_sb", "deposited smoothed where on the grid, M5 b"), ("fieldmask_a", "M2 a, M5 a"), ("fieldmask_b", "M2 a, M5 b")]:
        V = av_field_values(r, mk); g = [V[V.manip == k].afr for k in names]
        kw = stats.kruskal(*g); l = H.lsd_ranks(g, names)
        FR3D.append(dict(M11=r, fields=lab, n=[len(x) for x in g], cells=V.cell.nunique(), means=[round(x.mean(), 3) for x in g], H=kw.statistic, p=kw.pvalue,
                         lsd=[(a, b, round(p, 4)) for a, b, p in l[["a", "b", "p"]].values]))
print(pd.DataFrame(FR3D).round(4).to_string())
print("by mouse, whole-cell |ratio| (M11 a):"); print(MV["a"].groupby(["mouse", "manip"]).arr.mean().unstack()[names].round(2).to_string())
M11 a, whole-cell |ratio|: n=[37, 42, 36], means [np.float64(0.276), np.float64(0.397), np.float64(0.404)], H = 5.68, p = 0.0584
   LSD on ranks: [('replication', 'addition', -14.7, 0.0492), ('replication', 'relocation', -17.0, 0.0292), ('addition', 'relocation', -2.3, 0.7627)]
M11 b, whole-cell |ratio|: n=[37, 42, 36], means [np.float64(0.276), np.float64(0.426), np.float64(0.416)], H = 11.99, p = 0.0025
   LSD on ranks: [('replication', 'addition', -24.5, 0.0009), ('replication', 'relocation', -20.9, 0.0059), ('addition', 'relocation', 3.6, 0.621)]
   M11                                      fields             n  cells                  means       H       p                                                                                                   lsd
0    a               own smoothing, M5 a (adopted)  [23, 26, 23]     26   [0.294, 0.43, 0.388]  2.1317  0.3444  [(replication, addition, 0.1658), (replication, relocation, 0.2844), (addition, relocation, 0.7733)]
1    a                         own smoothing, M5 b  [33, 37, 33]     37  [0.315, 0.446, 0.393]  3.7047  0.1569   [(replication, addition, 0.057), (replication, relocation, 0.2326), (addition, relocation, 0.4912)]
2    a  deposited smoothed where on the grid, M5 a  [30, 33, 30]     33  [0.379, 0.506, 0.409]  3.4131  0.1815  [(replication, addition, 0.0836), (replication, relocation, 0.7293), (addition, relocation, 0.1667)]
3    a  deposited smoothed where on the grid, M5 b  [34, 38, 34]     38  [0.352, 0.448, 0.384]  1.7829  0.4101  [(replication, addition, 0.1893), (replication, relocation, 0.6027), (addition, relocation, 0.4343)]
4    a                                  M2 a, M5 a  [14, 15, 13]     15  [0.413, 0.482, 0.414]  0.9823  0.6119  [(replication, addition, 0.3507), (replication, relocation, 0.8037), (addition, relocation, 0.5056)]
5    a                                  M2 a, M5 b  [32, 34, 30]     34  [0.352, 0.458, 0.474]  1.9384  0.3794  [(replication, addition, 0.2311), (replication, relocation, 0.2314), (addition, relocation, 0.9707)]
6    b               own smoothing, M5 a (adopted)  [23, 26, 23]     26  [0.294, 0.484, 0.419]  6.5284  0.0382  [(replication, addition, 0.0112), (replication, relocation, 0.0913), (addition, relocation, 0.4019)]
7    b                         own smoothing, M5 b  [33, 37, 33]     37  [0.315, 0.481, 0.399]  8.4264  0.0148  [(replication, addition, 0.0037), (replication, relocation, 0.2326), (addition, relocation, 0.0847)]
8    b  deposited smoothed where on the grid, M5 a  [30, 33, 30]     33  [0.379, 0.549, 0.435]  7.1310  0.0283  [(replication, addition, 0.0087), (replication, relocation, 0.3937), (addition, relocation, 0.0742)]
9    b  deposited smoothed where on the grid, M5 b  [34, 38, 34]     38  [0.352, 0.489, 0.404]  5.4897  0.0643  [(replication, addition, 0.0237), (replication, relocation, 0.5301), (addition, relocation, 0.1022)]
10   b                                  M2 a, M5 a  [14, 15, 13]     15  [0.413, 0.564, 0.411]  4.8486  0.0885   [(replication, addition, 0.044), (replication, relocation, 0.8281), (addition, relocation, 0.0765)]
11   b                                  M2 a, M5 b  [32, 34, 30]     34  [0.352, 0.518, 0.474]  5.8309  0.0542  [(replication, addition, 0.0155), (replication, relocation, 0.2213), (addition, relocation, 0.2427)]
by mouse, whole-cell |ratio| (M11 a):
manip  replication  addition  relocation
mouse                                   
WT15          0.18      0.41         NaN
WT16           NaN      0.44        0.42
WT19          0.23      0.38        0.47
WT20          0.29      0.60        0.33
WT26          0.34      0.37        0.45
WT27          0.29      0.21        0.33

Result: Partially reproduced, resting on the M11, M2 and M5 assumptions. Whole-cell rate changes are larger for shock addition and relocation than for replication under the adopted reading (b) (means 0.43, 0.42 against 0.28; H = 12.0, p = 0.0025; LSD on ranks p = 0.0009 and 0.0059, addition against relocation p = 0.62), but not under reading (a) (p = 0.058). Field rate changes on smoothed maps differ across manipulations under M11 reading (b) (adopted mask, our smoothing with M5 (a): 26 cells, H = 6.53, p = 0.038; p 0.015 to 0.064 with the other smoothed masks), with addition above replication (p = 0.011) but not relocation (p = 0.091); no mask under either M11 reading puts relocation above replication (p 0.091 to 0.83), and under M11 reading (a) no mask gives a difference (p 0.16 to 0.61).

interneuron-rate-remapping¶

Putative interneurons showed the same pattern of rate change, replication less than shock addition equal to shock relocation.

In [25]:
for r in "ab":
    V = MVI[r]
    g = [V[V.manip == k].arr for k in names]
    kw = stats.kruskal(*g); l = H.lsd_ranks(g, names)
    print(f"M11 {r}: n={[len(x) for x in g]}, means {[round(x.mean(), 3) for x in g]}, H = {kw.statistic:.2f}, p = {kw.pvalue:.4f}")
    print("   LSD on ranks:", [(a, b, round(d, 1), round(p, 4)) for a, b, d, p in l[["a", "b", "diff", "p"]].values])
M11 a: n=[19, 21, 18], means [np.float64(0.134), np.float64(0.204), np.float64(0.169)], H = 0.65, p = 0.7242
   LSD on ranks: [('replication', 'addition', -1.2, 0.8299), ('replication', 'relocation', -4.3, 0.4457), ('addition', 'relocation', -3.2, 0.5684)]
M11 b: n=[19, 21, 18], means [np.float64(0.134), np.float64(0.224), np.float64(0.187)], H = 2.65, p = 0.2653
   LSD on ranks: [('replication', 'addition', -6.8, 0.2081), ('replication', 'relocation', -8.5, 0.1308), ('addition', 'relocation', -1.7, 0.754)]

Result: Not reproduced. Interneuron rate changes are ordered replication < relocation < addition in the means (0.13, 0.19, 0.22 under reading (b)), but Kruskal-Wallis gives p = 0.27 (reading (b)) and p = 0.72 (reading (a)), against p = 0.01.

Place avoidance behaviour (Figure 3B, speed)¶

Shock zones come from the shock-on Tracker files (ReinforcedSector): the training zone from the training 1 file, the conflict zone from the conflict file. Errors in shock-on sessions are the Tracker's entrances (avoidance state from 0 to 1, "entrance latency"); the shock-off recordings have no sector in their files, so their errors are entrances of the room-frame position into the zone of the preceding shock-on session (geometric), a method checked above against the shock-on files. Errors per meter use the path length of the same positions (Behavioral Procedures: "number of errors (shock zone entries), number of errors per meter, speed").

Variants asked for by the verifier: shock-off errors with an entrance counted only after at least 100 ms outside the zone (3 samples), the rule that best matches the Tracker's count on the shock-on files; the analyses without the four shock-off recordings whose own Tracker files log shocks; and, for WT15, whose only training 2 file is 20 min long, its errors in the first 10 min.

In [26]:
def shock_on_file(mo, kind):
    pat = {"training1": r"Ini1", "training2": r"Ini2", "conflict": r"Conf"}[kind]
    c = DAT[(DAT.folder == "DATfilesPlaceAvoidanceShockON") & (DAT.mouse == mo) & DAT.file.str.contains(pat)]
    return None if c.empty else "data/behavior/DATfilesPlaceAvoidanceShockON/" + c.file.iloc[0]

def path_cm(x, y, fs, step_s=1.0):
    """Path length (cm) from positions sampled every ``step_s`` seconds over tracked samples."""
    k = max(1, int(round(step_s * fs)))
    v = H.tracked(x, y)
    xs, ys, vs = x[::k].astype(float), y[::k].astype(float), v[::k]
    d = np.hypot(np.diff(xs), np.diff(ys)); ok = vs[1:] & vs[:-1]
    return d[ok].sum() / H.PX_PER_CM

ZONES = {}
for mo in SESS:
    f1 = shock_on_file(mo, "training1") or shock_on_file(mo, "training2"); fc = shock_on_file(mo, "conflict")
    ZONES[mo] = dict(training=H.sector_of(H.read_dat(f1)[0]), conflict=H.sector_of(H.read_dat(fc)[0]) if fc else None)
    print(mo, "training zone", ZONES[mo]["training"], "conflict zone", ZONES[mo]["conflict"],
          "separation (deg)", None if fc is None else (ZONES[mo]["conflict"][0] - ZONES[mo]["training"][0]) % 360)

rows = []
for mo in SESS:
    for kind in ["training1", "training2", "conflict"]:
        f = shock_on_file(mo, kind)
        if f:
            m, d = H.read_dat(f)
            st = d.State.values; x, y = d.RoomX.values, d.RoomY.values
            fs = 1000 / np.median(np.diff(d["1msTimeStamp"].values))
            pc = path_cm(x, y, fs)
            rows.append(dict(mouse=mo, kind=kind, shock="on", file=f.split("/")[-1], minutes=float(m["ElapsedTime_ms"]) / 6e4,
                             errors=int(((st[1:] == 1) & (st[:-1] == 0)).sum()), errors_geom=H.count_entries(H.in_sector(x, y, H.sector_of(m)), H.tracked(x, y)),
                             errors_db=H.count_entries(H.in_sector(x, y, H.sector_of(m)), H.tracked(x, y), min_out=3),
                             errors_10min=int(((st[1:] == 1) & (st[:-1] == 0) & (d["1msTimeStamp"].values[1:] - d["1msTimeStamp"].values[0] <= 6e5)).sum()),
                             path_m=pc / 100, path_m_tracker=float(m["ElapsedPath_m"])))
        for s in SESS[mo].get(kind, []):
            p = AV[s]["pos"]; zone = ZONES[mo]["conflict" if kind == "conflict" else "training"]
            pc = path_cm(p["rx"], p["ry"], p["fs"])
            rows.append(dict(mouse=mo, kind=kind, shock="off", file=s, minutes=len(p["rx"]) / p["fs"] / 60,
                             errors=H.count_entries(H.in_sector(p["rx"], p["ry"], zone), H.tracked(p["rx"], p["ry"])), errors_geom=np.nan,
                             errors_db=H.count_entries(H.in_sector(p["rx"], p["ry"], zone), H.tracked(p["rx"], p["ry"]), min_out=3), errors_10min=np.nan,
                             path_m=pc / 100, path_m_tracker=np.nan))
    for s in SESS[mo].get("pretraining", []):
        p = AV[s]["pos"]; pc = path_cm(p["rx"], p["ry"], p["fs"])
        rows.append(dict(mouse=mo, kind="pretraining", shock="off", file=s, minutes=len(p["rx"]) / p["fs"] / 60, errors=np.nan,
                         errors_geom=np.nan, path_m=pc / 100, path_m_tracker=np.nan))
BEH = pd.DataFrame(rows)
BEH["errors_per_m"] = BEH.errors / BEH.path_m
BEH["speed_cm_s"] = BEH.path_m * 100 / (BEH.minutes * 60)
print(BEH.round(2).to_string())
on = BEH[BEH.shock == "on"]
print("path from positions (1-s steps) vs Tracker's ElapsedPath, shock-on files: ratio median",
      round((on.path_m / on.path_m_tracker).median(), 3), "range", round((on.path_m / on.path_m_tracker).min(), 3), round((on.path_m / on.path_m_tracker).max(), 3))
print("geometric vs Tracker entrances, shock-on files: ratio median", round((on.errors_geom / on.errors.replace(0, np.nan)).median(), 2),
      "| sum of absolute differences", int((on.errors_geom - on.errors).abs().sum()))
# A rule closer to the Tracker's: an entrance counts after at least 3 samples (100 ms) outside.
print("geometric with 100 ms outside vs Tracker, shock-on files: ratio median", round((on.errors_db / on.errors.replace(0, np.nan)).median(), 2),
      "| sum of absolute differences", int((on.errors_db - on.errors).abs().sum()))
ON_DAT = [H.read_dat("data/behavior/DATfilesPlaceAvoidanceShockON/" + f) for f in on.file]
for k in [1, 3, 5, 10, 30]:
    e = [H.count_entries(H.in_sector(dd.RoomX.values, dd.RoomY.values, H.sector_of(mm)), H.tracked(dd.RoomX.values, dd.RoomY.values), min_out=k)
         for mm, dd in ON_DAT]
    print(f"   min_out {k:2d} samples: ratio to Tracker median {np.nanmedian(np.array(e) / on.errors.replace(0, np.nan).values):.2f}, sum |diff| {int(np.abs(np.array(e) - on.errors.values).sum())}")
WT15 training zone (135.0, 60.0, 25.5, 127.5) conflict zone (305.0, 60.0, 25.5, 127.5) separation (deg) 170.0
WT16 training zone (135.0, 60.0, 25.5, 127.5) conflict zone (305.0, 60.0, 25.5, 127.5) separation (deg) 170.0
WT19 training zone (135.0, 60.0, 25.5, 127.5) conflict zone (305.0, 60.0, 25.5, 127.5) separation (deg) 170.0
WT20 training zone (135.0, 60.0, 25.5, 127.5) conflict zone (315.0, 60.0, 25.5, 127.5) separation (deg) 180.0
WT26 training zone (225.0, 60.0, 25.5, 127.5) conflict zone (45.0, 60.0, 25.5, 127.5) separation (deg) 180.0
WT27 training zone (225.0, 60.0, 25.5, 127.5) conflict zone (45.0, 60.0, 25.5, 127.5) separation (deg) 180.0
   mouse         kind shock                                file  minutes  errors  errors_geom  errors_db  errors_10min  path_m  path_m_tracker  errors_per_m  speed_cm_s
0   WT15    training1    on                   WT15Ini1_Room.dat    20.00    17.0         21.0       18.0          12.0   38.16           42.70          0.45        3.18
1   WT15    training1   off                          WT15Ini1_2    19.98    32.0          NaN       29.0           NaN   43.14             NaN          0.74        3.60
2   WT15    training2    on                 WT15Ini2.1_Room.dat    20.00     1.0          1.0        1.0           0.0   34.35           42.38          0.03        2.86
3   WT15    training2   off                          WT15Ini2_1    19.98     1.0          NaN        1.0           NaN   34.45             NaN          0.03        2.87
4   WT15     conflict    on                 WT15Conf1__Room.dat    14.27    10.0         12.0       12.0          10.0   21.75           24.20          0.46        2.54
5   WT15  pretraining   off                            WT15Hab1    19.99     NaN          NaN        NaN           NaN   38.70             NaN           NaN        3.23
6   WT16    training1    on                   WT16Ini1_Room.dat    20.00     9.0         14.0       11.0           4.0   20.68           23.42          0.44        1.72
7   WT16    training2    on                   WT16Ini2_Room.dat    10.00     6.0          9.0        6.0           6.0    9.30           10.37          0.64        1.55
8   WT16    training2   off                          WT16Ini2_1    19.99    20.0          NaN       18.0           NaN   41.81             NaN          0.48        3.49
9   WT16     conflict    on                  WT16Conf1_Room.dat    15.00     1.0          1.0        1.0           0.0   15.15           17.31          0.07        1.68
10  WT16     conflict   off                         WT16Conf1_1    19.99    15.0          NaN       14.0           NaN   33.99             NaN          0.44        2.83
11  WT16  pretraining   off                            WT16Hab1    19.99     NaN          NaN        NaN           NaN   32.73             NaN           NaN        2.73
12  WT19    training1    on                   WT19Ini1_Room.dat    20.00     8.0         10.0        8.0           7.0   27.98           31.84          0.29        2.33
13  WT19    training1   off                   150720_WT19Ini1_2    19.99    29.0          NaN       25.0           NaN   32.85             NaN          0.88        2.74
14  WT19    training2    on          150720_WT19Ini2_1_Room.dat    10.00     9.0         10.0        8.0           9.0   13.91           15.74          0.65        2.32
15  WT19    training2   off                   150720_WT19Ini2_2    19.98    36.0          NaN       36.0           NaN   50.77             NaN          0.71        4.23
16  WT19     conflict    on        150720_WT19Conf1_12_Room.dat    20.00    34.0         46.0       34.0          25.0   29.26           33.07          1.16        2.44
17  WT19     conflict   off                  150720_WT19Conf1_2    19.98    92.0          NaN       82.0           NaN   25.82             NaN          3.56        2.15
18  WT19  pretraining   off                     150720_WT19Hab1    19.98     NaN          NaN        NaN           NaN   55.30             NaN           NaN        4.61
19  WT20    training1    on   150929_PIC_WT20_4Ini1_DG_Room.dat    20.00    15.0         18.0       17.0           9.0   27.91           32.95          0.54        2.33
20  WT20    training1   off          150929_PIC_WT20_4Ini1_2_DG    19.98     8.0          NaN        8.0           NaN   36.56             NaN          0.22        3.05
21  WT20    training2    on   150929_PIC_WT20_5Ini2_DG_Room.dat    10.00     2.0          2.0        2.0           2.0   13.72           15.32          0.15        2.29
22  WT20    training2   off          150929_PIC_WT20_5Ini2_2_DG    20.02     8.0          NaN        8.0           NaN   32.27             NaN          0.25        2.69
23  WT20     conflict    on  150929_PIC_WT20_6Conf1_DG_Room.dat    20.00     9.0         13.0       13.0           7.0   22.65           26.00          0.40        1.89
24  WT20     conflict   off         150929_PIC_WT20_6Conf1_2_DG    19.99    56.0          NaN       48.0           NaN   30.53             NaN          1.83        2.55
25  WT20  pretraining   off            150929_PIC_WT20_2Hab2_DG    19.99     NaN          NaN        NaN           NaN   87.56             NaN           NaN        7.30
26  WT20  pretraining   off            150929_PIC_WT20_3Hab3_DG    19.99     NaN          NaN        NaN           NaN   82.76             NaN           NaN        6.90
27  WT26    training1    on            151215_WT26Ini1_Room.dat    20.00    26.0         30.0       20.0          21.0   36.36           40.79          0.72        3.03
28  WT26    training1   off                   151215_WT26Ini1_2    19.98    45.0          NaN       39.0           NaN   51.22             NaN          0.88        4.27
29  WT26    training2    on            151215_WT26Ini2_Room.dat    10.00     7.0          7.0        4.0           7.0   16.86           19.10          0.42        2.81
30  WT26    training2   off                   151215_WT26Ini2_2    20.02    22.0          NaN       20.0           NaN   45.74             NaN          0.48        3.81
31  WT26     conflict    on           151215_WT26Conf1_Room.dat    20.00    37.0         36.0       34.0          25.0   44.03           49.24          0.84        3.67
32  WT26     conflict   off                  151215_WT26Conf1_2    20.02   107.0          NaN      100.0           NaN   36.01             NaN          2.97        3.00
33  WT26  pretraining   off                     151215_WT26Hab1    19.99     NaN          NaN        NaN           NaN   77.83             NaN           NaN        6.49
34  WT26  pretraining   off                     151215_WT26Hab2    19.99     NaN          NaN        NaN           NaN   62.58             NaN           NaN        5.22
35  WT27    training1    on            151215_WT27Ini1_Room.dat    20.00     9.0          8.0        8.0           8.0   28.23           32.15          0.32        2.35
36  WT27    training1   off                   151215_WT27Ini1_2    19.99    44.0          NaN       38.0           NaN   51.39             NaN          0.86        4.29
37  WT27    training2    on            151215_WT27Ini2_Room.dat    10.00     1.0          2.0        1.0           1.0   13.16           15.02          0.08        2.19
38  WT27    training2   off                   151215_WT27Ini2_2    19.99    42.0          NaN       39.0           NaN   45.43             NaN          0.92        3.79
39  WT27     conflict    on           151215_WT27Conf1_Room.dat    20.00    23.0         23.0       18.0          21.0   29.67           32.49          0.78        2.47
40  WT27     conflict   off                  151215_WT27Conf1_2    19.99    42.0          NaN       36.0           NaN   45.40             NaN          0.93        3.79
41  WT27  pretraining   off                     151215_WT27Hab1    19.98     NaN          NaN        NaN           NaN   80.97             NaN           NaN        6.75
42  WT27  pretraining   off                     151215_WT27Hab2    19.99     NaN          NaN        NaN           NaN   69.13             NaN           NaN        5.76
path from positions (1-s steps) vs Tracker's ElapsedPath, shock-on files: ratio median 0.883 range 0.811 0.913
geometric vs Tracker entrances, shock-on files: ratio median 1.18 | sum of absolute differences 43
geometric with 100 ms outside vs Tracker, shock-on files: ratio median 1.0 | sum of absolute differences 30
   min_out  1 samples: ratio to Tracker median 1.18, sum |diff| 43
   min_out  3 samples: ratio to Tracker median 1.00, sum |diff| 30
   min_out  5 samples: ratio to Tracker median 1.00, sum |diff| 34
   min_out 10 samples: ratio to Tracker median 0.92, sum |diff| 39
   min_out 30 samples: ratio to Tracker median 0.82, sum |diff| 51

fig3b-avoidance-learning¶

The recorded mice learned to avoid the shock zone in training 1 and kept the avoidance in training 2, while errors rose in the conflict trial and then fell.

In [27]:
Y = on.pivot_table(index="mouse", columns="kind", values="errors")[["training1", "training2", "conflict"]]
print(Y.to_string()); print("means:", Y.mean().round(2).to_dict(), "SEM:", Y.sem().round(2).to_dict())
F, df, p = H.rm_multivariate(Y.values)
print(f"reading (a) multivariate repeated-measures F({df[0]}, {df[1]}) = {F:.2f}, p = {p:.4f}")
F2, df2, p2 = H.rm_univariate(Y.values)
print(f"reading (b) univariate repeated-measures F({df2[0]}, {df2[1]}) = {F2:.2f}, p = {p2:.4f}")
# Fisher's LSD on the repeated measures: paired t tests
for a, b in [("training2", "training1"), ("training2", "conflict"), ("training1", "conflict")]:
    t = stats.ttest_rel(Y[a], Y[b]); print(f"  {a} vs {b}: mean diff {np.mean(Y[a] - Y[b]):.2f}, paired t = {t.statistic:.2f}, p = {t.pvalue:.4f}")
# WT15 has no 10-min training 2 shock-on file: the file deposited among the shock-on files is
# 20 min long and is byte-identical to its training 2 "recording" (cell above). Variants: count
# its errors in the first 10 min only, or leave WT15 out (5 mice, df 2 and 3).
print("WT15 training 2 shock-on file:", on[(on.mouse == "WT15") & (on.kind == "training2")][["file", "minutes", "errors", "errors_10min"]].to_dict("records"))
Y10 = Y.copy(); Y10.loc["WT15", "training2"] = on[(on.mouse == "WT15") & (on.kind == "training2")].errors_10min.iloc[0]
for lab, Yv in [("WT15 training 2, first 10 min", Y10), ("WT15 left out", Y.drop(index="WT15"))]:
    Fv, dfv, pv = H.rm_multivariate(Yv.values); Fu, dfu, pu = H.rm_univariate(Yv.values)
    print(f"variant, {lab}: means {Yv.mean().round(2).to_dict()}; multivariate F({dfv[0]}, {dfv[1]}) = {Fv:.2f}, p = {pv:.4f}; univariate F({dfu[0]}, {dfu[1]}) = {Fu:.2f}, p = {pu:.4f}")
    for a, b in [("training2", "training1"), ("training2", "conflict")]:
        t = stats.ttest_rel(Yv[a], Yv[b]); print(f"     {a} vs {b}: paired t = {t.statistic:.2f}, p = {t.pvalue:.4f}")
Ym = on.pivot_table(index="mouse", columns="kind", values="errors_per_m")[["training1", "training2", "conflict"]]
print("errors per meter (variant):", Ym.mean().round(3).to_dict(), "multivariate F = %.2f, p = %.4f" % (H.rm_multivariate(Ym.values)[0], H.rm_multivariate(Ym.values)[2]))
# within-trial learning curve of the conflict trial: errors by 5-min block
for mo in SESS:
    f = shock_on_file(mo, "conflict")
    if f:
        m, d = H.read_dat(f); st = d.State.values; t = d["1msTimeStamp"].values / 6e4
        e = np.where((st[1:] == 1) & (st[:-1] == 0))[0]
        print(mo, "conflict errors per 5-min block:", np.histogram(t[e + 1], [0, 5, 10, 15, 20])[0].tolist())
kind   training1  training2  conflict
mouse                                
WT15        17.0        1.0      10.0
WT16         9.0        6.0       1.0
WT19         8.0        9.0      34.0
WT20        15.0        2.0       9.0
WT26        26.0        7.0      37.0
WT27         9.0        1.0      23.0
means: {'training1': 14.0, 'training2': 4.33, 'conflict': 19.0} SEM: {'training1': 2.83, 'training2': 1.41, 'conflict': 5.97}
reading (a) multivariate repeated-measures F(2, 4) = 5.70, p = 0.0674
reading (b) univariate repeated-measures F(2, 10) = 4.62, p = 0.0379
  training2 vs training1: mean diff -9.67, paired t = -3.06, p = 0.0281
  training2 vs conflict: mean diff -14.67, paired t = -2.72, p = 0.0419
  training1 vs conflict: mean diff -5.00, paired t = -0.87, p = 0.4243
WT15 training 2 shock-on file: [{'file': 'WT15Ini2.1_Room.dat', 'minutes': 20.00055, 'errors': 1.0, 'errors_10min': 0.0}]
variant, WT15 training 2, first 10 min: means {'training1': 14.0, 'training2': 4.17, 'conflict': 19.0}; multivariate F(2, 4) = 5.76, p = 0.0665; univariate F(2, 10) = 4.73, p = 0.0358
     training2 vs training1: paired t = -3.05, p = 0.0286
     training2 vs conflict: paired t = -2.77, p = 0.0396
variant, WT15 left out: means {'training1': 13.4, 'training2': 5.0, 'conflict': 20.8}; multivariate F(2, 3) = 3.37, p = 0.1710; univariate F(2, 8) = 3.94, p = 0.0645
     training2 vs training1: paired t = -2.37, p = 0.0768
     training2 vs conflict: paired t = -2.45, p = 0.0708
errors per meter (variant): {'training1': 0.456, 'training2': 0.326, 'conflict': 0.617} multivariate F = 1.06, p = 0.4271
WT15 conflict errors per 5-min block: [8, 2, 0, 0]
WT16 conflict errors per 5-min block: [0, 0, 1, 0]
WT19 conflict errors per 5-min block: [10, 15, 7, 2]
WT20 conflict errors per 5-min block: [4, 3, 2, 0]
WT26 conflict errors per 5-min block: [4, 21, 6, 6]
WT27 conflict errors per 5-min block: [15, 6, 0, 2]

Result: Not reproduced. Errors fall from training 1 (mean 14.0) to training 2 (4.33) and rise in conflict (19.0), and paired comparisons put training 2 below training 1 (p = 0.028) and conflict (p = 0.042), but the criterion's test fails: the multivariate repeated-measures test whose df match the paper's (2, 4) gives F = 5.70, p = 0.067, against F = 18.2, p = 0.01. It also fails when WT15's 20-min training 2 file is counted over its first 10 min (p = 0.067) and when WT15 is left out (F(2, 3) = 3.37, p = 0.17). The univariate test, whose df do not fit six mice, gives F(2, 10) = 4.62, p = 0.038.

fig3b-shock-off-avoidance¶

The mice expressed the conditioned avoidance during the shock-off recording sessions, and performance in shock-on and shock-off sessions did not differ.

In [28]:
B = BEH[BEH.kind.isin(["training1", "training2", "conflict"])].copy()
print(B.pivot_table(index="mouse", columns=["kind", "shock"], values="errors").to_string())
for col in ["errors", "errors_per_m"]:
    tab, mm = H.mixed_terms(B[["mouse", "kind", "shock", col]].rename(columns={col: "y"}), "y ~ C(shock, Sum) * C(kind, Sum)", "mouse",
                            {"shock status": "shock", "condition": "kind", "interaction": "shock&kind"})
    print(col, "mixed model, mouse random, n =", len(B.dropna(subset=[col]))); print(tab.round(4).to_string())
    t, _ = H.anova2(B.dropna(subset=[col]), col, "shock", "kind"); print("ordinary two-way ANOVA:"); print(t.round(4).to_string())
    print(B.groupby(["kind", "shock"])[col].agg(["mean", "sem", "size"]).round(3).to_string())
# Variants. (1) Shock-off recordings whose own Tracker files log shocks are left out (this also
# drops the WT15 training 2 recording that is the same file as its shock-on session). (2) The
# shock-off errors counted with the 100-ms rule calibrated against the Tracker (cell above),
# shock-on errors staying the Tracker's own. (3) Both.
kind_of = lambda f: next((k for key, k in H.AVOID_KIND if key in f), None)
LOGGED = {(r.mouse, kind_of(r.file)) for r in DAT[(DAT.folder == "recordingDAT") & (DAT.shocks > 0)].itertuples()}
print("shock-off recordings whose Tracker files log shocks:", sorted(LOGGED))
logged = (B.shock == "off") & pd.Series([(m_, k_) in LOGGED for m_, k_ in zip(B.mouse, B.kind)], index=B.index)
Bdb = B.copy(); Bdb.loc[Bdb.shock == "off", "errors"] = Bdb.loc[Bdb.shock == "off", "errors_db"]
Bdb["errors_per_m"] = Bdb.errors / Bdb.path_m
for lab, Bv in [("(1) without shock-logging recordings", B[~logged]), ("(2) shock-off errors with the 100-ms rule", Bdb),
                ("(3) both", Bdb[~logged])]:
    print(f"variant {lab}: n = {len(Bv)}; means", Bv.groupby(["kind", "shock"]).errors.mean().round(2).to_dict())
    for col in ["errors", "errors_per_m"]:
        tab, _ = H.mixed_terms(Bv[["mouse", "kind", "shock", col]].rename(columns={col: "y"}), "y ~ C(shock, Sum) * C(kind, Sum)", "mouse",
                               {"shock status": "shock", "condition": "kind", "interaction": "shock&kind"})
        print(f"   {col}:", [(r.term, round(r.F, 2), round(r.p, 4)) for r in tab.itertuples()])
print("Tracker files of recorded sessions that log shocks (WT15, WT16):")
print(DAT[(DAT.folder == "recordingDAT") & (DAT.shocks > 0)][["file", "minutes", "sector", "shocks", "max_current"]].to_string())
kind  conflict       training1       training2     
shock      off    on       off    on       off   on
mouse                                              
WT15       NaN  10.0      32.0  17.0       1.0  1.0
WT16      15.0   1.0       NaN   9.0      20.0  6.0
WT19      92.0  34.0      29.0   8.0      36.0  9.0
WT20      56.0   9.0       8.0  15.0       8.0  2.0
WT26     107.0  37.0      45.0  26.0      22.0  7.0
WT27      42.0  23.0      44.0   9.0      42.0  1.0
errors mixed model, mouse random, n = 34
           term        F  df1   df2       p
0  shock status  22.3408    1  28.0  0.0001
1     condition   9.2150    2  28.0  0.0008
2   interaction   2.6319    2  28.0  0.0897
ordinary two-way ANOVA:
                 sum_sq    df        F  PR(>F)
shock         5728.1510   1.0  17.6810  0.0002
kind          4493.7124   2.0   6.9353  0.0036
shock x kind  1251.7769   2.0   1.9319  0.1637
Residual      9071.2333  28.0      NaN     NaN
                   mean     sem  size
kind      shock                      
conflict  off    62.400  16.687     5
          on     19.000   5.972     6
training1 off    31.600   6.698     5
          on     14.000   2.828     6
training2 off    21.500   6.417     6
          on      4.333   1.406     6
errors_per_m mixed model, mouse random, n = 34
           term       F  df1   df2       p
0  shock status  9.7929    1  28.0  0.0041
1     condition  8.7736    2  28.0  0.0011
2   interaction  4.3036    2  28.0  0.0235
ordinary two-way ANOVA:
              sum_sq    df       F  PR(>F)
shock         2.8436   1.0  8.7681  0.0062
kind          4.8302   2.0  7.4467  0.0026
shock x kind  2.3641   2.0  3.6447  0.0392
Residual      9.0808  28.0     NaN     NaN
                  mean    sem  size
kind      shock                    
conflict  off    1.947  0.591     5
          on     0.617  0.158     6
training1 off    0.716  0.127     5
          on     0.456  0.064     6
training2 off    0.478  0.130     6
          on     0.326  0.115     6
shock-off recordings whose Tracker files log shocks: [('WT15', 'training1'), ('WT15', 'training2'), ('WT16', 'conflict'), ('WT16', 'training2')]
variant (1) without shock-logging recordings: n = 30; means {('conflict', 'off'): 74.25, ('conflict', 'on'): 19.0, ('training1', 'off'): 31.5, ('training1', 'on'): 14.0, ('training2', 'off'): 27.0, ('training2', 'on'): 4.33}
   errors: [('shock status', 33.61, 0.0), ('condition', 14.07, 0.0001), ('interaction', 5.6, 0.0101)]
   errors_per_m: [('shock status', 16.43, 0.0005), ('condition', 13.87, 0.0001), ('interaction', 7.97, 0.0022)]
variant (2) shock-off errors with the 100-ms rule: n = 34; means {('conflict', 'off'): 56.0, ('conflict', 'on'): 19.0, ('training1', 'off'): 27.8, ('training1', 'on'): 14.0, ('training2', 'off'): 20.33, ('training2', 'on'): 4.33}
   errors: [('shock status', 18.7, 0.0002), ('condition', 8.77, 0.0011), ('interaction', 2.23, 0.1264)]
   errors_per_m: [('shock status', 7.75, 0.0095), ('condition', 8.52, 0.0013), ('interaction', 3.85, 0.0334)]
variant (3) both: n = 30; means {('conflict', 'off'): 66.5, ('conflict', 'on'): 19.0, ('training1', 'off'): 27.5, ('training1', 'on'): 14.0, ('training2', 'off'): 25.75, ('training2', 'on'): 4.33}
   errors: [('shock status', 26.89, 0.0), ('condition', 12.47, 0.0002), ('interaction', 4.61, 0.0202)]
   errors_per_m: [('shock status', 12.93, 0.0015), ('condition', 12.84, 0.0002), ('interaction', 6.93, 0.0042)]
Tracker files of recorded sessions that log shocks (WT15, WT16):
                    file  minutes                   sector  shocks  max_current
18   WT15Ini1_2_Room.dat     20.0  135 60 25.5000 127.5000      33          2.0
22   WT15Ini2_1_Room.dat     20.0  135 60 25.5000 127.5000       1          2.0
9   WT16Conf1_2_Room.dat     20.0  300 60 25.5000 127.5000       5          2.0
16   WT16Ini2_1_Room.dat     20.0  135 60 25.5000 127.5000      20          2.0

Result: Not reproduced. Errors in the shock-off recordings (means 31.6, 21.5 and 62.4) are higher than in the shock-on sessions (14.0, 4.33 and 19.0); with mouse as random term the shock status effect is F = 22.3, p = 0.0001 for errors and F = 9.79, p = 0.004 for errors per meter, which also has an interaction (p = 0.024). The effect stays without the four shock-off recordings whose Tracker files log shocks (errors p < 0.0001, errors per meter p = 0.0005), with shock-off errors counted by the 100-ms rule that matches the Tracker's count on shock-on files (median ratio 1.00; p = 0.0002 and 0.0095), and with both (p < 0.0001 and p = 0.0015).

speed-no-difference¶

Running speed did not differ between the training and conflict conditions.

In [29]:
rows = []
for lv, kinds in [("a: training1, training2, conflict", ["training1", "training2", "conflict"]), ("b: pretraining, training, conflict", ["pretraining", "training", "conflict"])]:
    for sh in ["on", "off"]:
        S = BEH[BEH.shock == sh].copy() if lv[0] == "a" or sh == "off" else BEH[(BEH.shock == "on") | (BEH.kind == "pretraining")].copy()
        S["level"] = S.kind.replace({"training1": "training", "training2": "training"}) if lv[0] == "b" else S.kind
        S = S.groupby(["mouse", "level"]).speed_cm_s.mean().reset_index()
        g = [S[S.level == k].speed_cm_s for k in (["training1", "training2", "conflict"] if lv[0] == "a" else ["pretraining", "training", "conflict"])]
        if min(len(x) for x in g) < 2:
            continue
        a = H.anova1(g)
        rows.append(dict(levels=lv, sessions="shock-" + sh, n=a["n"], means=np.round(a["means"], 2).tolist(), F=a["F"], df=a["df"], p=a["p"], p_welch=a["welch_p"], p_kw=a["kw_p"]))
SP = pd.DataFrame(rows); print(SP.round(4).to_string())
print("speed range (cm/s):", BEH.speed_cm_s.min().round(2), BEH.speed_cm_s.max().round(2))
                               levels   sessions          n               means        F       df       p  p_welch    p_kw
0   a: training1, training2, conflict   shock-on  [6, 6, 6]  [2.49, 2.34, 2.45]   0.1141  (2, 15)  0.8929   0.8731  0.6918
1   a: training1, training2, conflict  shock-off  [5, 6, 5]  [3.59, 3.48, 2.86]   1.9425  (2, 13)  0.1828   0.2173  0.1620
2  b: pretraining, training, conflict   shock-on  [6, 6, 6]  [4.96, 2.41, 2.45]  10.2195  (2, 15)  0.0016   0.0263  0.0109
3  b: pretraining, training, conflict  shock-off  [6, 6, 5]  [4.96, 3.53, 2.86]   5.1226  (2, 14)  0.0214   0.0545  0.0597
speed range (cm/s): 1.55 7.3

Result: Reproduced, on the reading whose design matches the paper's. Over training 1, training 2 and conflict in the shock-off recordings (5, 6 and 5 mice) the one-way ANOVA gives F(2, 13) = 1.94, p = 0.18, the paper's df and values. The shock-on sessions give p = 0.89. The readings with pretraining as a level differ (p = 0.0016 and 0.021), as mice run faster in pretraining (4.96 cm/s against 2.4 to 3.5).

Cell pair correlations (Figures 5, 6 and S2)¶

Spike counts in 133-ms bins are counts over 4 position samples (4 x 33.3 ms), so that every bin has a position; 20-ms and 250-ms bins are cut from the spike times. Kendall's tau-b over all bins of a session (M9). A pair's pretraining value is the mean over its pretraining sessions and its training value the mean over training 1 and 2 (claims, figs2a criterion: "pretraining and training sessions each pooled per pair"). Changes are (later - earlier) / SD of tau over six periods of the earlier session, averaged over a manipulation's session pairs (M9, M11).

In [30]:
STEP = 4  # samples per 133-ms bin
BINS = {}
for s, v in AV.items():
    p = v["pos"]; n = len(p["rx"]) // STEP
    mid = np.arange(n) * STEP + STEP // 2
    rx, ry = p["rx"][mid], p["ry"][mid]
    valid = H.tracked(rx, ry)
    mo = v["meta"]["mouse"]
    z = {}
    for zn in ["training", "conflict"]:
        sec = ZONES[mo][zn]
        if sec is None:
            continue
        dcm = H.distance_to_sector(rx, ry, sec) / H.PX_PER_CM
        z[zn] = dict(dist=dcm, inside=H.in_sector(rx, ry, sec))
    BINS[s] = dict(n=n, valid=valid, rx=rx, ry=ry, zones=z,
                   counts={u: H.bin_counts(d["spike_sample"], len(p["rx"]), STEP) for u, d in v["units"].items()})

def counts_time(s, u, width_ms):
    p = AV[s]["pos"]; d = AV[s]["units"][u]
    t_end = p["t0"] + int(len(p["rx"]) / p["fs"] * 1e4)
    return H.bin_counts_time(d["spike_times"], p["t0"], t_end, int(width_ms * 10))

def pairs_of(mo, kind):
    pcs = sorted(u for u in cells_av[(cells_av.mouse == mo) & (cells_av.cls == "pc")].itertuples(index=False))
    ins = sorted(u for u in cells_av[(cells_av.mouse == mo) & (cells_av.cls == "int")].itertuples(index=False))
    pcs = [(c.mouse, c.tetrode, c.cluster) for c in pcs]; ins = [(c.mouse, c.tetrode, c.cluster) for c in ins]
    if kind == "pc-int":
        return [(a, b) for a in pcs for b in ins]
    return [(pcs[i], pcs[j]) for i in range(len(pcs)) for j in range(i + 1, len(pcs))]

def session_counts(s, u, width):
    return BINS[s]["counts"][u] if width == 133 else counts_time(s, u, width)

TAU = {}   # (width, session, pair) -> (tau, sd6)
def tau_of(width, s, pr):
    key = (width, s, pr)
    if key not in TAU:
        a, b = session_counts(s, pr[0], width), session_counts(s, pr[1], width)
        TAU[key] = (H.kendall(a, b), H.tau_sd_six(a, b))
    return TAU[key]

t0 = time.time()
def pair_tables(kind, width, reading="a"):
    """Per pair: tau per condition, and normalized change per manipulation."""
    cond_rows, ch_rows = [], []
    for mo in SESS:
        prs = pairs_of(mo, kind); d = SESS[mo]
        for pr in prs:
            for cond, ss in [("pretraining", d.get("pretraining", [])), ("training", d.get("training1", []) + d.get("training2", [])), ("conflict", d.get("conflict") or [])]:
                vals = [tau_of(width, s, pr)[0] for s in ss]
                if vals:
                    cond_rows.append(dict(mouse=mo, pair=pr, cond=cond, tau=np.nanmean(vals)))
            for man, sp in av_pairs(reading)[mo].items():
                ch = []
                for s1, s2 in sp:
                    t1, sd = tau_of(width, s1, pr); t2 = tau_of(width, s2, pr)[0]
                    ch.append((t2 - t1) / sd if sd and sd > 0 else np.nan)
                if ch:
                    ch_rows.append(dict(mouse=mo, pair=pr, manip=man, change=np.nanmean(ch)))
    return pd.DataFrame(cond_rows), pd.DataFrame(ch_rows)

PT = {}
for kind in ["pc-int", "pc-pc"]:
    for w in [133, 20, 250]:
        if kind == "pc-pc" and w != 133:
            continue
        for r in "ab":
            PT[(kind, w, r)] = pair_tables(kind, w, r)
print(f"pair tables in {time.time() - t0:.0f} s")
for k, (c, ch) in PT.items():
    print(k, "tau values per condition", c.groupby("cond").size().to_dict(), "changes per manipulation", ch.groupby("manip").size().to_dict(),
          "NaN taus", int(c.tau.isna().sum()), "NaN changes", int(ch.change.isna().sum()))
pair tables in 15 s
('pc-int', 133, 'a') tau values per condition {'conflict': 134, 'pretraining': 152, 'training': 152} changes per manipulation {'addition': 152, 'relocation': 134, 'replication': 142} NaN taus 0 NaN changes 0
('pc-int', 133, 'b') tau values per condition {'conflict': 134, 'pretraining': 152, 'training': 152} changes per manipulation {'addition': 152, 'relocation': 134, 'replication': 142} NaN taus 0 NaN changes 0
('pc-int', 20, 'a') tau values per condition {'conflict': 134, 'pretraining': 152, 'training': 152} changes per manipulation {'addition': 152, 'relocation': 134, 'replication': 142} NaN taus 0 NaN changes 0
('pc-int', 20, 'b') tau values per condition {'conflict': 134, 'pretraining': 152, 'training': 152} changes per manipulation {'addition': 152, 'relocation': 134, 'replication': 142} NaN taus 0 NaN changes 0
('pc-int', 250, 'a') tau values per condition {'conflict': 134, 'pretraining': 152, 'training': 152} changes per manipulation {'addition': 152, 'relocation': 134, 'replication': 142} NaN taus 0 NaN changes 0
('pc-int', 250, 'b') tau values per condition {'conflict': 134, 'pretraining': 152, 'training': 152} changes per manipulation {'addition': 152, 'relocation': 134, 'replication': 142} NaN taus 0 NaN changes 0
('pc-pc', 133, 'a') tau values per condition {'conflict': 118, 'pretraining': 133, 'training': 133} changes per manipulation {'addition': 133, 'relocation': 118, 'replication': 123} NaN taus 0 NaN changes 0
('pc-pc', 133, 'b') tau values per condition {'conflict': 118, 'pretraining': 133, 'training': 133} changes per manipulation {'addition': 133, 'relocation': 118, 'replication': 123} NaN taus 0 NaN changes 0

figs2a-pc-pairs-no-change¶

Place cell pair spike train correlations at 133 ms did not differ across the three trial types, and their changes did not differ across manipulations.

In [31]:
condn = ["pretraining", "training", "conflict"]
for r in "ab":
    c, ch = PT[("pc-pc", 133, r)]
    g = [c[c.cond == k].tau.dropna() for k in condn]; h = [ch[ch.manip == k].change.dropna() for k in names]
    k1, k2 = stats.kruskal(*g), stats.kruskal(*h)
    print(f"M11 {r}: tau n={[len(x) for x in g]} medians {[round(x.median(), 4) for x in g]} H = {k1.statistic:.2f}, p = {k1.pvalue:.3f}; "
          f"change n={[len(x) for x in h]} medians {[round(x.median(), 3) for x in h]} H = {k2.statistic:.2f}, p = {k2.pvalue:.3f}")
M11 a: tau n=[133, 133, 118] medians [np.float64(0.0021), np.float64(0.0052), np.float64(0.0042)] H = 0.57, p = 0.751; change n=[123, 133, 118] medians [np.float64(0.031), np.float64(0.032), np.float64(0.085)] H = 0.80, p = 0.669
M11 b: tau n=[133, 133, 118] medians [np.float64(0.0021), np.float64(0.0052), np.float64(0.0042)] H = 0.57, p = 0.751; change n=[123, 133, 118] medians [np.float64(0.031), np.float64(0.14), np.float64(0.1)] H = 1.69, p = 0.429

Result: Reproduced. Place cell pair correlations do not differ across trial types (H = 0.57, p = 0.75; 133, 133 and 118 pairs, the paper's 384 values), and their changes do not differ across manipulations (p = 0.43 under reading (b), p = 0.67 under reading (a)).

fig5d1-pc-int-tau-no-difference¶

The distributions of place cell-interneuron correlations did not differ across trial types.

In [32]:
c, ch = PT[("pc-int", 133, "a")]
g = [c[c.cond == k].tau.dropna() for k in condn]
k1 = stats.kruskal(*g)
print(f"tau n={[len(x) for x in g]} medians {[round(x.median(), 4) for x in g]} means {[round(x.mean(), 4) for x in g]}; H = {k1.statistic:.2f}, p = {k1.pvalue:.3f}")
print("by mouse, median tau:"); print(c.groupby(["mouse", "cond"]).tau.median().unstack()[condn].round(4).to_string())
tau n=[152, 152, 134] medians [np.float64(0.0159), np.float64(0.0118), np.float64(0.0159)] means [np.float64(0.0179), np.float64(0.0138), np.float64(0.0168)]; H = 1.40, p = 0.497
by mouse, median tau:
cond   pretraining  training  conflict
mouse                                 
WT15        0.0122    0.0183       NaN
WT16        0.0030    0.0119    0.0002
WT19        0.0153    0.0103    0.0120
WT20        0.0299    0.0222    0.0139
WT26        0.0009    0.0016    0.0135
WT27        0.0239    0.0178    0.0338

Result: Reproduced. Place cell-interneuron correlations do not differ across trial types (H = 1.40, p = 0.50; 152, 152 and 134 pairs, the paper's 438 values).

fig5d2-pc-int-change-relocation¶

Place cell-interneuron pairs became more positively correlated across shock relocation than across replication or shock addition.

In [33]:
for r in "ab":
    c, ch = PT[("pc-int", 133, r)]
    h = [ch[ch.manip == k].change.dropna() for k in names]
    a = H.anova1(h); l = H.lsd(h, names)
    print(f"M11 {r}: n={a['n']} means {np.round(a['means'], 3).tolist()}; one-way ANOVA F{a['df']} = {a['F']:.2f}, p = {a['p']:.5f}; Welch p = {a['welch_p']:.4f}; KW p = {a['kw_p']:.4f}")
    print("   LSD:", [(x, y, round(d, 3), round(p, 4)) for x, y, d, p in l[["a", "b", "diff", "p"]].values])
    print("   by mouse, mean change:", ch.groupby(["mouse", "manip"]).change.mean().unstack()[names].round(2).to_dict("index"))
M11 a: n=[142, 152, 134] means [-0.285, -0.011, 0.161]; one-way ANOVA F(2, 425) = 6.76, p = 0.00129; Welch p = 0.0003; KW p = 0.0000
   LSD: [('replication', 'addition', -0.274, 0.0217), ('replication', 'relocation', -0.446, 0.0003), ('addition', 'relocation', -0.172, 0.1553)]
   by mouse, mean change: {'WT15': {'replication': -0.5, 'addition': 0.31, 'relocation': nan}, 'WT16': {'replication': nan, 'addition': -0.11, 'relocation': 0.24}, 'WT19': {'replication': -0.39, 'addition': 0.18, 'relocation': -0.23}, 'WT20': {'replication': -0.31, 'addition': -0.21, 'relocation': -0.08}, 'WT26': {'replication': -0.29, 'addition': -0.02, 'relocation': 0.5}, 'WT27': {'replication': -0.04, 'addition': -0.06, 'relocation': 0.24}}
M11 b: n=[142, 152, 134] means [-0.285, -0.185, 0.15]; one-way ANOVA F(2, 425) = 7.63, p = 0.00056; Welch p = 0.0007; KW p = 0.0000
   LSD: [('replication', 'addition', -0.099, 0.3779), ('replication', 'relocation', -0.434, 0.0002), ('addition', 'relocation', -0.335, 0.0036)]
   by mouse, mean change: {'WT15': {'replication': -0.5, 'addition': 0.08, 'relocation': nan}, 'WT16': {'replication': nan, 'addition': -0.11, 'relocation': 0.24}, 'WT19': {'replication': -0.39, 'addition': -0.02, 'relocation': -0.31}, 'WT20': {'replication': -0.31, 'addition': -0.46, 'relocation': -0.12}, 'WT26': {'replication': -0.29, 'addition': -0.24, 'relocation': 0.42}, 'WT27': {'replication': -0.04, 'addition': -0.08, 'relocation': 0.42}}

Result: Reproduced, resting on the M11 assumption. Normalized changes differ across manipulations (reading (b): means -0.29, -0.19, 0.15; F(2, 425) = 7.63, p = 0.00056), and Fisher's LSD puts relocation above replication (p = 0.0002) and addition (p = 0.0036). Under reading (a) relocation is above replication (p = 0.0003) but not addition (p = 0.16).

pc-int-fraction-increased¶

Most place cells increased co-firing with at least one interneuron, 75% for replication, 83% for shock addition and 92% for shock relocation, the last significantly above replication.

In [34]:
for r in "ab":
    c, ch = PT[("pc-int", 133, r)]
    ch = ch.assign(pc=ch.pair.map(lambda q: q[0]))
    for thr_lab, thr in [("(a) > 0", 0.0), ("(b) > 1 SD", 1.0)]:
        frac = ch.groupby(["manip", "pc"]).change.max().gt(thr).groupby("manip").agg(["sum", "size"])
        pct = (100 * frac["sum"] / frac["size"]).round(1).to_dict()
        z1 = H.prop_ztest(frac.loc["addition", "sum"], frac.loc["addition", "size"], frac.loc["replication", "sum"], frac.loc["replication", "size"])
        z2 = H.prop_ztest(frac.loc["relocation", "sum"], frac.loc["relocation", "size"], frac.loc["replication", "sum"], frac.loc["replication", "size"])
        print(f"M11 {r}, threshold {thr_lab}: % place cells {pct}, n {frac['size'].to_dict()}; addition vs replication z = {z1[0]:.2f}, p = {z1[1]:.3f}; relocation vs replication z = {z2[0]:.2f}, p = {z2[1]:.3f}")
print("expected 75 +/- 7.5, 83 +/- 8.3, 92 +/- 9.2 %; relocation test p < 0.05")
M11 a, threshold (a) > 0: % place cells {'addition': 92.9, 'relocation': 91.7, 'replication': 78.4}, n {'addition': 42, 'relocation': 36, 'replication': 37}; addition vs replication z = 1.85, p = 0.064; relocation vs replication z = 1.59, p = 0.113
M11 a, threshold (b) > 1 SD: % place cells {'addition': 28.6, 'relocation': 30.6, 'replication': 5.4}, n {'addition': 42, 'relocation': 36, 'replication': 37}; addition vs replication z = 2.69, p = 0.007; relocation vs replication z = 2.81, p = 0.005
M11 b, threshold (a) > 0: % place cells {'addition': 76.2, 'relocation': 91.7, 'replication': 78.4}, n {'addition': 42, 'relocation': 36, 'replication': 37}; addition vs replication z = -0.23, p = 0.817; relocation vs replication z = 1.59, p = 0.113
M11 b, threshold (b) > 1 SD: % place cells {'addition': 28.6, 'relocation': 44.4, 'replication': 5.4}, n {'addition': 42, 'relocation': 36, 'replication': 37}; addition vs replication z = 2.69, p = 0.007; relocation vs replication z = 3.87, p = 0.000
expected 75 +/- 7.5, 83 +/- 8.3, 92 +/- 9.2 %; relocation test p < 0.05

Result: Partially reproduced. With a change above zero (reading (a)) and M11 reading (b), 78.4, 76.2 and 91.7% of place cells increased co-firing with at least one interneuron, all within tolerance of 75, 83 and 92%, but relocation against replication gives z = 1.59, p = 0.11, against p = 0.03. With the 1-SD threshold the test is significant (p < 0.001) but the percentages (5 to 44%) are far from the paper's.

figs2bc-other-timescales¶

The place cell-interneuron results held at 20 and 250 ms; correlations did not differ across trial types while their changes were larger for shock relocation.

In [35]:
for w in [20, 250]:
    for r in "ab":
        c, ch = PT[("pc-int", w, r)]
        g = [c[c.cond == k].tau.dropna() for k in condn]; h = [ch[ch.manip == k].change.dropna() for k in names]
        k1, k2 = stats.kruskal(*g), stats.kruskal(*h)
        print(f"{w} ms, M11 {r}: tau H = {k1.statistic:.2f}, p = {k1.pvalue:.3f}; change n={[len(x) for x in h]} medians {[round(x.median(), 3) for x in h]} means {[round(x.mean(), 3) for x in h]} H = {k2.statistic:.2f}, p = {k2.pvalue:.4f}")
20 ms, M11 a: tau H = 0.52, p = 0.771; change n=[142, 152, 134] medians [np.float64(-0.05), np.float64(-0.128), np.float64(0.105)] means [np.float64(-0.04), np.float64(-0.126), np.float64(0.203)] H = 5.70, p = 0.0579
20 ms, M11 b: tau H = 0.52, p = 0.771; change n=[142, 152, 134] medians [np.float64(-0.05), np.float64(-0.184), np.float64(0.155)] means [np.float64(-0.04), np.float64(-0.125), np.float64(0.208)] H = 6.94, p = 0.0312
250 ms, M11 a: tau H = 1.47, p = 0.481; change n=[142, 152, 134] medians [np.float64(-0.255), np.float64(-0.014), np.float64(0.227)] means [np.float64(-0.339), np.float64(0.019), np.float64(0.197)] H = 25.33, p = 0.0000
250 ms, M11 b: tau H = 1.47, p = 0.481; change n=[142, 152, 134] medians [np.float64(-0.255), np.float64(-0.228), np.float64(0.225)] means [np.float64(-0.339), np.float64(-0.174), np.float64(0.177)] H = 24.46, p = 0.0000

Result: Reproduced, resting on the M11 assumption. Under reading (b), at 20 ms tau does not differ across trial types (p = 0.77) and changes differ with relocation highest (H = 6.94, p = 0.031); at 250 ms tau p = 0.48 and changes H = 24.5, p < 0.0001, relocation highest. Under reading (a) the 20-ms change test gives p = 0.058.

pc-int-pair-classes¶

In pretraining, 53% of place cell-interneuron pairs were significantly positively correlated (81 pairs), 10% negatively (15) and 37% independent (56).

In [36]:
rng = np.random.default_rng(5)
def classify(a, b, how, nshift=200):
    t = H.kendall(a, b)
    if not np.isfinite(t):
        return "independent", t
    if how == "a":
        p = stats.kendalltau(a, b).pvalue
        return ("positive" if t > 0 else "negative") if p < 0.05 else "independent", t
    sh = rng.integers(int(len(a) * 0.1), int(len(a) * 0.9), nshift)
    null = np.array([stats.kendalltau(a, np.roll(b, k)).statistic for k in sh])
    lo, hi = np.percentile(null, [2.5, 97.5])
    return ("positive" if t > hi else "negative" if t < lo else "independent"), t

CLS = {}
for how in "ab":
    for which in ["i", "ii", "iii"]:
        rows = []
        for mo in SESS:
            pre = SESS[mo].get("pretraining", [])
            if which == "ii" and len(pre) < 2:
                continue
            for pr in pairs_of(mo, "pc-int"):
                if which == "i":
                    a, b = BINS[pre[0]]["counts"][pr[0]], BINS[pre[0]]["counts"][pr[1]]
                elif which == "ii":
                    a, b = BINS[pre[1]]["counts"][pr[0]], BINS[pre[1]]["counts"][pr[1]]
                else:
                    a = np.concatenate([BINS[s]["counts"][pr[0]] for s in pre]); b = np.concatenate([BINS[s]["counts"][pr[1]] for s in pre])
                cl, t = classify(a, b, how)
                rows.append(dict(mouse=mo, pair=pr, cls=cl, tau=t))
        CLS[(how, which)] = pd.DataFrame(rows)
        vc = CLS[(how, which)].cls.value_counts()
        print(f"reading ({how})({which}): n pairs {len(rows)}; positive {vc.get('positive', 0)}, negative {vc.get('negative', 0)}, independent {vc.get('independent', 0)}")
print("expected: positive 81 +/- 8.1, negative 15 +/- 1.5, independent 56 +/- 5.6")
reading (a)(i): n pairs 152; positive 69, negative 16, independent 67
reading (a)(ii): n pairs 103; positive 47, negative 12, independent 44
reading (a)(iii): n pairs 152; positive 71, negative 21, independent 60
reading (b)(i): n pairs 152; positive 67, negative 12, independent 73
reading (b)(ii): n pairs 103; positive 46, negative 11, independent 46
reading (b)(iii): n pairs 152; positive 69, negative 17, independent 66
expected: positive 81 +/- 8.1, negative 15 +/- 1.5, independent 56 +/- 5.6

Result: Not reproduced. Readings (i) and (iii) give 152 pairs, the paper's total; readings (ii), which need a second pretraining session, give 103. None gives the three counts within tolerance. Over the 152-pair readings positive pairs number 67 to 71 (expected 81 ± 8.1), negative 12 to 21 (15 ± 1.5) and independent 60 to 73 (56 ± 5.6); the 103-pair readings give 46 and 47 positive, 11 and 12 negative and 44 and 46 independent. Reading (a)(i) matches the negative count (16) and reading (a)(iii) the independent count (60).

fig5d3-independent-pairs-increase, fig5d4-positive-pairs-decrease, negative-pairs-no-change¶

After shock relocation, the initially independent place cell-interneuron pairs became more positively correlated. Initially positively correlated pairs did not change with shock relocation but their correlations decreased across replication and shock addition. Initially negatively correlated pairs did not change across manipulations.

The classes come from pc-int-pair-classes; every class reading is shown, with reading (a)(iii) (Kendall's own test on both pretraining sessions joined) first.

In [37]:
for key in [("a", "iii"), ("a", "i"), ("a", "ii"), ("b", "iii"), ("b", "i"), ("b", "ii")]:
    cl = CLS[key].set_index("pair").cls
    for r in "ab":
        ch = PT[("pc-int", 133, r)][1].copy(); ch["cls"] = ch.pair.map(cl)
        out = []
        for k in ["independent", "positive", "negative"]:
            sub = ch[ch.cls == k]
            h = [sub[sub.manip == m].change.dropna() for m in names]
            if min(len(x) for x in h) < 2:
                out.append(f"{k}: too few"); continue
            kw = stats.kruskal(*h)
            wil = [stats.wilcoxon(x).pvalue if len(x) > 5 else np.nan for x in h]
            out.append(f"{k}: n={[len(x) for x in h]} medians {[round(x.median(), 2) for x in h]} H = {kw.statistic:.2f}, p = {kw.pvalue:.4f}; signed-rank p vs 0 {np.round(wil, 4).tolist()}")
        print(f"classes {key}, M11 {r}:"); print("   " + "\n   ".join(out))
classes ('a', 'iii'), M11 a:
   independent: n=[53, 60, 51] medians [np.float64(-0.2), np.float64(0.25), np.float64(0.23)] H = 9.83, p = 0.0073; signed-rank p vs 0 [0.0115, 0.139, 0.1111]
   positive: n=[70, 71, 65] medians [np.float64(-0.21), np.float64(-0.34), np.float64(0.2)] H = 15.77, p = 0.0004; signed-rank p vs 0 [0.0001, 0.0, 0.2708]
   negative: n=[19, 21, 18] medians [np.float64(-0.32), np.float64(0.39), np.float64(0.54)] H = 8.82, p = 0.0122; signed-rank p vs 0 [0.0728, 0.0421, 0.0665]
classes ('a', 'iii'), M11 b:
   independent: n=[53, 60, 51] medians [np.float64(-0.2), np.float64(0.08), np.float64(0.23)] H = 8.35, p = 0.0154; signed-rank p vs 0 [0.0115, 0.6802, 0.099]
   positive: n=[70, 71, 65] medians [np.float64(-0.21), np.float64(-0.55), np.float64(-0.02)] H = 20.55, p = 0.0000; signed-rank p vs 0 [0.0001, 0.0, 0.6878]
   negative: n=[19, 21, 18] medians [np.float64(-0.32), np.float64(0.67), np.float64(0.57)] H = 10.71, p = 0.0047; signed-rank p vs 0 [0.0728, 0.0384, 0.0066]
classes ('a', 'i'), M11 a:
   independent: n=[60, 67, 58] medians [np.float64(-0.21), np.float64(0.19), np.float64(0.36)] H = 11.98, p = 0.0025; signed-rank p vs 0 [0.008, 0.2826, 0.0271]
   positive: n=[68, 69, 63] medians [np.float64(-0.21), np.float64(-0.3), np.float64(0.08)] H = 11.57, p = 0.0031; signed-rank p vs 0 [0.0001, 0.0002, 0.4893]
   negative: n=[14, 16, 13] medians [np.float64(-0.29), np.float64(0.47), np.float64(0.53)] H = 7.30, p = 0.0259; signed-rank p vs 0 [0.0906, 0.0386, 0.1677]
classes ('a', 'i'), M11 b:
   independent: n=[60, 67, 58] medians [np.float64(-0.21), np.float64(0.06), np.float64(0.38)] H = 12.84, p = 0.0016; signed-rank p vs 0 [0.008, 0.8808, 0.0125]
   positive: n=[68, 69, 63] medians [np.float64(-0.21), np.float64(-0.49), np.float64(-0.07)] H = 16.98, p = 0.0002; signed-rank p vs 0 [0.0001, 0.0, 0.8911]
   negative: n=[14, 16, 13] medians [np.float64(-0.29), np.float64(0.73), np.float64(0.3)] H = 8.66, p = 0.0132; signed-rank p vs 0 [0.0906, 0.0386, 0.1272]
classes ('a', 'ii'), M11 a:
   independent: n=[44, 44, 44] medians [np.float64(-0.09), np.float64(0.17), np.float64(0.22)] H = 6.92, p = 0.0315; signed-rank p vs 0 [0.1833, 0.5514, 0.016]
   positive: n=[47, 47, 47] medians [np.float64(-0.2), np.float64(-0.44), np.float64(0.2)] H = 11.89, p = 0.0026; signed-rank p vs 0 [0.003, 0.0, 0.4156]
   negative: n=[12, 12, 12] medians [np.float64(-0.37), np.float64(0.49), np.float64(0.54)] H = 12.75, p = 0.0017; signed-rank p vs 0 [0.0093, 0.064, 0.0425]
classes ('a', 'ii'), M11 b:
   independent: n=[44, 44, 44] medians [np.float64(-0.09), np.float64(-0.03), np.float64(0.39)] H = 10.97, p = 0.0041; signed-rank p vs 0 [0.1833, 0.8398, 0.0026]
   positive: n=[47, 47, 47] medians [np.float64(-0.2), np.float64(-0.56), np.float64(0.01)] H = 14.02, p = 0.0009; signed-rank p vs 0 [0.003, 0.0, 0.9207]
   negative: n=[12, 12, 12] medians [np.float64(-0.37), np.float64(-0.07), np.float64(0.57)] H = 10.25, p = 0.0060; signed-rank p vs 0 [0.0093, 0.8501, 0.0161]
classes ('b', 'iii'), M11 a:
   independent: n=[59, 66, 57] medians [np.float64(-0.21), np.float64(0.25), np.float64(0.25)] H = 12.31, p = 0.0021; signed-rank p vs 0 [0.0055, 0.0732, 0.0636]
   positive: n=[68, 69, 63] medians [np.float64(-0.21), np.float64(-0.44), np.float64(0.2)] H = 16.87, p = 0.0002; signed-rank p vs 0 [0.0001, 0.0, 0.2886]
   negative: n=[15, 17, 14] medians [np.float64(-0.32), np.float64(0.55), np.float64(0.59)] H = 8.48, p = 0.0144; signed-rank p vs 0 [0.0946, 0.0267, 0.1531]
classes ('b', 'iii'), M11 b:
   independent: n=[59, 66, 57] medians [np.float64(-0.21), np.float64(0.09), np.float64(0.23)] H = 10.67, p = 0.0048; signed-rank p vs 0 [0.0055, 0.4567, 0.0581]
   positive: n=[68, 69, 63] medians [np.float64(-0.21), np.float64(-0.56), np.float64(0.04)] H = 23.13, p = 0.0000; signed-rank p vs 0 [0.0001, 0.0, 0.6318]
   negative: n=[15, 17, 14] medians [np.float64(-0.32), np.float64(0.79), np.float64(0.57)] H = 9.15, p = 0.0103; signed-rank p vs 0 [0.0946, 0.0448, 0.0353]
classes ('b', 'i'), M11 a:
   independent: n=[66, 73, 62] medians [np.float64(-0.22), np.float64(0.22), np.float64(0.38)] H = 16.84, p = 0.0002; signed-rank p vs 0 [0.0016, 0.1043, 0.0102]
   positive: n=[66, 67, 61] medians [np.float64(-0.21), np.float64(-0.3), np.float64(0.08)] H = 10.99, p = 0.0041; signed-rank p vs 0 [0.0001, 0.0001, 0.6126]
   negative: n=[10, 12, 11] medians [np.float64(-0.07), np.float64(0.26), np.float64(0.53)] H = 2.34, p = 0.3105; signed-rank p vs 0 [0.4922, 0.1514, 0.3652]
classes ('b', 'i'), M11 b:
   independent: n=[66, 73, 62] medians [np.float64(-0.22), np.float64(0.07), np.float64(0.38)] H = 16.71, p = 0.0002; signed-rank p vs 0 [0.0016, 0.4868, 0.0059]
   positive: n=[66, 67, 61] medians [np.float64(-0.21), np.float64(-0.55), np.float64(-0.07)] H = 17.34, p = 0.0002; signed-rank p vs 0 [0.0001, 0.0, 0.9857]
   negative: n=[10, 12, 11] medians [np.float64(-0.07), np.float64(0.53), np.float64(0.23)] H = 3.85, p = 0.1460; signed-rank p vs 0 [0.4922, 0.1099, 0.2783]
classes ('b', 'ii'), M11 a:
   independent: n=[46, 46, 46] medians [np.float64(-0.09), np.float64(0.17), np.float64(0.23)] H = 8.80, p = 0.0122; signed-rank p vs 0 [0.1163, 0.4745, 0.0079]
   positive: n=[46, 46, 46] medians [np.float64(-0.2), np.float64(-0.46), np.float64(0.2)] H = 11.29, p = 0.0035; signed-rank p vs 0 [0.0035, 0.0, 0.4545]
   negative: n=[11, 11, 11] medians [np.float64(-0.35), np.float64(0.46), np.float64(0.53)] H = 10.34, p = 0.0057; signed-rank p vs 0 [0.0186, 0.1016, 0.0674]
classes ('b', 'ii'), M11 b:
   independent: n=[46, 46, 46] medians [np.float64(-0.09), np.float64(-0.08), np.float64(0.42)] H = 13.39, p = 0.0012; signed-rank p vs 0 [0.1163, 0.7048, 0.0013]
   positive: n=[46, 46, 46] medians [np.float64(-0.2), np.float64(-0.57), np.float64(-0.0)] H = 13.42, p = 0.0012; signed-rank p vs 0 [0.0035, 0.0, 1.0]
   negative: n=[11, 11, 11] medians [np.float64(-0.35), np.float64(-0.0), np.float64(0.59)] H = 8.13, p = 0.0172; signed-rank p vs 0 [0.0186, 0.7002, 0.0244]

Result: Reproduced, resting on the class reading (a)(iii) and M11 reading (b). The initially independent pairs differ across manipulations (H = 8.35, p = 0.015), with relocation highest (median 0.23 against 0.08 and -0.20). Under M11 reading (a) the test is p = 0.0073 but addition (0.25) is as high as relocation (0.23).

Result: Reproduced, resting on the class reading (a)(iii) and M11 reading (b). Positive pairs differ across manipulations (H = 20.6, p < 0.0001); their changes are below zero for replication (median -0.21, signed-rank p = 0.0001) and addition (-0.55, p < 0.0001) and not different from zero for relocation (-0.02, p = 0.69).

Result: Not reproduced. Under the adopted class reading (a)(iii), the 19 to 21 negative pairs per manipulation differ (H = 10.7, p = 0.0047 under M11 (b); p = 0.012 under (a)), with replication below the shock manipulations. Of the six class readings, only the shuffle classes of reading (b)(i) give no difference (p = 0.15 and 0.31); the (ii) readings, on the 103 pairs of mice with two pretraining sessions, differ (p 0.0017 to 0.017).

Shock zone vicinities and approach events (M7, M8)¶

Zone vicinity for correlations: 133-ms bins whose middle position is within 4.5 cm of a zone but not in it (M7). Both zones are defined in every session, pretraining included. Approach events (M8): local minima of the distance to the nearest edge of a zone, kept when closer than 75% of the session's mean distance; minima inside the zone are errors, the others avoidances; the 4 s before each are pooled. Minima are found on (a) the raw 30-Hz distance and (b) a 1-s moving average.

In [38]:
ZN = ["training", "conflict"]
MAN_ADOPT = "b"  # M11 reading adopted (see the summary); reading (a) is shown beside it
def vic_mask(s, zn):
    z = BINS[s]["zones"].get(zn)
    if z is None:
        return None
    return BINS[s]["valid"] & (z["dist"] > 0) & (z["dist"] <= 4.5) & ~z["inside"]

DIST = {}
def approach_mask(s, zn, kind, smooth):
    p = AV[s]["pos"]; mo = AV[s]["meta"]["mouse"]; sec = ZONES[mo][zn]
    if sec is None:
        return None
    x, y = p["rx"], p["ry"]; v = H.tracked(x, y)
    if (s, zn) not in DIST:
        DIST[(s, zn)] = H.distance_to_sector(x, y, sec) / H.PX_PER_CM
    d = DIST[(s, zn)].copy()
    d[~v] = np.nan
    if smooth:
        k = int(round(p["fs"]))
        d = pd.Series(d).rolling(k, center=True, min_periods=1).mean().values
    ok = np.isfinite(d)
    mean_d = np.nanmean(d)
    i = np.arange(1, len(d) - 1)
    is_min = ok[i] & ok[i - 1] & ok[i + 1] & (d[i] < d[i - 1]) & (d[i] <= d[i + 1]) & (d[i] < 0.75 * mean_d)
    mins = i[is_min]
    mins = mins[(d[mins] == 0) if kind == "error" else (d[mins] > 0)]
    w = int(round(4 * p["fs"]))
    samp = np.zeros(len(d), bool)
    for m in mins:
        samp[max(0, m - w):m] = True
    nb = BINS[s]["n"]
    mb = samp[:nb * STEP].reshape(nb, STEP).any(axis=1)
    return mb, len(mins)

def masked_tau(s, pr, mask):
    if mask is None or mask.sum() < 20:
        return np.nan
    a, b = BINS[s]["counts"][pr[0]][mask], BINS[s]["counts"][pr[1]][mask]
    return H.kendall(a, b)

def masked_sd6(s, pr, mask):
    if mask is None or mask.sum() < 60:
        return np.nan
    a, b = BINS[s]["counts"][pr[0]][mask], BINS[s]["counts"][pr[1]][mask]
    return H.tau_sd_six(a, b)

MASKS = {}
for s in AV:
    for zn in ZN:
        MASKS[("vic", s, zn)] = vic_mask(s, zn)
        for kind in ["avoid", "error"]:
            for sm in [False, True]:
                r = approach_mask(s, zn, kind, sm)
                MASKS[(kind, sm, s, zn)] = None if r is None else r[0]
                MASKS[("n_" + kind, sm, s, zn)] = None if r is None else r[1]
ev = pd.DataFrame([dict(session=k[2], zone=k[3], kind=k[0][2:], smooth=k[1], events=v) for k, v in MASKS.items() if k[0].startswith("n_") and v is not None])
print("approach events per session (median over sessions):"); print(ev.groupby(["kind", "smooth", "zone"]).events.median().unstack().to_string())
vb = pd.DataFrame([dict(session=k[1], zone=k[2], bins=int(v.sum())) for k, v in MASKS.items() if k[0] == "vic" and v is not None])
print("zone-vicinity 133-ms bins per session: median", vb.groupby("zone").bins.median().to_dict(), "min", vb.groupby("zone").bins.min().to_dict())

def cond_of(s):
    return AV[s]["meta"]["kind"].replace("training1", "training").replace("training2", "training")

def zone_tau_table(maskkey, kind="pc-int"):
    rows = []
    for mo in SESS:
        for pr in pairs_of(mo, kind):
            for cond in condn:
                ss = [s for s in AV if AV[s]["meta"]["mouse"] == mo and cond_of(s) == cond]
                for zn in ZN:
                    vals = [masked_tau(s, pr, MASKS[maskkey(s, zn)]) for s in ss]
                    vals = [v for v in vals if np.isfinite(v)]
                    if vals:
                        rows.append(dict(mouse=mo, pair=pr, cond=cond, zone=zn, tau=np.mean(vals)))
    return pd.DataFrame(rows)

def cell_lsd(T, y, f1, f2, target):
    """Fisher's LSD of one design cell against every other, with the two-way model's error."""
    t, m = H.anova2(T, y, f1, f2)
    mse, dfr = m.mse_resid, m.df_resid
    g = T.groupby([f1, f2])[y]
    a = g.get_group(target)
    out = []
    for k, b in g:
        if k == target:
            continue
        d = a.mean() - b.mean(); se = np.sqrt(mse * (1 / len(a) + 1 / len(b)))
        out.append((k, round(d, 4), round(2 * stats.t.sf(abs(d / se), dfr), 4)))
    return t, out
approach events per session (median over sessions):
zone          conflict  training
kind  smooth                    
avoid False      998.0    1037.0
      True       143.0     154.0
error False      126.0      68.0
      True        65.0      33.0
zone-vicinity 133-ms bins per session: median {'conflict': 1934.0, 'training': 1249.0} min {'conflict': 349, 'training': 144}

fig5e1-correlation-near-zone¶

During the conflict trial, place cell-interneuron correlations were higher near the current shock zone than near its prior location, with no such difference in pretraining or training.

In [39]:
TZ = zone_tau_table(lambda s, zn: ("vic", s, zn))
t, out = cell_lsd(TZ, "tau", "zone", "cond", ("conflict", "conflict"))
print("n =", len(TZ), "(paper df 806 imply 812)"); print(t.round(4).to_string())
print(TZ.groupby(["cond", "zone"]).tau.agg(["mean", "sem", "size"]).round(4).to_string())
print("LSD, conflict near conflict zone against each other cell (diff, p):", out)
print("by mouse, conflict trial:"); print(TZ[TZ.cond == "conflict"].groupby(["mouse", "zone"]).tau.mean().unstack().round(4).to_string())
n = 876 (paper df 806 imply 812)
             sum_sq     df       F  PR(>F)
zone         0.0008    1.0  0.5490  0.4589
cond         0.0002    2.0  0.0801  0.9231
zone x cond  0.0012    2.0  0.4274  0.6523
Residual     1.2513  870.0     NaN     NaN
                        mean     sem  size
cond        zone                          
conflict    conflict  0.0183  0.0035   134
            training  0.0130  0.0032   134
pretraining conflict  0.0160  0.0032   152
            training  0.0153  0.0028   152
training    conflict  0.0145  0.0025   152
            training  0.0147  0.0034   152
LSD, conflict near conflict zone against each other cell (diff, p): [(('conflict', 'pretraining'), np.float64(0.0023), np.float64(0.6092)), (('conflict', 'training'), np.float64(0.0038), np.float64(0.3974)), (('training', 'conflict'), np.float64(0.0053), np.float64(0.2535)), (('training', 'pretraining'), np.float64(0.0029), np.float64(0.5166)), (('training', 'training'), np.float64(0.0036), np.float64(0.4233))]
by mouse, conflict trial:
zone   conflict  training
mouse                    
WT16    -0.0112   -0.0047
WT19     0.0039   -0.0025
WT20     0.0213    0.0216
WT26     0.0110    0.0097
WT27     0.0460    0.0247

Result: Not reproduced. Zone-vicinity correlations show no zone by condition interaction (F = 0.43, p = 0.65); in conflict the mean tau near the conflict zone (0.018) is not above the other cells of the design (LSD p 0.25 to 0.61).

fig5e2-e4-change-near-zone¶

The correlation increases with shock relocation occurred only near the relocated shock zone, for all pairs, independent pairs and positive pairs.

In [40]:
def zone_change_table(maskfn, sd_reading, reading):
    rows = []
    for mo in SESS:
        for pr in pairs_of(mo, "pc-int"):
            for man, sp in av_pairs(reading)[mo].items():
                for zn in ZN:
                    ch = []
                    for s1, s2 in sp:
                        m1, m2 = MASKS[maskfn(s1, zn)], MASKS[maskfn(s2, zn)]
                        t1, t2 = masked_tau(s1, pr, m1), masked_tau(s2, pr, m2)
                        sd = tau_of(133, s1, pr)[1] if sd_reading == "a" else masked_sd6(s1, pr, m1)
                        if np.isfinite(t1) and np.isfinite(t2) and sd and sd > 0:
                            ch.append((t2 - t1) / sd)
                    if ch:
                        rows.append(dict(mouse=mo, pair=pr, manip=man, zone=zn, change=np.mean(ch)))
    return pd.DataFrame(rows)

cl = CLS[("a", "iii")].set_index("pair").cls
ZC = {}
for r in [MAN_ADOPT, "a"]:
    for sdr in "ab":
        Z = zone_change_table(lambda s, zn: ("vic", s, zn), sdr, r); Z["cls"] = Z.pair.map(cl); ZC[(r, sdr)] = Z
        for lab, sub in [("all", Z), ("independent", Z[Z.cls == "independent"]), ("positive", Z[Z.cls == "positive"])]:
            t, out = cell_lsd(sub, "change", "zone", "manip", ("conflict", "relocation"))
            means = sub.groupby(["zone", "manip"]).change.mean().round(3).to_dict()
            print(f"M11 {r}, SD reading {sdr}, {lab} pairs: n = {len(sub)}; interaction F = {t.loc['zone x manip', 'F']:.2f}, p = {t.loc['zone x manip', 'PR(>F)']:.4f}")
            print("    means:", means); print("    LSD relocation near conflict zone vs:", out)
M11 b, SD reading a, all pairs: n = 853; interaction F = 0.04, p = 0.9652
    means: {('conflict', 'addition'): -0.093, ('conflict', 'relocation'): 0.148, ('conflict', 'replication'): -0.103, ('training', 'addition'): -0.16, ('training', 'relocation'): 0.158, ('training', 'replication'): -0.099}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.2412), np.float64(0.2963)), (('conflict', 'replication'), np.float64(0.2514), np.float64(0.2841)), (('training', 'addition'), np.float64(0.3083), np.float64(0.1819)), (('training', 'relocation'), np.float64(-0.0096), np.float64(0.9679)), (('training', 'replication'), np.float64(0.2472), np.float64(0.2947))]
M11 b, SD reading a, independent pairs: n = 325; interaction F = 0.23, p = 0.7935
    means: {('conflict', 'addition'): 0.028, ('conflict', 'relocation'): 0.014, ('conflict', 'replication'): 0.031, ('training', 'addition'): 0.1, ('training', 'relocation'): -0.158, ('training', 'replication'): -0.206}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(-0.0141), np.float64(0.9672)), (('conflict', 'replication'), np.float64(-0.0163), np.float64(0.9632)), (('training', 'addition'), np.float64(-0.0856), np.float64(0.803)), (('training', 'relocation'), np.float64(0.1726), np.float64(0.6284)), (('training', 'replication'), np.float64(0.2207), np.float64(0.538))]
M11 b, SD reading a, positive pairs: n = 412; interaction F = 0.60, p = 0.5469
    means: {('conflict', 'addition'): -0.484, ('conflict', 'relocation'): 0.16, ('conflict', 'replication'): -0.194, ('training', 'addition'): -0.707, ('training', 'relocation'): 0.255, ('training', 'replication'): 0.105}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.6443), np.float64(0.0627)), (('conflict', 'replication'), np.float64(0.3542), np.float64(0.307)), (('training', 'addition'), np.float64(0.8671), np.float64(0.0124)), (('training', 'relocation'), np.float64(-0.0949), np.float64(0.788)), (('training', 'replication'), np.float64(0.0547), np.float64(0.8746))]
M11 b, SD reading b, all pairs: n = 833; interaction F = 0.29, p = 0.7513
    means: {('conflict', 'addition'): -0.021, ('conflict', 'relocation'): 0.111, ('conflict', 'replication'): -0.051, ('training', 'addition'): -0.036, ('training', 'relocation'): -0.014, ('training', 'replication'): -0.049}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.1315), np.float64(0.2826)), (('conflict', 'replication'), np.float64(0.161), np.float64(0.1955)), (('training', 'addition'), np.float64(0.1463), np.float64(0.232)), (('training', 'relocation'), np.float64(0.1244), np.float64(0.3445)), (('training', 'replication'), np.float64(0.1592), np.float64(0.203))]
M11 b, SD reading b, independent pairs: n = 323; interaction F = 0.72, p = 0.4876
    means: {('conflict', 'addition'): 0.003, ('conflict', 'relocation'): 0.044, ('conflict', 'replication'): 0.037, ('training', 'addition'): 0.103, ('training', 'relocation'): -0.082, ('training', 'replication'): -0.111}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.0417), np.float64(0.8)), (('conflict', 'replication'), np.float64(0.0071), np.float64(0.9666)), (('training', 'addition'), np.float64(-0.0587), np.float64(0.7217)), (('training', 'relocation'), np.float64(0.1265), np.float64(0.4648)), (('training', 'replication'), np.float64(0.1558), np.float64(0.3658))]
M11 b, SD reading b, positive pairs: n = 395; interaction F = 0.64, p = 0.5262
    means: {('conflict', 'addition'): -0.208, ('conflict', 'relocation'): 0.092, ('conflict', 'replication'): -0.135, ('training', 'addition'): -0.293, ('training', 'relocation'): 0.003, ('training', 'replication'): 0.059}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.2998), np.float64(0.1389)), (('conflict', 'replication'), np.float64(0.2268), np.float64(0.2642)), (('training', 'addition'), np.float64(0.3855), np.float64(0.0572)), (('training', 'relocation'), np.float64(0.0892), np.float64(0.6908)), (('training', 'replication'), np.float64(0.0326), np.float64(0.8724))]
M11 a, SD reading a, all pairs: n = 834; interaction F = 0.12, p = 0.8883
    means: {('conflict', 'addition'): -0.158, ('conflict', 'relocation'): 0.137, ('conflict', 'replication'): -0.103, ('training', 'addition'): 0.022, ('training', 'relocation'): 0.209, ('training', 'replication'): -0.099}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.2946), np.float64(0.2568)), (('conflict', 'replication'), np.float64(0.2401), np.float64(0.3631)), (('training', 'addition'), np.float64(0.1149), np.float64(0.6607)), (('training', 'relocation'), np.float64(-0.0725), np.float64(0.7924)), (('training', 'replication'), np.float64(0.2359), np.float64(0.374))]
M11 a, SD reading a, independent pairs: n = 321; interaction F = 0.97, p = 0.3786
    means: {('conflict', 'addition'): -0.141, ('conflict', 'relocation'): -0.025, ('conflict', 'replication'): 0.031, ('training', 'addition'): 0.358, ('training', 'relocation'): -0.063, ('training', 'replication'): -0.206}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.1159), np.float64(0.766)), (('conflict', 'replication'), np.float64(-0.0554), np.float64(0.8902)), (('training', 'addition'), np.float64(-0.3832), np.float64(0.3274)), (('training', 'relocation'), np.float64(0.0386), np.float64(0.9253)), (('training', 'replication'), np.float64(0.1817), np.float64(0.6553))]
M11 a, SD reading a, positive pairs: n = 397; interaction F = 0.39, p = 0.6745
    means: {('conflict', 'addition'): -0.46, ('conflict', 'relocation'): 0.224, ('conflict', 'replication'): -0.194, ('training', 'addition'): -0.644, ('training', 'relocation'): 0.234, ('training', 'replication'): 0.105}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.6837), np.float64(0.0815)), (('conflict', 'replication'), np.float64(0.4178), np.float64(0.2882)), (('training', 'addition'), np.float64(0.8672), np.float64(0.0296)), (('training', 'relocation'), np.float64(-0.0104), np.float64(0.9802)), (('training', 'replication'), np.float64(0.1183), np.float64(0.7635))]
M11 a, SD reading b, all pairs: n = 788; interaction F = 0.55, p = 0.5778
    means: {('conflict', 'addition'): -0.054, ('conflict', 'relocation'): 0.1, ('conflict', 'replication'): -0.051, ('training', 'addition'): 0.086, ('training', 'relocation'): 0.051, ('training', 'replication'): -0.049}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.1539), np.float64(0.2337)), (('conflict', 'replication'), np.float64(0.1506), np.float64(0.2447)), (('training', 'addition'), np.float64(0.0138), np.float64(0.9156)), (('training', 'relocation'), np.float64(0.0489), np.float64(0.7313)), (('training', 'replication'), np.float64(0.1487), np.float64(0.2529))]
M11 a, SD reading b, independent pairs: n = 308; interaction F = 1.81, p = 0.1659
    means: {('conflict', 'addition'): -0.031, ('conflict', 'relocation'): -0.009, ('conflict', 'replication'): 0.037, ('training', 'addition'): 0.244, ('training', 'relocation'): -0.021, ('training', 'replication'): -0.111}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.0222), np.float64(0.8916)), (('conflict', 'replication'), np.float64(-0.0462), np.float64(0.7809)), (('training', 'addition'), np.float64(-0.2527), np.float64(0.1205)), (('training', 'relocation'), np.float64(0.0123), np.float64(0.9449)), (('training', 'replication'), np.float64(0.1025), np.float64(0.5426))]
M11 a, SD reading b, positive pairs: n = 368; interaction F = 0.44, p = 0.6440
    means: {('conflict', 'addition'): -0.262, ('conflict', 'relocation'): 0.163, ('conflict', 'replication'): -0.135, ('training', 'addition'): -0.24, ('training', 'relocation'): 0.06, ('training', 'replication'): 0.059}
    LSD relocation near conflict zone vs: [(('conflict', 'addition'), np.float64(0.4258), np.float64(0.0529)), (('conflict', 'replication'), np.float64(0.2983), np.float64(0.1686)), (('training', 'addition'), np.float64(0.4035), np.float64(0.0756)), (('training', 'relocation'), np.float64(0.1033), np.float64(0.6746)), (('training', 'replication'), np.float64(0.1041), np.float64(0.6306))]

Result: Not reproduced. Under every reading of M11 and of the SD, the zone by manipulation interaction has p ≥ 0.17 for all, independent and positive pairs, against p = 0.0044, 0.0011 and 0.00001.

fig5e1-inset-rate-change-near-zone¶

Rate remapping in the shock zone vicinities rose similarly with shock addition and relocation and did not follow the pattern of the correlations.

In [41]:
def masked_rate(s, u, mask):
    if mask is None or mask.sum() < 20:
        return np.nan
    return BINS[s]["counts"][u][mask].sum() / (mask.sum() * STEP / AV[s]["pos"]["fs"])

def zone_rate_change(maskfn, reading, cls="pc"):
    rows = []
    for mo in SESS:
        us = [(c.mouse, c.tetrode, c.cluster) for c in cells_av[(cells_av.mouse == mo) & (cells_av.cls == cls)].itertuples()]
        for u in us:
            for man, sp in av_pairs(reading)[mo].items():
                for zn in ZN:
                    ch = []
                    for s1, s2 in sp:
                        r1, r2 = masked_rate(s1, u, MASKS[maskfn(s1, zn)]), masked_rate(s2, u, MASKS[maskfn(s2, zn)])
                        if np.isfinite(r1) and np.isfinite(r2):
                            v = H.rate_change(r1, r2)
                            if np.isfinite(v):
                                ch.append(abs(v))
                    if ch:
                        rows.append(dict(mouse=mo, cell=u, manip=man, zone=zn, achange=np.mean(ch)))
    return pd.DataFrame(rows)

for r in [MAN_ADOPT, "a"]:
    RZ = zone_rate_change(lambda s, zn: ("vic", s, zn), r)
    t, m = H.anova2(RZ, "achange", "zone", "manip")
    print(f"M11 {r}: n = {len(RZ)} (paper df 245 imply 251)"); print(t.round(4).to_string())
    print(RZ.groupby(["manip"]).achange.agg(["mean", "sem", "size"]).round(3).to_string())
    print("LSD on manipulation:", H.lsd([RZ[RZ.manip == k].achange for k in names], names, m.mse_resid, m.df_resid)[["a", "b", "diff", "p"]].round(4).values.tolist())
M11 b: n = 230 (paper df 245 imply 251)
               sum_sq     df       F  PR(>F)
zone           0.3877    1.0  7.7472  0.0058
manip          0.2862    2.0  2.8599  0.0594
zone x manip   0.0260    2.0  0.2595  0.7717
Residual      11.2086  224.0     NaN     NaN
              mean    sem  size
manip                          
addition     0.469  0.023    84
relocation   0.489  0.028    72
replication  0.405  0.027    74
LSD on manipulation: [['replication', 'addition', -0.0641, 0.0737], ['replication', 'relocation', -0.0843, 0.0238], ['addition', 'relocation', -0.0202, 0.5748]]
M11 a: n = 230 (paper df 245 imply 251)
               sum_sq     df       F  PR(>F)
zone           0.2950    1.0  4.7681  0.0300
manip          0.2688    2.0  2.1724  0.1163
zone x manip   0.0215    2.0  0.1736  0.8408
Residual      13.8578  224.0     NaN     NaN
              mean    sem  size
manip                          
addition     0.440  0.028    84
relocation   0.490  0.031    72
replication  0.405  0.027    74
LSD on manipulation: [['replication', 'addition', -0.035, 0.3782], ['replication', 'relocation', -0.0854, 0.0392], ['addition', 'relocation', -0.0504, 0.2085]]

Result: Not reproduced. Zone-vicinity rate changes are higher for addition (0.47) and relocation (0.49) than replication (0.41) and show no interaction (p = 0.77), but the manipulation effect is p = 0.059 under reading (b) and p = 0.12 under reading (a), against p = 0.0001.

correlation-not-speed¶

Zone-vicinity correlations were not related to running speed or acceleration but were weakly related to place cell and interneuron firing rates, which did not differ across conditions.

In [42]:
rows = []
W6 = 45  # 45 bins of 133 ms = 6 s
for s, v in AV.items():
    p = v["pos"]; fs = p["fs"]
    x = pd.Series(np.where(H.tracked(p["rx"], p["ry"]), p["rx"], np.nan)).interpolate().bfill().ffill().values
    y = pd.Series(np.where(H.tracked(p["rx"], p["ry"]), p["ry"], np.nan)).interpolate().bfill().ffill().values
    k = int(round(fs))
    xs = pd.Series(x).rolling(k, center=True, min_periods=1).mean().values; ys = pd.Series(y).rolling(k, center=True, min_periods=1).mean().values
    sp = np.hypot(np.gradient(xs), np.gradient(ys)) * fs / H.PX_PER_CM  # cm/s, ~1-s rolling window
    acc = np.gradient(pd.Series(sp).rolling(k, center=True, min_periods=1).mean().values) * fs
    n6 = BINS[s]["n"] // W6
    spb = sp[:n6 * W6 * STEP].reshape(n6, -1).mean(1); acb = acc[:n6 * W6 * STEP].reshape(n6, -1).mean(1)
    for pr in pairs_of(v["meta"]["mouse"], "pc-int"):
        a = BINS[s]["counts"][pr[0]][:n6 * W6].reshape(n6, W6); b = BINS[s]["counts"][pr[1]][:n6 * W6].reshape(n6, W6)
        for j in range(n6):
            if a[j].std() > 0 and b[j].std() > 0:
                rows.append(dict(session=s, mouse=v["meta"]["mouse"], tau=stats.kendalltau(a[j], b[j]).statistic, speed=spb[j], acc=acb[j],
                                 pc_rate=a[j].sum() / 6.0, int_rate=b[j].sum() / 6.0))
SB = pd.DataFrame(rows)
print("6-s bins with both cells active:", len(SB), "; speed range (cm/s)", SB.speed.min().round(2), SB.speed.max().round(2))
for col in ["speed", "acc", "pc_rate", "int_rate"]:
    r_, p_ = stats.pearsonr(SB[col], SB.tau)
    print(f"tau vs {col}: r = {r_:.4f}, r2 = {r_**2:.5f}, p = {p_:.4g}")
rows = []
for s in AV:
    for u in AV[s]["units"]:
        for zn in ZN:
            r_ = masked_rate(s, u, MASKS[("vic", s, zn)])
            if np.isfinite(r_):
                rows.append(dict(cell=u, cls=AV[s]["units"][u]["cls"], cond=cond_of(s), zone=zn, rate=r_))
RR = pd.DataFrame(rows).groupby(["cell", "cls", "cond", "zone"]).rate.mean().reset_index()
for lab, sub in [("all cells", RR), ("place cells", RR[RR.cls == "pc"]), ("interneurons", RR[RR.cls == "int"])]:
    t, _ = H.anova2(sub, "rate", "zone", "cond")
    print(f"zone-vicinity rate, {lab}, n = {len(sub)} (paper df 293 imply 299):"); print(t.round(4).to_string())
6-s bins with both cells active: 88180 ; speed range (cm/s) 0.21 14.45
tau vs speed: r = -0.0055, r2 = 0.00003, p = 0.1049
tau vs acc: r = -0.0066, r2 = 0.00004, p = 0.05004
tau vs pc_rate: r = 0.0299, r2 = 0.00089, p = 6.439e-19
tau vs int_rate: r = 0.0210, r2 = 0.00044, p = 4.201e-10
zone-vicinity rate, all cells, n = 360 (paper df 293 imply 299):
                 sum_sq     df       F  PR(>F)
zone             1.1005    1.0  0.0111  0.9163
cond            65.3205    2.0  0.3281  0.7205
zone x cond      8.1358    2.0  0.0409  0.9600
Residual     35235.2088  354.0     NaN     NaN
zone-vicinity rate, place cells, n = 240 (paper df 293 imply 299):
               sum_sq     df       F  PR(>F)
zone           3.2258    1.0  1.6935  0.1944
cond           0.3069    2.0  0.0806  0.9226
zone x cond    1.0273    2.0  0.2697  0.7639
Residual     445.7390  234.0     NaN     NaN
zone-vicinity rate, interneurons, n = 120 (paper df 293 imply 299):
                 sum_sq     df       F  PR(>F)
zone            18.9833    1.0  0.1320  0.7171
cond           207.6147    2.0  0.7217  0.4882
zone x cond     13.1186    2.0  0.0456  0.9554
Residual     16398.5713  114.0     NaN     NaN

Result: Reproduced, narrowly. Over 88180 6-s bins, tau is not related to speed (r = -0.0055, p = 0.105) and not to acceleration (r = -0.0066, p = 0.05004, at the threshold, so this part is fragile); it is weakly related to place cell rate (r2 = 0.0009, p < 0.001) and interneuron rate (r2 = 0.0004, p < 0.001). Zone-vicinity rates show no zone (p = 0.92) or condition effect (p = 0.72).

fig6b-correlation-before-avoidance, fig6c-no-increase-before-errors¶

Place cell-interneuron correlations increased in the 4 s before successful avoidances of the relocated shock zone in the conflict trial. No place cell-interneuron correlation increase was present before failed avoidances (shock zone entries).

In [43]:
FIG6 = {}
for kind in ["avoid", "error"]:
    for sm in [False, True]:
        T6 = zone_tau_table(lambda s, zn: (kind, sm, s, zn))
        T6["pid"] = T6.pair.map(str)
        t, out = cell_lsd(T6, "tau", "zone", "cond", ("conflict", "conflict"))
        try:
            mt, _ = H.mixed_terms(T6[["tau", "zone", "cond", "pid"]], "tau ~ C(zone, Sum) * C(cond, Sum)", "pid",
                                  {"zone": "zone", "condition": "cond", "interaction": "zone&cond"})
            mtxt = mt.round(4).values.tolist()
        except Exception as e:
            mtxt = f"mixed model failed: {e}"
        cellmeans = T6.groupby(["cond", "zone"]).tau.mean()
        FIG6[(kind, sm)] = dict(p_int=t.loc["zone x cond", "PR(>F)"], top=cellmeans.idxmax())
        print(f"{kind}, minima on {'1-s smoothed' if sm else 'raw'} distance: n = {len(T6)}")
        print(t.round(4).to_string()); print("   mixed (pair random):", mtxt)
        print("   cell means:", cellmeans.round(4).to_dict()); print("   LSD conflict-near-conflict vs:", out)
avoid, minima on raw distance: n = 876
             sum_sq     df       F  PR(>F)
zone         0.0010    1.0  0.9603  0.3274
cond         0.0020    2.0  0.9757  0.3773
zone x cond  0.0017    2.0  0.8235  0.4393
Residual     0.9125  870.0     NaN     NaN
   mixed (pair random): [['zone', 2.4829, 1, 870.0, 0.1155], ['condition', 3.0459, 2, 870.0, 0.0481], ['interaction', 2.129, 2, 870.0, 0.1196]]
   cell means: {('conflict', 'conflict'): 0.0189, ('conflict', 'training'): 0.0132, ('pretraining', 'conflict'): 0.0158, ('pretraining', 'training'): 0.017, ('training', 'conflict'): 0.014, ('training', 'training'): 0.0121}
   LSD conflict-near-conflict vs: [(('conflict', 'pretraining'), np.float64(0.0031), np.float64(0.419)), (('conflict', 'training'), np.float64(0.0049), np.float64(0.2059)), (('training', 'conflict'), np.float64(0.0057), np.float64(0.1491)), (('training', 'pretraining'), np.float64(0.0019), np.float64(0.6297)), (('training', 'training'), np.float64(0.0068), np.float64(0.075))]
avoid, minima on 1-s smoothed distance: n = 876
             sum_sq     df       F  PR(>F)
zone         0.0006    1.0  0.5071  0.4766
cond         0.0039    2.0  1.7488  0.1746
zone x cond  0.0027    2.0  1.1968  0.3027
Residual     0.9678  870.0     NaN     NaN
   mixed (pair random): [['zone', 1.0911, 1, 870.0, 0.2965], ['condition', 3.9352, 2, 870.0, 0.0199], ['interaction', 2.5749, 2, 870.0, 0.0767]]
   cell means: {('conflict', 'conflict'): 0.018, ('conflict', 'training'): 0.0124, ('pretraining', 'conflict'): 0.016, ('pretraining', 'training'): 0.0189, ('training', 'conflict'): 0.0135, ('training', 'training'): 0.0113}
   LSD conflict-near-conflict vs: [(('conflict', 'pretraining'), np.float64(0.002), np.float64(0.6108)), (('conflict', 'training'), np.float64(0.0045), np.float64(0.2525)), (('training', 'conflict'), np.float64(0.0056), np.float64(0.1683)), (('training', 'pretraining'), np.float64(-0.0009), np.float64(0.8152)), (('training', 'training'), np.float64(0.0067), np.float64(0.092))]
error, minima on raw distance: n = 866
             sum_sq     df       F  PR(>F)
zone         0.0007    1.0  0.5395  0.4628
cond         0.0062    2.0  2.2607  0.1049
zone x cond  0.0009    2.0  0.3275  0.7208
Residual     1.1759  860.0     NaN     NaN
   mixed (pair random): [['zone', 0.8106, 1, 860.0, 0.3682], ['condition', 3.6832, 2, 860.0, 0.0255], ['interaction', 0.501, 2, 860.0, 0.6061]]
   cell means: {('conflict', 'conflict'): 0.0165, ('conflict', 'training'): 0.0137, ('pretraining', 'conflict'): 0.017, ('pretraining', 'training'): 0.0179, ('training', 'conflict'): 0.0129, ('training', 'training'): 0.0092}
   LSD conflict-near-conflict vs: [(('conflict', 'pretraining'), np.float64(-0.0005), np.float64(0.9094)), (('conflict', 'training'), np.float64(0.0036), np.float64(0.4163)), (('training', 'conflict'), np.float64(0.0028), np.float64(0.5377)), (('training', 'pretraining'), np.float64(-0.0014), np.float64(0.7441)), (('training', 'training'), np.float64(0.0073), np.float64(0.1035))]
error, minima on 1-s smoothed distance: n = 861
             sum_sq     df       F  PR(>F)
zone         0.0007    1.0  0.3704  0.5430
cond         0.0016    2.0  0.4166  0.6594
zone x cond  0.0003    2.0  0.0693  0.9331
Residual     1.6132  855.0     NaN     NaN
   mixed (pair random): [['zone', 0.5529, 1, 855.0, 0.4573], ['condition', 0.753, 2, 855.0, 0.4713], ['interaction', 0.1003, 2, 855.0, 0.9046]]
   cell means: {('conflict', 'conflict'): 0.0157, ('conflict', 'training'): 0.0189, ('pretraining', 'conflict'): 0.0177, ('pretraining', 'training'): 0.0182, ('training', 'conflict'): 0.0139, ('training', 'training'): 0.0157}
   LSD conflict-near-conflict vs: [(('conflict', 'pretraining'), np.float64(-0.002), np.float64(0.7022)), (('conflict', 'training'), np.float64(0.0018), np.float64(0.7231)), (('training', 'conflict'), np.float64(-0.0031), np.float64(0.5531)), (('training', 'pretraining'), np.float64(-0.0024), np.float64(0.6396)), (('training', 'training'), np.float64(0.0), np.float64(0.9998))]

Result: Not reproduced. Before avoidances the zone by condition interaction is p = 0.44 (raw minima) and p = 0.30 (smoothed); with pair as random term p = 0.12 and 0.077. With raw minima conflict near the conflict zone is the highest cell (0.019), but not above the others by LSD (p 0.075 to 0.63); with smoothed minima pretraining near the training zone (0.0189) is above it (0.018), and the LSD p are 0.092 to 0.82.

Result: Reproduced. Before errors the zone by condition interaction is p = 0.72 (raw minima) and p = 0.93 (smoothed).

fig6-inset-rate-changes¶

Rate changes before avoidances and errors differed across manipulations but did not follow the pattern of the correlation increases.

In [44]:
for kind in ["avoid", "error"]:
    for sm in [False, True]:
        for r in "ab":  # M11 reading (b) adopted, (a) beside it
            RZ6 = zone_rate_change(lambda s, zn: (kind, sm, s, zn), r)
            t, m = H.anova2(RZ6, "achange", "zone", "manip")
            print(f"{kind}, {'smoothed' if sm else 'raw'} minima, M11 {r}: n = {len(RZ6)}"); print(t.round(4).to_string())
            print("   means by zone x manipulation:", RZ6.groupby(["zone", "manip"]).achange.mean().round(3).to_dict())
avoid, raw minima, M11 a: n = 230
               sum_sq     df       F  PR(>F)
zone           0.0295    1.0  0.5738  0.4496
manip          0.4399    2.0  4.2740  0.0151
zone x manip   0.0491    2.0  0.4774  0.6210
Residual      11.5280  224.0     NaN     NaN
   means by zone x manipulation: {('conflict', 'addition'): 0.428, ('conflict', 'relocation'): 0.425, ('conflict', 'replication'): 0.302, ('training', 'addition'): 0.386, ('training', 'relocation'): 0.381, ('training', 'replication'): 0.321}
avoid, raw minima, M11 b: n = 230
              sum_sq     df       F  PR(>F)
zone          0.0136    1.0  0.3469  0.5565
manip         0.6289    2.0  8.0182  0.0004
zone x manip  0.0344    2.0  0.4388  0.6454
Residual      8.7842  224.0     NaN     NaN
   means by zone x manipulation: {('conflict', 'addition'): 0.444, ('conflict', 'relocation'): 0.435, ('conflict', 'replication'): 0.302, ('training', 'addition'): 0.408, ('training', 'relocation'): 0.406, ('training', 'replication'): 0.321}
avoid, smoothed minima, M11 a: n = 230
               sum_sq     df       F  PR(>F)
zone           0.0119    1.0  0.2194  0.6400
manip          0.2897    2.0  2.6700  0.0715
zone x manip   0.0135    2.0  0.1244  0.8831
Residual      12.1537  224.0     NaN     NaN
   means by zone x manipulation: {('conflict', 'addition'): 0.425, ('conflict', 'relocation'): 0.428, ('conflict', 'replication'): 0.334, ('training', 'addition'): 0.404, ('training', 'relocation'): 0.398, ('training', 'replication'): 0.341}
avoid, smoothed minima, M11 b: n = 230
              sum_sq     df       F  PR(>F)
zone          0.0202    1.0  0.4841  0.4873
manip         0.4199    2.0  5.0235  0.0073
zone x manip  0.0303    2.0  0.3625  0.6963
Residual      9.3607  224.0     NaN     NaN
   means by zone x manipulation: {('conflict', 'addition'): 0.454, ('conflict', 'relocation'): 0.436, ('conflict', 'replication'): 0.334, ('training', 'addition'): 0.406, ('training', 'relocation'): 0.42, ('training', 'replication'): 0.341}
error, raw minima, M11 a: n = 230
               sum_sq     df       F  PR(>F)
zone           0.3467    1.0  5.1117  0.0247
manip          0.2944    2.0  2.1701  0.1166
zone x manip   0.1620    2.0  1.1944  0.3048
Residual      15.1922  224.0     NaN     NaN
   means by zone x manipulation: {('conflict', 'addition'): 0.441, ('conflict', 'relocation'): 0.484, ('conflict', 'replication'): 0.333, ('training', 'addition'): 0.5, ('training', 'relocation'): 0.507, ('training', 'replication'): 0.484}
error, raw minima, M11 b: n = 230
               sum_sq     df       F  PR(>F)
zone           0.5093    1.0  9.9952  0.0018
manip          0.4547    2.0  4.4622  0.0126
zone x manip   0.1031    2.0  1.0121  0.3651
Residual      11.4127  224.0     NaN     NaN
   means by zone x manipulation: {('conflict', 'addition'): 0.462, ('conflict', 'relocation'): 0.48, ('conflict', 'replication'): 0.333, ('training', 'addition'): 0.546, ('training', 'relocation'): 0.527, ('training', 'replication'): 0.484}
error, smoothed minima, M11 a: n = 224
               sum_sq     df       F  PR(>F)
zone           0.1985    1.0  3.0193  0.0837
manip          0.9128    2.0  6.9415  0.0012
zone x manip   0.1281    2.0  0.9742  0.3791
Residual      14.3332  218.0     NaN     NaN
   means by zone x manipulation: {('conflict', 'addition'): 0.456, ('conflict', 'relocation'): 0.541, ('conflict', 'replication'): 0.33, ('training', 'addition'): 0.478, ('training', 'relocation'): 0.57, ('training', 'replication'): 0.459}
error, smoothed minima, M11 b: n = 224
               sum_sq     df       F  PR(>F)
zone           0.3539    1.0  7.2884  0.0075
manip          0.8612    2.0  8.8692  0.0002
zone x manip   0.0655    2.0  0.6745  0.5105
Residual      10.5842  218.0     NaN     NaN
   means by zone x manipulation: {('conflict', 'addition'): 0.473, ('conflict', 'relocation'): 0.523, ('conflict', 'replication'): 0.33, ('training', 'addition'): 0.536, ('training', 'relocation'): 0.57, ('training', 'replication'): 0.459}

Result: Reproduced, resting on the M11 assumption. Under M11 reading (b), before avoidances rate changes differ across manipulations (p = 0.0004 raw, 0.0073 smoothed) and not between zones (p = 0.56, 0.49) or by interaction (p = 0.65, 0.70); before errors both zone (p = 0.0018, 0.0075) and manipulation (p = 0.013, 0.0002) effects are present, as the Figure 6C legend says. Under reading (a) the criterion fails with either minima: with raw minima the avoidance pattern holds (manipulation p = 0.015; zone p = 0.45, interaction p = 0.62) but the error manipulation effect does not (p = 0.12; zone p = 0.025); with smoothed minima the avoidance manipulation effect is p = 0.072 and the error zone effect p = 0.084 (error manipulation p = 0.0012).

Positional information (Figure 4)¶

Ipos per place cell per 133-ms step in the room and the arena frame (M6), with location x the 8-pixel bin (reading a) or a 16-pixel block (reading b) of the step's middle position. Ensemble ΔIpos is the sum of room Ipos minus the sum of arena Ipos over the mouse's place cells.

In [45]:
def ipos_session(s, block):
    v = AV[s]; p = v["pos"]; n = BINS[s]["n"]
    mid = np.arange(n) * STEP + STEP // 2
    out = {}
    for fr, (x, y) in {"room": (p["rx"], p["ry"]), "arena": (p["ax"], p["ay"])}.items():
        xm, ym = x[mid], y[mid]; ok = H.tracked(xm, ym)
        nb = 256 // block
        loc = (np.clip(ym // block, 0, nb - 1) * nb + np.clip(xm // block, 0, nb - 1)).astype(int)
        tot = np.zeros(n); valid = ok.copy()
        for u, d in v["units"].items():
            if d["cls"] != "pc":
                continue
            ip = H.ipos_series(BINS[s]["counts"][u], loc, ok)
            tot = tot + np.nan_to_num(ip)
        tot[~valid] = np.nan
        out[fr] = tot
    out["d"] = out["room"] - out["arena"]
    return out

IP = {blk: {s: ipos_session(s, blk) for s in AV} for blk in [8, 16]}
for blk in [8, 16]:
    allv = np.concatenate([IP[blk][s]["d"] for s in AV])
    print(f"location {blk} px: ensemble dIpos per step, finite {np.isfinite(allv).mean():.3f}, range {np.nanmin(allv):.2f} to {np.nanmax(allv):.2f} bits, mean {np.nanmean(allv):.3f}")
location 8 px: ensemble dIpos per step, finite 0.996, range -18.50 to 22.20 bits, mean 0.045
location 16 px: ensemble dIpos per step, finite 0.996, range -15.11 to 14.74 bits, mean 0.082

ipos-speed-correlation¶

Ensemble ΔIpos was only weakly related to running speed, explaining 0.69% of the variance.

In [46]:
rows = []
for blk in [8, 16]:
    for sp_r in ["a", "b"]:
        D, S_ = [], []
        for s in AV:
            p = AV[s]["pos"]; n = BINS[s]["n"]
            x = pd.Series(np.where(H.tracked(p["rx"], p["ry"]), p["rx"], np.nan)).interpolate().bfill().ffill().values
            y = pd.Series(np.where(H.tracked(p["rx"], p["ry"]), p["ry"], np.nan)).interpolate().bfill().ffill().values
            if sp_r == "a":
                xb, yb = x[:n * STEP].reshape(n, STEP), y[:n * STEP].reshape(n, STEP)
                sp = np.hypot(xb[:, -1] - xb[:, 0], yb[:, -1] - yb[:, 0]) / H.PX_PER_CM / ((STEP - 1) / p["fs"])
            else:
                k = int(round(p["fs"]))
                xs = pd.Series(x).rolling(k, center=True, min_periods=1).mean().values; ys = pd.Series(y).rolling(k, center=True, min_periods=1).mean().values
                spf = np.hypot(np.gradient(xs), np.gradient(ys)) * p["fs"] / H.PX_PER_CM
                sp = spf[:n * STEP].reshape(n, STEP).mean(1)
            D.append(IP[blk][s]["d"]); S_.append(sp)
        D, S_ = np.concatenate(D), np.concatenate(S_); ok = np.isfinite(D) & np.isfinite(S_)
        r_, p_ = stats.pearsonr(D[ok], S_[ok])
        rows.append(dict(location_px=blk, speed_reading=sp_r, n_steps=int(ok.sum()), r=r_, r2_pct=100 * r_ ** 2, p=p_))
IPS = pd.DataFrame(rows); print(IPS.to_string()); print("expected r2 = 0.69 +/- 0.069 %, p < 0.001")
   location_px speed_reading  n_steps         r    r2_pct              p
0            8             a   224139  0.031263  0.097736   1.372671e-49
1            8             b   224139  0.043993  0.193542   1.961144e-96
2           16             a   224139  0.074309  0.552187  7.198058e-272
3           16             b   224139  0.103874  1.078987   0.000000e+00
expected r2 = 0.69 +/- 0.069 %, p < 0.001

Result: Not reproduced. ΔIpos is weakly related to speed (p < 0.001 in all readings), but the variance explained is 0.10 to 1.08%, and none of the four readings gives 0.69 ± 0.069% (closest 0.55%, 16-pixel locations and 133-ms displacement).

fig4b-room-preference-pretraining¶

Room-frame information dominated arena-frame information more often during pretraining, and this preference disappeared when shock was added or relocated.

In [47]:
for blk in [8, 16]:
    rows = []
    for s in AV:
        d = IP[blk][s]["d"]; ok = np.isfinite(d)
        rows.append(dict(mouse=AV[s]["meta"]["mouse"], cond=cond_of(s), room=(d[ok] > 0).mean(), arena=(d[ok] < 0).mean()))
    FB = pd.DataFrame(rows).groupby(["mouse", "cond"])[["room", "arena"]].mean().reset_index()
    L = FB.melt(id_vars=["mouse", "cond"], var_name="frame", value_name="frac")
    tab, _ = H.mixed_terms(L, "frac ~ C(frame, Sum) * C(cond, Sum)", "mouse", {"frame": "frame", "condition": "cond", "interaction": "frame&cond"})
    print(f"location {blk} px: fraction of time room- or arena-preferring, per mouse and condition (n mice per condition {FB.groupby('cond').size().to_dict()})")
    print(FB.groupby("cond")[["room", "arena"]].agg(["mean", "sem"]).round(3).to_string())
    print(tab.round(4).to_string())
    print("   with the paper's df (frame 1, 10.6; condition and interaction 2, 19.8): p =",
          [round(float(stats.f.sf(F_, d1, d2)), 4) for F_, d1, d2 in zip(tab.F, [1, 2, 2], [10.6, 19.8, 19.8])])
    for c in condn:
        sub = FB[FB.cond == c]
        t = stats.ttest_rel(sub.room, sub.arena)
        print(f"   {c}: room - arena = {np.mean(sub.room - sub.arena):.3f}, paired t = {t.statistic:.2f}, p = {t.pvalue:.4f}")
location 8 px: fraction of time room- or arena-preferring, per mouse and condition (n mice per condition {'conflict': 5, 'pretraining': 6, 'training': 6})
              room         arena       
              mean    sem   mean    sem
cond                                   
conflict     0.495  0.026  0.492  0.023
pretraining  0.590  0.028  0.410  0.028
training     0.492  0.035  0.506  0.036
          term       F  df1   df2       p
0        frame  5.0927    1  28.0  0.0320
1    condition  0.0251    2  28.0  0.9752
2  interaction  6.5476    2  28.0  0.0046
   with the paper's df (frame 1, 10.6; condition and interaction 2, 19.8): p = [0.0462, 0.9752, 0.0066]
   pretraining: room - arena = 0.180, paired t = 3.24, p = 0.0229
   training: room - arena = -0.015, paired t = -0.21, p = 0.8415
   conflict: room - arena = 0.003, paired t = 0.06, p = 0.9534
location 16 px: fraction of time room- or arena-preferring, per mouse and condition (n mice per condition {'conflict': 5, 'pretraining': 6, 'training': 6})
              room         arena       
              mean    sem   mean    sem
cond                                   
conflict     0.570  0.045  0.429  0.045
pretraining  0.691  0.054  0.309  0.054
training     0.581  0.057  0.419  0.057
          term        F  df1   df2       p
0        frame  26.9813    1  28.0  0.0000
1    condition   0.0001    2  28.0  0.9999
2  interaction   3.1591    2  28.0  0.0579
   with the paper's df (frame 1, 10.6; condition and interaction 2, 19.8): p = [0.0003, 0.9999, 0.0645]
   pretraining: room - arena = 0.382, paired t = 3.51, p = 0.0171
   training: room - arena = 0.162, paired t = 1.41, p = 0.2170
   conflict: room - arena = 0.140, paired t = 1.56, p = 0.1930

Result: Reproduced, resting on the M6 assumption (8-pixel locations). The frame by condition interaction is F = 6.55, p = 0.0046 (p = 0.0066 with the paper's df); room-preferring time exceeds arena-preferring time in pretraining (0.59 against 0.41, p = 0.023) and not in training (p = 0.84) or conflict (p = 0.95). With 16-pixel locations the interaction is p = 0.058 (0.065 with the paper's df).

fig4c-ipos-before-avoidance¶

In the ~1 s before approaches to a shock zone, ΔIpos was positive (room-preferring) and larger near the currently shocked zone than near the opposite zone, following the zone to its new location in conflict.

In [48]:
def minima_50(s, zn, smooth):
    p = AV[s]["pos"]; mo = AV[s]["meta"]["mouse"]
    if ZONES[mo][zn] is None:
        return np.array([], int)
    d = DIST[(s, zn)].copy(); d[~H.tracked(p["rx"], p["ry"])] = np.nan
    if smooth:
        d = pd.Series(d).rolling(int(round(p["fs"])), center=True, min_periods=1).mean().values
    ok = np.isfinite(d); i = np.arange(1, len(d) - 1)
    m = ok[i] & ok[i - 1] & ok[i + 1] & (d[i] < d[i - 1]) & (d[i] <= d[i + 1]) & (d[i] < 0.5 * np.nanmean(d))
    return i[m]

res4c = []
for blk in [8, 16]:
    for sm in [False, True]:
        for win in [0.8, 1.0, 1.2]:
            rows = []
            for s in AV:
                dI = IP[blk][s]["d"]; fs = AV[s]["pos"]["fs"]
                for zn in ZN:
                    mins = minima_50(s, zn, sm)
                    vals = []
                    for m in mins:
                        b1 = m // STEP; b0 = max(0, int((m - win * fs) // STEP))
                        seg = dI[b0:b1]
                        if np.isfinite(seg).any():
                            vals.append(np.nanmean(seg))
                    if vals:
                        rows.append(dict(mouse=AV[s]["meta"]["mouse"], cond=cond_of(s), zone=zn, dI=np.mean(vals), n_events=len(vals)))
            F4 = pd.DataFrame(rows).groupby(["mouse", "cond", "zone"]).agg(dI=("dI", "mean"), n_events=("n_events", "sum")).reset_index()
            tab, _ = H.mixed_terms(F4, "dI ~ C(cond, Sum) * C(zone, Sum)", "mouse", {"condition": "cond", "zone": "zone", "interaction": "cond&zone"})
            mz = F4.groupby(["cond", "zone"]).dI.mean()
            ok = (tab.p[2] < 0.05) and mz[("training", "training")] > mz[("training", "conflict")] and mz[("conflict", "conflict")] > mz[("conflict", "training")] \
                and mz[("training", "training")] > 0 and mz[("conflict", "conflict")] > 0
            res4c.append(dict(location_px=blk, smoothed=sm, window_s=win, p_interaction=tab.p[2], F_interaction=tab.F[2], **{f"{c}|{z}": mz[(c, z)] for c, z in mz.index}, criterion_met=ok))
            if blk == 8 and not sm and win == 1.0:
                print("main reading (8 px, raw minima, 1 s):"); print(F4.groupby(["cond", "zone"]).agg(dI=("dI", "mean"), sem=("dI", "sem"), mice=("dI", "size"), events=("n_events", "sum")).round(4).to_string())
                print(tab.round(4).to_string())
R4C = pd.DataFrame(res4c); print(R4C.round(4).to_string())
main reading (8 px, raw minima, 1 s):
                          dI     sem  mice  events
cond        zone                                  
conflict    conflict  0.0699  0.0362     5    3522
            training  0.0014  0.0240     5    4841
pretraining conflict  0.0507  0.0330     6    7185
            training  0.0754  0.0233     6    7119
training    conflict -0.0557  0.0210     6    8739
            training  0.2283  0.0429     6    5129
          term        F  df1   df2       p
0    condition   1.9612    2  28.0  0.1595
1         zone  12.9248    1  28.0  0.0012
2  interaction  22.5233    2  28.0  0.0000
    location_px  smoothed  window_s  p_interaction  F_interaction  conflict|conflict  conflict|training  pretraining|conflict  pretraining|training  training|conflict  training|training  criterion_met
0             8     False       0.8         0.0000        23.6670             0.0728             0.0003                0.0493                0.0728            -0.0574             0.2324           True
1             8     False       1.0         0.0000        22.5233             0.0699             0.0014                0.0507                0.0754            -0.0557             0.2283           True
2             8     False       1.2         0.0000        21.2574             0.0682             0.0012                0.0521                0.0767            -0.0540             0.2231           True
3             8      True       0.8         0.0000        26.1355             0.1280             0.0101                0.0532                0.0778            -0.0792             0.2977           True
4             8      True       1.0         0.0000        24.9131             0.1124             0.0078                0.0526                0.0780            -0.0744             0.2766           True
5             8      True       1.2         0.0000        24.9243             0.1040             0.0042                0.0556                0.0797            -0.0710             0.2695           True
6            16     False       0.8         0.0000        16.3989             0.0839             0.0170                0.0925                0.1048            -0.0076             0.1935           True
7            16     False       1.0         0.0000        15.5652             0.0802             0.0185                0.0940                0.1067            -0.0061             0.1902           True
8            16     False       1.2         0.0001        14.3600             0.0769             0.0185                0.0952                0.1084            -0.0048             0.1860           True
9            16      True       0.8         0.0000        15.6497             0.1034             0.0260                0.0925                0.1104            -0.0173             0.2265           True
10           16      True       1.0         0.0001        14.0972             0.0924             0.0257                0.0941                0.1106            -0.0149             0.2184           True
11           16      True       1.2         0.0001        14.0201             0.0855             0.0238                0.0964                0.1124            -0.0136             0.2132           True

Result: Reproduced. In all twelve readings (location size, smoothing of the distance, window of 0.8 to 1.2 s) the condition by zone interaction has p ≤ 0.0001 and the ordering holds: in training ΔIpos before approaches to the training zone is 0.23 bits against -0.056 for the conflict zone, and in conflict 0.070 for the conflict zone against 0.0014 for the training zone (main reading).

fig4d-room-maps-uncorrelated¶

Maps of the proportion of time in the room-dominant state in training and in conflict were not correlated.

In [49]:
for blk in [8, 16]:
    maps = {}
    for c in ["training", "conflict"]:
        per_mouse = []
        for mo in SESS:
            num = np.zeros(H.NBIN * H.NBIN); den = np.zeros(H.NBIN * H.NBIN)
            for s in [s for s in AV if AV[s]["meta"]["mouse"] == mo and cond_of(s) == c]:
                d = IP[blk][s]["d"]; ok = np.isfinite(d)
                loc = ((BINS[s]["ry"] // H.BIN_PX) * H.NBIN + BINS[s]["rx"] // H.BIN_PX).astype(int)
                np.add.at(num, loc[ok], (d[ok] > 0).astype(float)); np.add.at(den, loc[ok], 1.0)
            if den.sum():
                with np.errstate(invalid="ignore"):
                    per_mouse.append(np.where(den > 0, num / den, np.nan))
        maps[c] = np.nanmean(np.array(per_mouse), axis=0)
    ok = np.isfinite(maps["training"]) & np.isfinite(maps["conflict"])
    r_, p_ = stats.pearsonr(maps["training"][ok], maps["conflict"][ok])
    print(f"location {blk} px for dIpos: pixels visited in both {ok.sum()}; training-conflict map r = {r_:.3f}, p = {p_:.4g}; map value ranges "
          f"{np.nanmin(maps['training']):.2f}-{np.nanmax(maps['training']):.2f} and {np.nanmin(maps['conflict']):.2f}-{np.nanmax(maps['conflict']):.2f}")
location 8 px for dIpos: pixels visited in both 677; training-conflict map r = 0.068, p = 0.07587; map value ranges 0.00-1.00 and 0.00-1.00
location 16 px for dIpos: pixels visited in both 677; training-conflict map r = 0.164, p = 1.88e-05; map value ranges 0.00-1.00 and 0.00-1.00

Result: Reproduced, resting on the M6 assumption. With 8-pixel locations the training and conflict maps of room-preferring time are not correlated (r = 0.068, p = 0.076, 677 pixels); with 16-pixel locations they are (r = 0.16, p < 0.001).

fig4d-room-ipos-near-active-zone¶

Room-frame positional information near the shock zone, normalized by overall Ipos, was higher near the training zone in training and near the relocated zone in conflict than in the other conditions.

In [50]:
for blk in [8, 16]:
    for norm in ["a", "b"]:
        rows = []
        for s in AV:
            R_, A_ = IP[blk][s]["room"], IP[blk][s]["arena"]
            den = np.nanmean(R_) if norm == "a" else np.nanmean(R_ + A_)
            for zn in ZN:
                z = BINS[s]["zones"].get(zn)
                if z is None:
                    continue
                m = BINS[s]["valid"] & (z["dist"] <= 4.5)
                rows.append(dict(mouse=AV[s]["meta"]["mouse"], cond=cond_of(s), zone=zn, val=np.nanmean(R_[m]) / den))
        F4d = pd.DataFrame(rows).groupby(["mouse", "cond", "zone"]).val.mean().reset_index()
        out = []
        for zn in ZN:
            sub = F4d[F4d.zone == zn]
            tab, _ = H.mixed_terms(sub, "val ~ C(cond, Sum)", "mouse", {"condition": "cond"})
            mz = sub.groupby("cond").val.mean().round(3).to_dict()
            paper_df = {"training": 8.9, "conflict": 9.8}[zn]  # the Figure 4D legend's df
            # Fisher's LSD with the mixed model's pooled error (M12), residual df and the paper's df
            L_ = H.mixed_lsd(sub, "val", "cond", "mouse", condn)
            L_p = H.mixed_lsd(sub, "val", "cond", "mouse", condn, df_denom=paper_df)
            lsd_ = [(a, b, round(d, 3), round(p, 4), round(pp, 4)) for (a, b, d, p), pp in zip(L_[["a", "b", "diff", "p"]].values, L_p.p)]
            w = sub.pivot_table(index="mouse", columns="cond", values="val")
            pt_ = [(a, b, round(float(stats.ttest_rel(w[a], w[b], nan_policy="omit").pvalue), 4))
                   for a, b in [("training", "pretraining"), ("training", "conflict"), ("conflict", "pretraining")]]
            out.append(f"{zn} zone: F = {tab.F[0]:.2f}, p = {tab.p[0]:.4f} (df2 {tab.df2[0]:.0f}; p = {stats.f.sf(tab.F[0], 2, paper_df):.4f} with the paper's df2 {paper_df}), n = {len(sub)}, means {mz}\n"
                       f"      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): {lsd_}\n"
                       f"      variant, paired t over mice (a, b, p): {pt_}")
        print(f"location {blk} px, normalizer {norm}:"); print("   " + "\n   ".join(out))
location 8 px, normalizer a:
   training zone: F = 87.28, p = 0.0000 (df2 14; p = 0.0000 with the paper's df2 8.9), n = 17, means {'conflict': 0.968, 'pretraining': 1.018, 'training': 1.898}
      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): [('pretraining', 'training', -0.879, 0.0, 0.0), ('pretraining', 'conflict', 0.051, 0.5415, 0.5472), ('training', 'conflict', 0.931, 0.0, 0.0)]
      variant, paired t over mice (a, b, p): [('training', 'pretraining', 0.0), ('training', 'conflict', 0.0013), ('conflict', 'pretraining', 0.559)]
   conflict zone: F = 4.66, p = 0.0281 (df2 14; p = 0.0378 with the paper's df2 9.8), n = 17, means {'conflict': 1.461, 'pretraining': 0.939, 'training': 0.85}
      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): [('pretraining', 'training', 0.089, 0.6665, 0.6693), ('pretraining', 'conflict', -0.523, 0.028, 0.0347), ('training', 'conflict', -0.612, 0.0124, 0.017)]
      variant, paired t over mice (a, b, p): [('training', 'pretraining', 0.2118), ('training', 'conflict', 0.0917), ('conflict', 'pretraining', 0.1483)]
location 8 px, normalizer b:
   training zone: F = 85.62, p = 0.0000 (df2 14; p = 0.0000 with the paper's df2 8.9), n = 17, means {'conflict': 0.487, 'pretraining': 0.539, 'training': 0.954}
      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): [('pretraining', 'training', -0.415, 0.0, 0.0), ('pretraining', 'conflict', 0.052, 0.2154, 0.227), ('training', 'conflict', 0.467, 0.0, 0.0)]
      variant, paired t over mice (a, b, p): [('training', 'pretraining', 0.0001), ('training', 'conflict', 0.0009), ('conflict', 'pretraining', 0.2368)]
   conflict zone: F = 4.78, p = 0.0262 (df2 14; p = 0.0356 with the paper's df2 9.8), n = 17, means {'conflict': 0.735, 'pretraining': 0.5, 'training': 0.429}
      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): [('pretraining', 'training', 0.071, 0.4764, 0.4815), ('pretraining', 'conflict', -0.235, 0.0373, 0.0447), ('training', 'conflict', -0.306, 0.0097, 0.0138)]
      variant, paired t over mice (a, b, p): [('training', 'pretraining', 0.0984), ('training', 'conflict', 0.0768), ('conflict', 'pretraining', 0.1729)]
location 16 px, normalizer a:
   training zone: F = 54.17, p = 0.0000 (df2 14; p = 0.0000 with the paper's df2 8.9), n = 17, means {'conflict': 0.978, 'pretraining': 1.009, 'training': 1.757}
      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): [('pretraining', 'training', -0.748, 0.0, 0.0), ('pretraining', 'conflict', 0.035, 0.6988, 0.7022), ('training', 'conflict', 0.783, 0.0, 0.0)]
      variant, paired t over mice (a, b, p): [('training', 'pretraining', 0.0001), ('training', 'conflict', 0.0027), ('conflict', 'pretraining', 0.5952)]
   conflict zone: F = 5.34, p = 0.0189 (df2 14; p = 0.0270 with the paper's df2 9.8), n = 17, means {'conflict': 1.36, 'pretraining': 0.939, 'training': 0.863}
      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): [('pretraining', 'training', 0.077, 0.6261, 0.6294), ('pretraining', 'conflict', -0.422, 0.0207, 0.0265), ('training', 'conflict', -0.499, 0.0081, 0.0119)]
      variant, paired t over mice (a, b, p): [('training', 'pretraining', 0.1458), ('training', 'conflict', 0.0756), ('conflict', 'pretraining', 0.1296)]
location 16 px, normalizer b:
   training zone: F = 40.93, p = 0.0000 (df2 14; p = 0.0000 with the paper's df2 8.9), n = 17, means {'conflict': 0.509, 'pretraining': 0.566, 'training': 0.927}
      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): [('pretraining', 'training', -0.361, 0.0, 0.0), ('pretraining', 'conflict', 0.057, 0.2861, 0.2965), ('training', 'conflict', 0.418, 0.0, 0.0)]
      variant, paired t over mice (a, b, p): [('training', 'pretraining', 0.002), ('training', 'conflict', 0.0019), ('conflict', 'pretraining', 0.1246)]
   conflict zone: F = 4.80, p = 0.0258 (df2 14; p = 0.0352 with the paper's df2 9.8), n = 17, means {'conflict': 0.711, 'pretraining': 0.531, 'training': 0.459}
      LSD, mixed-model pooled error (a, b, mean a-b, p residual df, p paper df): [('pretraining', 'training', 0.072, 0.3769, 0.3833), ('pretraining', 'conflict', -0.183, 0.0468, 0.0548), ('training', 'conflict', -0.255, 0.0088, 0.0127)]
      variant, paired t over mice (a, b, p): [('training', 'pretraining', 0.0784), ('training', 'conflict', 0.0601), ('conflict', 'pretraining', 0.1998)]

Result: Reproduced. Normalized room Ipos near each zone differs across conditions in every reading (8-pixel locations, room normalizer: training zone F = 87.3, p < 0.0001; conflict zone F = 4.66, p = 0.028, or p = 0.038 with the paper's df). Fisher's LSD with the mixed model's pooled error puts training highest near the training zone (1.90 against 1.02 and 0.97; p < 0.0001) and conflict highest near the conflict zone (1.46 against 0.94 and 0.85; p = 0.028 and 0.012, or 0.035 and 0.017 with the paper's df). The other readings agree. Over all four readings conflict is above pretraining with p 0.021 to 0.047 (residual df) or 0.027 to 0.055 (paper's df), and above training with p 0.008 to 0.012 or 0.012 to 0.017; the one p above 0.05 is conflict against pretraining with 16-pixel locations, the room plus arena normalizer and the paper's df (0.055). Paired t tests over the five mice, the earlier variant, do not separate conflict near the conflict zone (p 0.060 to 0.20).

Overdispersion and network consistency (Figure 5B)¶

Standardized rates z = (obs - exp)/sqrt(exp) per 5-s episode (M10), on the room-frame session rate map of the place cell, keeping episodes whose expected count exceeds the cell's average rate over 5 s and whose bins were all sampled more than 0.67 s. Episodes are (a) consecutive non-overlapping 5-s windows or (b) 5-s windows centred on each entry into a firing field (M5 reading a fields on our smoothed maps, as for the other place avoidance analyses).

In [51]:
WIN5 = None
def episodes(s, u, reading):
    v = AV[s]; p = v["pos"]; fs = p["fs"]; win = int(round(5 * fs)); n = len(p["rx"])
    rec = AR.loc[(s, u, "room")]
    if reading == "a":
        starts = np.arange(0, n - win, win)
    else:
        # fields of the adopted rule for this task: M5 (a) on our smoothed maps
        F_ = rec.fieldunion_ta
        if F_ is None:
            return np.array([]), np.array([], int), win
        bx = np.clip(p["rx"] // H.BIN_PX, 0, H.NBIN - 1); by = np.clip(p["ry"] // H.BIN_PX, 0, H.NBIN - 1)
        inF = F_[by, bx] & H.tracked(p["rx"], p["ry"])
        ent = np.where(inF[1:] & ~inF[:-1])[0] + 1
        starts = ent - win // 2; starts = starts[(starts >= 0) & (starts + win < n)]
    rmap_full = H.rate_map(rec.spk, rec.occ, 0.0)
    z, st = H.standardized_rates(v["units"][u]["spike_sample"], p["rx"], p["ry"], fs, rmap_full, rec.rate, rec.occ, starts, win)
    return z, st, win

ZR = {}
for r in "ab":
    rows = []
    for s, v in AV.items():
        for u, d in v["units"].items():
            if d["cls"] != "pc":
                continue
            z, st, win = episodes(s, u, r)
            for zi, si in zip(z, st):
                rows.append(dict(session=s, mouse=v["meta"]["mouse"], cond=cond_of(s), cell=u, z=zi, start=si, win=win))
    ZR[r] = pd.DataFrame(rows)
    print(f"episode reading {r}: passes per condition", ZR[r].groupby("cond").size().to_dict(), "(paper: 9152 in all)")
episode reading a: passes per condition {'conflict': 1656, 'pretraining': 2465, 'training': 3618} (paper: 9152 in all)
episode reading b: passes per condition {'conflict': 512, 'pretraining': 2482, 'training': 2715} (paper: 9152 in all)

standardized-rates-no-difference¶

The distributions of standardized firing rates during field passes did not differ across pretraining, training and conflict.

In [52]:
for r in "ab":
    Z = ZR[r]; a = H.anova1([Z[Z.cond == c].z for c in condn])
    print(f"reading {r}: n = {a['n']}, means {np.round(a['means'], 3).tolist()}; one-way ANOVA F{a['df']} = {a['F']:.2f}, p = {a['p']:.4f}; KW p = {a['kw_p']:.4f}")
reading a: n = [2465, 3618, 1656], means [-0.076, -0.014, 0.089]; one-way ANOVA F(2, 7736) = 2.51, p = 0.0815; KW p = 0.1048
reading b: n = [2482, 2715, 512], means [-0.134, -0.039, 0.096]; one-way ANOVA F(2, 5706) = 2.34, p = 0.0966; KW p = 0.0741

Result: Reproduced. With consecutive 5-s episodes the standardized rates do not differ across conditions (F(2, 7736) = 2.51, p = 0.082), nor with 5-s windows centred on field entries, on fields of our smoothed maps (F(2, 5706) = 2.34, p = 0.097; 512 conflict passes).

overdispersion-similar¶

Overdispersion of standardized rates in pretraining (variance 5.2) was similar to that in training (5.74) and conflict (5.63), also with single cells as the unit.

In [53]:
for r in "ab":
    Z = ZR[r]; v = {c: Z[Z.cond == c].z.var(ddof=1) for c in condn}; n = {c: (Z.cond == c).sum() for c in condn}
    txt = []
    for c in ["training", "conflict"]:
        F = v[c] / v["pretraining"]; d1, d2 = n[c] - 1, n["pretraining"] - 1
        p2 = 2 * min(stats.f.sf(F, d1, d2), stats.f.cdf(F, d1, d2))
        txt.append(f"{c} vs pretraining F({d1}, {d2}) = {F:.2f}, two-sided p = {p2:.4f}")
    pc_ = Z.groupby(["cell", "cond"]).z.agg(["var", "size"]).reset_index(); pc_ = pc_[pc_["size"] >= 15]
    a = H.anova1([pc_[pc_.cond == c]["var"] for c in condn])
    print(f"reading {r}: variances {dict((k, round(x, 2)) for k, x in v.items())}, n {n}; " + "; ".join(txt))
    print(f"   per cell (>= 15 passes): n = {a['n']}, mean variance {np.round(a['means'], 2).tolist()}, F{a['df']} = {a['F']:.2f}, p = {a['p']:.4f}")
print("expected variances 5.2 +/- 0.52, 5.74 +/- 0.57, 5.63 +/- 0.56")
reading a: variances {'pretraining': np.float64(5.28), 'training': np.float64(5.34), 'conflict': np.float64(5.72)}, n {'pretraining': np.int64(2465), 'training': np.int64(3618), 'conflict': np.int64(1656)}; training vs pretraining F(3617, 2464) = 1.01, two-sided p = 0.7728; conflict vs pretraining F(1655, 2464) = 1.08, two-sided p = 0.0779
   per cell (>= 15 passes): n = [42, 41, 34], mean variance [5.35, 5.39, 5.16], F(2, 114) = 0.03, p = 0.9723
reading b: variances {'pretraining': np.float64(5.73), 'training': np.float64(5.78), 'conflict': np.float64(5.4)}, n {'pretraining': np.int64(2482), 'training': np.int64(2715), 'conflict': np.int64(512)}; training vs pretraining F(2714, 2481) = 1.01, two-sided p = 0.8190; conflict vs pretraining F(511, 2481) = 0.94, two-sided p = 0.3943
   per cell (>= 15 passes): n = [27, 21, 6], mean variance [5.83, 5.43, 6.51], F(2, 51) = 0.15, p = 0.8598
expected variances 5.2 +/- 0.52, 5.74 +/- 0.57, 5.63 +/- 0.56

Result: Reproduced, resting on the M10 assumption. With consecutive 5-s episodes the variances of z are 5.28, 5.34 and 5.72, all within tolerance of 5.2, 5.74 and 5.63; the F tests against pretraining give p = 0.77 and 0.078, and the per-cell ANOVA p = 0.97. With field-entry windows, reading (b), the variances are 5.73, 5.78 and 5.40, the first just outside 5.2 ± 0.52, and no test is significant (p = 0.82, 0.39 and 0.86).

network-consistency-overall and fig5b-network-consistency-zones¶

Overall network consistency of place cell pairs was positive and similar across pretraining, training and conflict. Network consistency rose opposite the shock zone after training and fell in that location when the shock was relocated there, giving a zone by manipulation interaction.

NC = z1 z2 tau12 for a pass of both cells of a place cell pair, with tau12 the pair's 133-ms tau over the session. Readings of "overlapping": (a) the same 5-s episode passes both cells' rules (episode reading a); (b) the two cells' fields (M5 a, on our smoothed maps) share a bin, on the same episodes. Zone passes: episodes with at least 3 s within 6 cm of a zone or in it.

In [54]:
def nc_table(fields_overlap):
    Z = ZR["a"]; rows = []
    fieldsets = {}
    for (s, u), g in Z.groupby(["session", "cell"]):
        pass
    for s, v in AV.items():
        mo = v["meta"]["mouse"]; Zs = Z[Z.session == s]
        byc = {u: g.set_index("start").z for u, g in Zs.groupby("cell")}
        fs = v["pos"]["fs"]; win = int(round(5 * fs))
        zone_near = {}
        for zn in ZN:
            if ZONES[mo][zn] is not None:
                d = DIST[(s, zn)]
                zone_near[zn] = (d <= 6.0) & H.tracked(v["pos"]["rx"], v["pos"]["ry"])
        for pr in pairs_of(mo, "pc-pc"):
            if pr[0] not in byc or pr[1] not in byc:
                continue
            if fields_overlap:
                # fields of the adopted rule for this task: M5 (a) on our smoothed maps
                f1 = AR.loc[(s, pr[0], "room")].fieldunion_ta; f2 = AR.loc[(s, pr[1], "room")].fieldunion_ta
                if f1 is None or f2 is None or not (f1 & f2).any():
                    continue
            common = byc[pr[0]].index.intersection(byc[pr[1]].index)
            if len(common) == 0:
                continue
            tau = tau_of(133, s, pr)[0]
            for st in common:
                row = dict(session=s, mouse=mo, cond=cond_of(s), pair=pr, nc=byc[pr[0]][st] * byc[pr[1]][st] * tau)
                for zn, m in zone_near.items():
                    row[f"near_{zn}"] = m[st:st + win].sum() / fs >= 3.0
                rows.append(row)
    return pd.DataFrame(rows)

NC = {r: nc_table(r == "b") for r in "ab"}
for r in "ab":
    print(f"overlap reading {r}: pass values per condition", NC[r].groupby("cond").size().to_dict(), "(paper: 2526 in all)")
overlap reading a: pass values per condition {'conflict': 1912, 'pretraining': 2914, 'training': 4253} (paper: 2526 in all)
overlap reading b: pass values per condition {'conflict': 359, 'pretraining': 696, 'training': 840} (paper: 2526 in all)
In [55]:
for r in "ab":
    N_ = NC[r]; a = H.anova1([N_[N_.cond == c].nc for c in condn])
    print(f"reading {r}: n = {a['n']}, mean NC {np.round(a['means'], 4).tolist()}, SEM {[round(N_[N_.cond == c].nc.sem(), 4) for c in condn]}; F{a['df']} = {a['F']:.2f}, p = {a['p']:.4f}")
reading a: n = [2914, 4253, 1912], mean NC [0.0421, 0.0541, 0.0611], SEM [np.float64(0.0067), np.float64(0.0076), np.float64(0.0202)]; F(2, 9076) = 0.72, p = 0.4889
reading b: n = [696, 840, 359], mean NC [0.0691, 0.129, 0.2337], SEM [np.float64(0.0215), np.float64(0.0269), np.float64(0.1025)]; F(2, 1892) = 2.91, p = 0.0545

Result: Reproduced. Under reading (a) mean NC is positive in every condition (0.042, 0.054, 0.061) and does not differ (F(2, 9076) = 0.72, p = 0.49), on 9079 pass values against the paper's 2526. Reading (b), fields of our smoothed maps sharing a bin, gives 1895 values, means 0.069, 0.129 and 0.234 and p = 0.055, the same outcome.

In [56]:
for r in "ab":
    N_ = NC[r]; rows = []
    for zn in ZN:
        sub = N_[N_.get(f"near_{zn}", False) == True]
        rows.append(sub.assign(zone=zn)[["cond", "zone", "nc"]])
    NZ = pd.concat(rows)
    t, _ = H.anova2(NZ, "nc", "zone", "cond")
    print(f"reading {r}: n = {len(NZ)} (paper df 1038 imply 1044)"); print(t.round(4).to_string())
    print(NZ.groupby(["zone", "cond"]).nc.agg(["mean", "sem", "size"]).round(4).to_string())
    for zn in ZN:
        g = [NZ[(NZ.zone == zn) & (NZ.cond == c)].nc for c in condn]
        print(f"   {zn} zone LSD:", H.lsd(g, condn)[["a", "b", "diff", "p"]].round(4).values.tolist())
reading a: n = 6090 (paper df 1038 imply 1044)
                sum_sq      df       F  PR(>F)
zone            0.0921     1.0  0.2911  0.5896
cond            0.0938     2.0  0.1482  0.8622
zone x cond     0.4670     2.0  0.7384  0.4779
Residual     1924.1542  6084.0     NaN     NaN
                        mean     sem  size
zone     cond                             
conflict conflict     0.0093  0.0076   516
         pretraining  0.0408  0.0124   966
         training     0.0575  0.0089  2869
training conflict     0.0595  0.0449   719
         pretraining  0.0416  0.0088   977
         training     0.0581  0.0282    43
   training zone LSD: [['pretraining', 'training', -0.0165, 0.8951], ['pretraining', 'conflict', -0.0179, 0.6505], ['training', 'conflict', -0.0014, 0.9912]]
   conflict zone LSD: [['pretraining', 'training', -0.0167, 0.2966], ['pretraining', 'conflict', 0.0315, 0.1798], ['training', 'conflict', 0.0482, 0.0192]]
reading b: n = 1191 (paper df 1038 imply 1044)
                sum_sq      df       F  PR(>F)
zone            0.4266     1.0  0.3578  0.5498
cond            0.4413     2.0  0.1851  0.8311
zone x cond     4.7583     2.0  1.9957  0.1364
Residual     1412.7024  1185.0     NaN     NaN
                        mean     sem  size
zone     cond                             
conflict conflict     0.0130  0.0315    97
         pretraining  0.1442  0.0800   115
         training     0.1466  0.0333   531
training conflict     0.3084  0.2512   125
         pretraining  0.0634  0.0174   308
         training     0.1373  0.0771    15
   training zone LSD: [['pretraining', 'training', -0.074, 0.8526], ['pretraining', 'conflict', -0.2451, 0.1253], ['training', 'conflict', -0.1711, 0.6776]]
   conflict zone LSD: [['pretraining', 'training', -0.0023, 0.9755], ['pretraining', 'conflict', 0.1312, 0.1987], ['training', 'conflict', 0.1336, 0.1025]]

Result: Not reproduced. The zone by condition interaction is p = 0.48 (reading (a)) and p = 0.14 (reading (b)), against p = 0.04. Near the conflict zone NC is 0.041, 0.058 and 0.009 in pretraining, training and conflict under reading (a), the fall from training to conflict being significant (p = 0.019), but the rise from pretraining to training is not (p = 0.30).

Optogenetic experiments (Figure 2)¶

fig2c-cfos-reduced, fig2d-conflict-deficit, fig2-quadrant-preference and fig2e-shock-off-deficit need the POMC-Halorhodopsin Cre+ and Cre- mice: their cFos counts and their place avoidance behaviour. The data set holds wild-type recordings only (data descriptor: "wild-type (WT) mice"; the file list above has no other subjects), and the paper names no other deposit. These claims are blocked as data missing.

In [57]:
print("mice in the data set's files:", sorted(set(re.findall(r"WT\d+", " ".join(H.members())))))
print("files naming Cre, POMC, Halo or cFos:", [m for m in H.members() if re.search(r"cre|pomc|halo|fos", m, re.I)])
print(f"total run time {time.time() - T0:.0f} s; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
mice in the data set's files: ['WT13', 'WT15', 'WT16', 'WT1690', 'WT18', 'WT19', 'WT20', 'WT26', 'WT27']
files naming Cre, POMC, Halo or cFos: []
total run time 408 s; peak memory 0.60 GB

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
fig1-single-field-proportion not reproduced (rests on M2, M5)
fig1-field-number-scaling not reproduced (rests on M2, M5)
fig1b-stability-dg-below-ca-removal reproduced
fig1-rate-remapping-no-difference reproduced
fig1c-field-rate-change-no-difference reproduced (rests on M2, M5)
tables1-dg-ca-similar partially reproduced
fig2c-cfos-reduced blocked, data missing
fig2d-conflict-deficit blocked, data missing
fig2-quadrant-preference blocked, data missing
fig2e-shock-off-deficit blocked, data missing
fig3b-avoidance-learning not reproduced
fig3b-shock-off-avoidance not reproduced
speed-no-difference reproduced (rests on the session reading)
tables2-firing-quality-similar not reproduced
fig3c-stability-no-difference reproduced (rests on M11)
fig3c-replication-vs-relocation reproduced (rests on M11)
fig3c-stability-vs-environment reproduced
fig3d-rate-remapping-task partially reproduced (rests on M11, M2, M5)
interneuron-rate-remapping not reproduced
ipos-speed-correlation not reproduced
fig4b-room-preference-pretraining reproduced (rests on M6)
fig4c-ipos-before-avoidance reproduced
fig4d-room-maps-uncorrelated reproduced (rests on M6)
fig4d-room-ipos-near-active-zone reproduced
figs2a-pc-pairs-no-change reproduced
standardized-rates-no-difference reproduced
overdispersion-similar reproduced (rests on M10)
network-consistency-overall reproduced
fig5b-network-consistency-zones not reproduced
fig5d1-pc-int-tau-no-difference reproduced
fig5d2-pc-int-change-relocation reproduced (rests on M11)
pc-int-fraction-increased partially reproduced
figs2bc-other-timescales reproduced (rests on M11)
pc-int-pair-classes not reproduced
fig5d3-independent-pairs-increase reproduced (rests on the class reading, M11)
fig5d4-positive-pairs-decrease reproduced (rests on the class reading, M11)
negative-pairs-no-change not reproduced
fig5e1-correlation-near-zone not reproduced
fig5e2-e4-change-near-zone not reproduced
correlation-not-speed reproduced (acceleration p = 0.05004)
fig5e1-inset-rate-change-near-zone not reproduced
fig6b-correlation-before-avoidance not reproduced
fig6c-no-increase-before-errors reproduced
fig6-inset-rate-changes reproduced (rests on M11)

How the analysis differs from the paper's:

  • Rate maps are on the data set's 32 x 32 grid. The paper does not say whether its maps were smoothed. Place fields (the claims file's M5 rule, 20% of peak or 1 AP/s, at least 9 contiguous bins, not the paper's, which it does not state) are found on smoothed maps: the data set's own smoothed maps (RmSm) in the environment experiment, whose kernel is not described but acts like a sum over about 2 x 2 bins, and our 3 x 3 smoothing in the place avoidance task. On the unsmoothed maps of the first round many cells had no field; on the smoothed maps few have none, and three of the four field means of Figure 1 are within tolerance, but the single-field share of CA cells and the field count of removed DG cells are still below the paper's.
  • Fisher's LSD after a mixed model uses the model's pooled error (the environment field counts and fig4d); for the field counts paired and unpaired t tests are shown beside it.
  • The mixed models are statsmodels' linear mixed models with Wald F tests; their denominator df are not JMP's Kenward-Roger df. Where it matters, p is also given with the paper's df (fig4b, fig4d).
  • Shock-off errors are counted from positions, as their Tracker files hold no zone; the zone is the one of the shock-on session before. A count with an entrance only after 100 ms outside matches the Tracker on shock-on files (median ratio 1.00) and gives the same outcomes.
  • The sessions the data set lacks (a second pretraining session for WT15, WT16 and WT19, the training 1 recording of WT16) leave 115 place cell values over the three manipulations (37, 42 and 36) against the paper's 120 and 142 place cell-interneuron replication changes against 152.

What was found about the data set:

  • The paper's cell lists are in the data set and match the paper's counts (45 DG and 20 CA place cells in the environment experiment; 42 DG place cells and 21 interneurons in 6 mice in the place avoidance task, 36 and 18 in the conflict session).
  • The environment session 140731_WT15_testbox2 has the same position series as 140731_WT15_testbox1, and two of its four listed units the same spike trains; it is counted once.
  • The Tracker files of the shock-off recordings of WT15 (after training 1 and 2) and WT16 (after training 2 and conflict) log shocks (1 to 33) and a shock zone, where the paper says recordings were made with the shock off; the WT15 training 2 recording is also deposited among the shock-on files.
  • For WT15, WT16 and WT19 the conflict zone is 170 degrees from the training zone (305 against 135), where the paper says 180.
  • The clock check (split-half map correlation, aligned against positions shifted by 60 s) passes in 80 of 82 sessions; in 140731_WT15_testbox1 and 140803_WT16_rotated90dcircleintestbox2 the listed cells have no stable map within the session, so a shared clock could not be shown there.
  • The data descriptor says the Spike and Time maps are 256 x 256; they hold 1024 values, a 32 x 32 grid, except the place avoidance maps of WT15Hab1, WT16Hab1, 150720_WT19Ini1_2 and 150720_WT19Conf1_2, which are 41 x 41. Our spike-count maps match the deposited plain maps closely (median r 0.988 and 0.985) but not exactly. The smoothed maps are not described. The WT19 pretraining session lasts 30 min, where the paper says 20.
  • 140731_WT15_testbox1 and testbox2 have the same positions, and three of four listed units' spike trains start with the same spike times, with different FIRST_TIMESTAMP values and spike counts in two of four units: two sortings of one recording, it appears.
  • WT15's only training 2 Tracker file is 20 min long, where training 2 lasted 10 min, and holds one entrance.