Reproducing Park et al. (2019) from CRCNS hc-20¶

Paper. Park EH, Keeley S, Savin C, Ranck JB Jr, Fenton AA (2019). How the internally organized direction sense is used to navigate. Neuron 101:285-293. doi:10.1016/j.neuron.2018.11.019. The claims file (claims/park-2019.yaml) was written from the version of record with its STAR Methods and Supplemental Information, and from the paper's code (https://github.com/FentonLab/PyCode_MEC_HDC-NeuronMS_Park at commit 545a738).

Data set. CRCNS hc-20, doi:10.6080/K0SF2TDN, the file hc-20/live/data.zip in the public S3 bucket crcnsarchive, streamed and opened in place. CRCNS data sets are not versioned, and the paper cites the data set's DOI only, so the version pinned is the one published now, recorded as unversioned with the MD5 sum of data.zip from the data set's checksums.md5 (b82c7b97b0ba3491f04ecc4dbcd48e83); the setup cell below checks it against the published file, so a later change is detectable. There is no other version to choose between. The data descriptor is version 0.6 (14 Nov 2018).

What the data set holds. The spike trains and 30 Hz tracking of the 115 head-direction cells in the three trials (stable1, rotating in room and arena coordinates, stable2), a file list that matches units across trials, and the tracker's files of each trial. It holds no other MEC units, no LFP, no waveforms and no training sessions.

Claim Tested here
cell-counts tested
hd-cell-rate tested
fig1a-avoidance-learning blocked, data missing (training sessions not deposited)
fig1c-speed tested
fig1c-lfp-power blocked, data missing (no LFP)
fig1c-firing-rate tested
fig1c-directionality tested
fig1d-preference-change tested
fig1d-instability tested
fig2-decoding-stable-vs-rotating tested
figs2-frame-preference tested
fig2c-proximity-anticorrelation tested
figs3-no-head-direction-bias tested
fig3-hd-pair-correlations-preserved tested
figs4-all-pair-correlations-preserved blocked, data missing (only head-direction cells deposited)
figs5-hd-cells-high-model-information blocked, data missing (the 921 modelled cells are not deposited)
figs6-subclass-correlations-preserved blocked, data missing (as figs5)
no-angular-velocity-tuning tested
fig4-internal-tuning-preserved tested
fig4c-arena-registration-short-lived tested
fig5-error-inhomogeneous tested
fig5c-error-minima-at-cues tested
In [1]:
import time
import warnings

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

import hd20

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

sums = hd20.checksums()
print("checksums.md5 of hc-20/live:", sums)
print("data.zip MD5 as pinned:", hd20.DATA_ZIP_MD5, "; as published now:", sums["data.zip"],
      "; same:", sums["data.zip"] == hd20.DATA_ZIP_MD5)
units, data = hd20.load_units()
print(f"loaded {len(units)} units x {len(hd20.TRIALS)} trials from {hd20.DATASET} ({hd20.DATASET_VERSION}) "
      f"in {time.time() - started:.0f} s")
TR = hd20.TRIALS
U = list(units.unit)
SESS = units.groupby("session").unit.apply(list).to_dict()
checksums.md5 of hc-20/live: {'data.zip': 'b82c7b97b0ba3491f04ecc4dbcd48e83', 'docs/crcns_hc-20_data_description.docx': '90b41abf832396c64af0c5b6f466e00e', 'docs/crcns_hc-20_data_description.pdf': '7ecbeeecda020adfbd2ba3fc928a0f83', 'filelist.txt': '8aea19e312b8fcefb1d26e445b62c295'}
data.zip MD5 as pinned: b82c7b97b0ba3491f04ecc4dbcd48e83 ; as published now: b82c7b97b0ba3491f04ecc4dbcd48e83 ; same: True
/home/runner/work/encore/encore/executed/park-2019/.venv/lib/python3.13/site-packages/openpyxl/worksheet/_reader.py:329: UserWarning: Unknown extension is not supported and will be removed
  warn(msg)
loaded 115 units x 4 trials from CRCNS hc-20 (unversioned) in 99 s

Data check¶

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

In [2]:
rows = []
for u in U:
    for tr in TR:
        x = data[u][tr]
        ok = x["d"] <= 360
        rows.append({"unit": u, "trial": tr, "fs_header": x["fs_header"], "fs": x["fs"], "samples": len(x["d"]),
                     "duration_s": len(x["d"]) / x["fs"], "spikes": int(x["n"].sum()),
                     "untracked_dir": 1 - ok.mean(), "xy_zero": np.mean((x["x"] == 0) & (x["y"] == 0)),
                     "dir_min": x["d"][ok].min(), "dir_max": x["d"][ok].max(),
                     "x_max": x["x"].max(), "y_max": x["y"].max(), "max_spk_per_sample": x["n"].max(),
                     "spikes_sorted": bool(np.all(np.diff(x["spike_t"]) >= 0)), "trailing_bytes": x["trailing"]})
survey = pd.DataFrame(rows)
TRIALDUR = survey.set_index(["unit", "trial"]).duration_s
print("Units:", len(U), "; sessions (date and rat):", units.session.nunique(), "; rats:", units.rat.nunique())
print("\nUnits per rat:")
print(units.groupby("rat").agg(units=("unit", "size"), sessions=("session", "nunique")).T.to_string())
print("\nPer trial, over units:")
print(survey.groupby("trial")[["fs", "samples", "duration_s", "spikes", "untracked_dir", "xy_zero", "dir_min",
                                "dir_max", "x_max", "y_max", "max_spk_per_sample"]]
      .agg(["min", "median", "max"]).T.round(3).to_string())
print("\nHeaders with a sampling rate other than about 30 Hz:")
print(survey[survey.fs_header > 100][["unit", "trial", "fs_header", "fs", "samples"]].to_string(index=False))
print("\nFiles shorter than 29 min:")
print(survey[survey.duration_s < 29 * 60][["unit", "trial", "samples", "duration_s", "spikes"]].to_string(index=False))
print("\nFiles whose spike times are not in order:")
for _, r in survey[~survey.spikes_sorted].iterrows():
    dd = np.diff(data[r.unit][r.trial]["spike_t"])
    print(f"  {r.unit} {r.trial}: {int((dd < 0).sum())} decreasing step(s) of {dd.min() / 10:.1f} ms in {len(dd) + 1} spikes")
print("\nTrailing bytes after the last whole sample in any file:", int(survey.trailing_bytes.max()))
print("Samples with more than 15 spikes (in 33 ms):")
for u in U:
    for tr in ["SA1", "RA_rm", "SA2"]:
        n = data[u][tr]["n"]
        if n.max() > 15:
            print(f"  {u} {tr}: {int((n > 15).sum())} samples, max {n.max()}")
Units: 115 ; sessions (date and rat): 44 ; rats: 13

Units per rat:
rat       R024  R027  R029  R035  R039  R084  R130  R157  R176  R357  R521  R523  R848
units        5     3    40    17     6     2     1    25     1     8     3     2     2
sessions     3     1    12     9     3     1     1     6     1     3     2     1     1

Per trial, over units:
trial                          RA_ar      RA_rm        SA1        SA2
fs                 min        30.021     30.021     30.021     30.008
                   median     30.022     30.022     30.022     30.022
                   max        30.022     30.022     30.023     30.022
samples            min     53982.000  53982.000  53990.000  26954.000
                   median  54002.000  54002.000  54002.000  54002.000
                   max     54664.000  54664.000  54346.000  54294.000
duration_s         min      1798.086   1798.086   1798.326    897.797
                   median   1798.726   1798.726   1798.726   1798.726
                   max      1820.803   1820.803   1810.211   1808.479
spikes             min         8.000      8.000     35.000      3.000
                   median    962.000    962.000   1201.000   1009.000
                   max     72207.000  72207.000  24765.000  23764.000
untracked_dir      min         0.068      0.060      0.079      0.043
                   median      0.178      0.167      0.175      0.149
                   max         0.394      0.386      0.722      0.734
xy_zero            min         0.030      0.018      0.007      0.001
                   median      0.060      0.048      0.026      0.022
                   max         0.181      0.125      0.139      0.159
dir_min            min         0.000      0.000      0.000      0.000
                   median      0.000      0.000      0.000      0.000
                   max         0.000      0.000      0.000      0.000
dir_max            min       357.000    356.000    356.000    356.000
                   median    357.000    357.000    357.000    357.000
                   max       359.000    359.000    357.000    358.000
x_max              min       248.000    245.000    252.000    194.000
                   median    250.000    248.000    255.000    255.000
                   max       251.000    248.000    255.000    255.000
y_max              min       244.000    248.000    251.000    240.000
                   median    249.000    249.000    252.000    252.000
                   max       251.000    249.000    255.000    255.000
max_spk_per_sample min         1.000      1.000      1.000      1.000
                   median      3.000      3.000      3.000      3.000
                   max        21.000     21.000     62.000     13.000

Headers with a sampling rate other than about 30 Hz:
          unit trial  fs_header      fs  samples
1017R035-P11C2   SA2     2000.0 30.0219    54185

Files shorter than 29 min:
          unit trial  samples  duration_s  spikes
1121R157-P11C2   SA2    26954  897.797299      56

Files whose spike times are not in order:
  1020R157-P11C1 RA_rm: 1 decreasing step(s) of -1.5 ms in 4507 spikes
  1020R157-P11C1 RA_ar: 1 decreasing step(s) of -1.5 ms in 4507 spikes

Trailing bytes after the last whole sample in any file: 0
Samples with more than 15 spikes (in 33 ms):
  1006R035-P11C3 SA1: 1 samples, max 62
  1020R157-P11C2 SA1: 7 samples, max 23
  1020R157-P11C2 RA_rm: 7 samples, max 19
  1024R357-P9C2 RA_rm: 1 samples, max 16
  1026R157-P11C2 SA1: 2 samples, max 32
  1026R157-P11C2 RA_rm: 1 samples, max 18
  1026R157-P11C3 RA_rm: 3 samples, max 21

The data descriptor says the TSD files sample position and direction at 30 Hz, with times in 100 us units and directions in degrees; the headers give 30.008 to 30.023 samples/s, and 30 min trials hold about 54,000 samples (1798 s), consistent with it. One header (1017R035-P11C2, stable2) states 2000 samples/s and a first timestamp of 5; the file holds 54,185 samples, a 30 min trial at 30 Hz, so its rate is taken as 30 Hz. Directions run from 0 to 359 degrees; directions above 360 (4294967295, that is -1) mark samples without a direction, 4 to 73% of a file's samples, which the descriptor does not mention. Positions are pixels from 0 to 255; x = y = 0 marks lost positions. The rotating trial's room and arena files of a unit hold the same spikes (checked below).

In [3]:
fl = units[["unit", "session"] + [f"listed_{t}" for t in TR] + [f"file_{t}" for t in TR]]
mism = fl[fl[[f"listed_{t}" for t in TR]].to_numpy() != fl[[f"file_{t}" for t in TR]].to_numpy()].dropna(how="all")
shifted = units[units.listed_SA2 != units.file_SA2]
print("Rows of FileNameList.xlsx whose files are not all the same tetrode and cluster:")
print(shifted[["unit", "file_SA1", "listed_SA2", "file_SA2"]].to_string(index=False))
print("\nSpike counts of these units (by file name) in each trial, and of the SA2 file the list gives:")
for _, r in shifted.iterrows():
    listed = [k for k in U if units.set_index("unit").loc[k, "file_SA2"] == r.listed_SA2][0]
    print(f"  {r.unit}: SA1 {data[r.unit]['SA1']['n'].sum()}, RA {data[r.unit]['RA_rm']['n'].sum()}, "
          f"SA2 by name {data[r.unit]['SA2']['n'].sum()}, SA2 as listed {data[listed]['SA2']['n'].sum()}")
print("\nRoom and arena files of the rotating trial hold the same spikes for every unit:",
      all(np.array_equal(data[u]["RA_rm"]["n"], data[u]["RA_ar"]["n"]) for u in U))
same = []
for s, us in SESS.items():
    for tr in TR:
        ref = data[us[0]][tr]
        for u in us[1:]:
            same.append(np.array_equal(data[u][tr]["d"][:26954], ref["d"][:26954]))
print("Cells of a session share their tracking in every trial:", all(same), f"({len(same)} comparisons)")
Rows of FileNameList.xlsx whose files are not all the same tetrode and cluster:
          unit               file_SA1              listed_SA2                file_SA2
1121R157-P11C2 1121SA1R157-cl.P11C2Rm  1121SA2R157-cl.P11C3Rm 1121SA2R157-cl1.P11C2Rm
1121R157-P11C3 1121SA1R157-cl.P11C3Rm  1121SA2R157-cl.P11C4Rm  1121SA2R157-cl.P11C3Rm
1121R157-P11C4 1121SA1R157-cl.P11C4Rm   1121SA2R157-cl.P9C2Rm  1121SA2R157-cl.P11C4Rm
 1121R157-P9C2  1121SA1R157-cl.P9C2Rm   1121SA2R157-cl.P9C3Rm   1121SA2R157-cl.P9C2Rm
 1121R157-P9C3  1121SA1R157-cl.P9C3Rm 1121SA2R157-cl1.P11C2Rm   1121SA2R157-cl.P9C3Rm

Spike counts of these units (by file name) in each trial, and of the SA2 file the list gives:
  1121R157-P11C2: SA1 327, RA 52, SA2 by name 56, SA2 as listed 21567
  1121R157-P11C3: SA1 6100, RA 19758, SA2 by name 21567, SA2 as listed 4439
  1121R157-P11C4: SA1 1258, RA 2205, SA2 by name 4439, SA2 as listed 1338
  1121R157-P9C2: SA1 1504, RA 1708, SA2 by name 1338, SA2 as listed 561
  1121R157-P9C3: SA1 557, RA 467, SA2 by name 561, SA2 as listed 56

Room and arena files of the rotating trial hold the same spikes for every unit: True
Cells of a session share their tracking in every trial: True (284 comparisons)

The data descriptor says FileNameList.xlsx lists the files of one unit on one row. For session 1121R157 the stable2 column is shifted by one row against the other three for five rows (each unit's stable2 file is the next unit's), and the last of them takes the file cl1.P11C2. Units are matched by tetrode and cluster in the file names here. The stable2 file of 1121R157-P11C2 is 15 min long (26,954 samples) and its rate is taken over its own duration.

In [4]:
dup = []
first = {s: us[0] for s, us in SESS.items()}
for tr in TR:
    keys = {}
    for s, u in first.items():
        x = data[u][tr]
        keys.setdefault((x["d"][:20000].tobytes(), x["x"][:20000].tobytes()), []).append(s)
    for v in keys.values():
        if len(v) > 1:
            a, b = data[first[v[0]]][tr], data[first[v[1]]][tr]
            n = min(len(a["d"]), len(b["d"]))
            dup.append({"trial": tr, "sessions": " and ".join(v), "samples": f"{len(a['d'])} and {len(b['d'])}",
                        "direction identical": np.mean(a["d"][:n] == b["d"][:n]),
                        "x identical": np.mean(a["x"][:n] == b["x"][:n]),
                        "first timestamps": f"{a['first_ts']:.0f} and {b['first_ts']:.0f}",
                        "spike samples identical": np.mean(a["n"][:n] == b["n"][:n]) == 1})
print("Tracking (positions and directions) deposited for two different sessions:")
print(pd.DataFrame(dup).to_string(index=False))
ra_ar_same = [np.mean(data[first["1211R039"]]["RA_ar"]["d"][:54000] == data[first["1212R039"]]["RA_ar"]["d"][:54000])]
print("Arena-frame directions of the same two rotating trials identical in a fraction", round(ra_ar_same[0], 3))
spk_dup = {}
for u in U:
    for tr in ["SA1", "RA_rm", "SA2"]:
        spk_dup.setdefault(data[u][tr]["spike_t"].tobytes(), []).append((u, tr))
print("Spike trains deposited twice:", [v for v in spk_dup.values() if len(v) > 1])
DUP_TRACK = {("1015R029", "SA2"), ("1025R029", "SA2"), ("1211R039", "RA_rm"), ("1212R039", "RA_rm")}
Tracking (positions and directions) deposited for two different sessions:
trial              sessions         samples  direction identical  x identical first timestamps  spike samples identical
RA_rm 1211R039 and 1212R039 54002 and 54002                  1.0          1.0  29745 and 20270                    False
  SA2 1015R029 and 1025R029 54294 and 54002                  1.0          1.0   23185 and 9680                    False
Arena-frame directions of the same two rotating trials identical in a fraction 0.091
Spike trains deposited twice: [[('1024R157-P9C1', 'SA1'), ('1024R157-P9C1', 'RA_rm')]]

Two pairs of trials from different days share their tracking sample for sample: stable2 of 1015R029 and of 1025R029 (rat R029), and the room-frame tracking of the rotating trial of 1211R039 and 1212R039 (rat R039), whose arena-frame tracking differs. Their spike trains differ, so one trial of each pair carries another day's tracking. Which one is not known; analyses of position or direction in these trials are shown with and without the four sessions. No spike train is deposited twice.

In [5]:
import io

dats = hd20.dat_files()
z = hd20.open_zip()
zones = {}
for s in SESS:
    p = dats[(dats.session == s) & (dats.trial == "RA") & (dats.frame == "room")].path.iloc[0]
    info, _ = hd20.parse_dat(z.read(p))
    room = [float(v) for v in info["RoomTrackReinforcedSector"].split()]
    arena = [float(v) for v in (info["ArenaTrackReinforcedSector"] or info["RoomTrackReinforcedSector"]).split()]
    zones[s] = {"room": room, "arena": arena, "pix_per_cm": float(info["TrackerResolution_PixPerCM"]),
                "centre": [float(v) for v in info["ArenaCenterXY"].split()], "diam_m": float(info["ArenaDiameter_m"])}
print("Tracker files:", len(dats), "; per trial and frame:", dats.groupby(["trial", "frame"]).size().to_dict())
print("Sessions with all four tracker files:",
      int((dats.groupby("session").size() == 4).sum()), "of", dats.session.nunique(),
      "; sessions of the TSD files without tracker files:", sorted(set(SESS) - set(dats.session)))
zt = pd.DataFrame({s: {"room zone (centre, width, inner r, outer r)": " ".join(f"{v:g}" for v in z_["room"]),
                       "arena zone": " ".join(f"{v:g}" for v in z_["arena"]),
                       "pix/cm": z_["pix_per_cm"], "centre": z_["centre"], "diameter m": z_["diam_m"]}
                   for s, z_ in zones.items()}).T
print(zt.drop(columns=["centre"]).value_counts().to_string())
dat_names = {p_.split("/")[-1] for p_ in dats.path}
listed = {lst: set(pd.read_excel(io.BytesIO(z.read(f"data/DAT/{lst}")), header=None, engine="calamine")[0].astype(str).str.strip())
          for lst in ["Rotating_File_List.xls", "Stable_File_List.xls"]}
for lst, names in listed.items():
    print(f"{lst}: {len(names)} names; in the zip's DAT folder: {len(names & dat_names)}; not in the zip: {sorted(names - dat_names)}")
print("DAT files in neither list:", sorted(dat_names - set().union(*listed.values())))
Tracker files: 176 ; per trial and frame: {('RA', 'arena'): 44, ('RA', 'room'): 44, ('SA1', 'room'): 44, ('SA2', 'room'): 44}
Sessions with all four tracker files: 43 of 45 ; sessions of the TSD files without tracker files: []
room zone (centre, width, inner r, outer r)  arena zone         pix/cm  diameter m
90 45 51 127.5                               90 45 51 127.5     2.1333  1.2           31
90 30 63.75 127.5                            90 30 63.75 127.5  2.1333  1.2           13
Rotating_File_List.xls: 88 names; in the zip's DAT folder: 88; not in the zip: []
Stable_File_List.xls: 88 names; in the zip's DAT folder: 88; not in the zip: []
DAT files in neither list: []

The tracker headers give an arena of 1.2 m at 2.1333 pixels/cm centred on (127.5, 127.5), so the arena spans about 256 pixels, as the TSD positions do. The shock zone is a 30 degree sector from radius 63.75 to 127.5 pixels (50% of the radius) or a 45 degree sector from 51 to 127.5 pixels (40%), as the STAR Methods describe, centred at 90 degrees in both frames in every session. The check below finds which direction 90 degrees is in pixel coordinates, from the samples the tracker flags as inside each zone.

In [6]:
flag_ang = []
for s in list(SESS)[:44]:
    for fr, bit in [("room", 1), ("arena", 2)]:
        p = dats[(dats.session == s) & (dats.trial == "RA") & (dats.frame == fr)].path.iloc[0]
        _, df = hd20.parse_dat(z.read(p))
        m = ((df.sectors.fillna(0).astype(int) & bit) > 0) & (df.x > 0)
        if m.sum() > 10:
            a = np.angle(np.exp(1j * np.arctan2(-(df.y[m] - 127.5), df.x[m] - 127.5)).mean(), deg=True) % 360
            flag_ang.append({"session": s, "frame": fr, "flagged": int(m.sum()), "angle_y_up": a})
flag_ang = pd.DataFrame(flag_ang)
print("Angle of the samples flagged inside the zone, measured with y pointing up (degrees):")
print(flag_ang.groupby("frame").angle_y_up.describe().round(1).to_string())


def zone_xy(z_):
    """Pixel position of the centre of a sector (centre angle, width, inner, outer radius), the
    angle counted with y up, as the flagged samples show."""
    a = np.deg2rad(z_[0])
    r = (z_[2] + z_[3]) / 2
    return 127.5 + r * np.cos(a), 127.5 - r * np.sin(a)
Angle of the samples flagged inside the zone, measured with y pointing up (degrees):
       count  mean   std   min   25%   50%    75%    max
frame                                                   
arena   36.0  94.7   9.4  66.8  88.7  93.4  101.4  110.9
room    44.0  94.5  11.4  69.2  91.4  94.1  103.8  110.5

The samples flagged inside each zone lie at about 90 degrees when the angle is counted with y pointing up (pixel y grows downwards), so the zone centre is placed at (127.5, 127.5 - r) with r the zone's mid radius. This is consistent with the headers; it is not a check of the zone's exact edges.

Clock. The spikes are stored inside the tracker samples, so they share the tracking clock by construction. The check below shows that the assignment carries direction information: the directionality of the stable1 tuning curves with the spike counts as stored, and with the spike counts shifted against the tracking by 1 to 120 s.

In [7]:
shift_rows = []
for sh in [0, 1, 3, 10, 30, 120]:
    rs = []
    for u in U:
        x = data[u]["SA1"]
        k = int(round(sh * x["fs"]))
        y = dict(x)
        y["n"] = np.roll(x["n"], k)
        rs.append(hd20.resultant(hd20.tuning(y)[2])[0])
    shift_rows.append({"shift_s": sh, "median_directionality": np.median(rs), "mean": np.mean(rs)})
print(pd.DataFrame(shift_rows).round(3).to_string(index=False))
off = []
for u in U[:20]:
    x = data[u]["SA1"]
    st = x["first_ts"] + x["spike_sample"] * 1e4 / x["fs"]
    off.append((x["spike_t"] - st) / 10)
off = np.concatenate(off)
print("Spike time minus the nominal time of its sample (first timestamp + index / rate), ms, 20 units:",
      np.percentile(off, [0, 5, 50, 95, 100]).round(1))
 shift_s  median_directionality  mean
       0                  0.419 0.460
       1                  0.346 0.366
       3                  0.238 0.253
      10                  0.133 0.161
      30                  0.085 0.104
     120                  0.072 0.101
Spike time minus the nominal time of its sample (first timestamp + index / rate), ms, 20 units: [ -15.8   57.8  536.  2501.6 3337.7]

Two more problems show in the outputs above. The stable1 file of unit 1024R157-P9C1 holds the same spikes, sample for sample, as its rotating-trial files (2919 spikes), on different tracking; its stable1 spikes are very likely the rotating trial's. It is kept in the analyses as deposited (one unit of 115), and the claims that compare stable1 with other trials are not sensitive to one unit at the level of the tests. One tracker file of session 0803R027 is named for rat R024 (0803SA2R024RoomTrack...). Spike times run ahead of the nominal sample times (first timestamp plus index over rate) by up to about 3 s by the end of a trial, so the tracker samples are not exactly evenly spaced; analyses of direction use the sample each spike is stored in, and the spike-count correlations use the spike times.

cell-counts¶

The paper analyses 115 dorsal MEC head-direction cells from 13 rats, among 353 MEC cells forming 556 cell pairs (Table S1), out of 1594 MEC single units recorded.

Reading (a) counts what the data set holds; reading (b) applies the paper's head-direction criteria (stable1 mean rate below 10 AP/s, Rayleigh test of the Rayleigh vector of the 10 degree tuning curve, STAR Methods, "Quantifying Head-direction Signals, Directionality", with n the spikes behind the curve, and Kuiper's test of the spike directions against the sampled directions, each at p < 0.05; n = 36 bins and the Rayleigh test of the raw spike directions are variants). Reading (b) is circular, as the deposited units were already selected as head-direction cells; it checks that the selection holds on the deposited files. The per-rat counts are compared with Table S1 of the paper (values typed from the table as the reference).

In [8]:
TABLE_S1 = {  # Table S1: rat: (head-direction cells, MEC cells, MEC cell pairs)
    "R024": (5, 32, 116), "R027": (3, 8, 15), "R029": (41, 63, 141), "R030": (0, 9, 3), "R035": (17, 43, 73),
    "R039": (6, 16, 31), "R084": (2, 2, 1), "R130": (1, 6, 3), "R157": (25, 68, 50), "R176": (1, 2, 1),
    "R357": (8, 10, 14), "R521": (3, 53, 76), "R523": (1, 7, 1), "R848": (2, 20, 18), "R850": (0, 14, 13)}
sess_n = units.groupby("session").size()
pairs_by_rat = (sess_n * (sess_n - 1) // 2).groupby(units.groupby("session").rat.first()).sum()
cls = []
for u in U:
    x = data[u]["SA1"]
    ok = x["d"] <= 360
    spk_dirs = np.repeat(x["d"][ok].astype(float), x["n"][ok])
    # Rayleigh vector of the 10 degree tuning curve (STAR Methods, Quantifying Head-direction
    # Signals, Directionality); its z statistic with n the spikes behind the curve, and n = 36 bins
    # as a variant
    spikes, _, rate_curve = hd20.tuning(x)
    r, _ = hd20.resultant(rate_curve)
    r_spk, _ = hd20.resultant(np.ones(len(spk_dirs)), np.deg2rad(spk_dirs))
    v, pk = hd20.kuiper_two_sample(spk_dirs, x["d"][ok].astype(float))
    cls.append({"unit": u, "rate_SA1": x["n"].sum() / (len(x["d"]) / x["fs"]), "rayleigh_r": r,
                "rayleigh_p": hd20.rayleigh_p(r, spikes.sum()), "rayleigh_p_36": hd20.rayleigh_p(r, 36),
                "rayleigh_p_spikes": hd20.rayleigh_p(r_spk, len(spk_dirs)), "kuiper_V": v, "kuiper_p": pk})
cls = pd.DataFrame(cls).merge(units[["unit", "rat", "session"]])
cls["passes"] = (cls.rate_SA1 < 10) & (cls.rayleigh_p < 0.05) & (cls.kuiper_p < 0.05)
by_rat = pd.DataFrame({
    "HD cells, Table S1": {r: v[0] for r, v in TABLE_S1.items()},
    "HD units in data set": units.groupby("rat").size(),
    "pass criteria (b)": cls.groupby("rat").passes.sum(),
    "simultaneous HD pairs in data set": pairs_by_rat,
    "MEC cells, Table S1": {r: v[1] for r, v in TABLE_S1.items()},
    "MEC pairs, Table S1": {r: v[2] for r, v in TABLE_S1.items()}}).fillna(0).astype(int)
by_rat.loc["total"] = by_rat.sum()
print(by_rat.to_string())
print("\nRats with head-direction units:", units.rat.nunique())
print("Reading (a): head-direction units", len(U), "(expected 115 +/- 11.5); MEC units in the data set", len(U),
      "(expected 353, the other MEC units are not deposited); simultaneously recorded pairs", int(pairs_by_rat.sum()),
      "(all of them head-direction pairs; expected 556 MEC pairs, and 142 head-direction pairs in Figure 4)")
print("Reading (b): units passing the head-direction criteria", int(cls.passes.sum()), "of", len(cls))
print("Failing units:")
print(cls[~cls.passes].round(4).to_string(index=False))
for name, col in [("n = 36 bins", "rayleigh_p_36"), ("Rayleigh test on the spike directions", "rayleigh_p_spikes")]:
    print(f"Variant, {name}: {int(((cls.rate_SA1 < 10) & (cls[col] < 0.05) & (cls.kuiper_p < 0.05)).sum())} pass")
print("\nThe two R523 units (Table S1 lists one R523 and 41 R029 head-direction cells):")
print(units[units.rat == "R523"][["unit", "file_SA1", "file_RA_rm", "file_SA2"]].to_string(index=False))
print("\nRates in stable1 (AP/s): min %.2f, max %.2f; Rayleigh p max %.2g; Kuiper p max %.2g" %
      (cls.rate_SA1.min(), cls.rate_SA1.max(), cls.rayleigh_p.max(), cls.kuiper_p.max()))
for alpha in [0.01, 0.001]:
    print(f"  at p < {alpha}: {int(((cls.rate_SA1 < 10) & (cls.rayleigh_p < alpha) & (cls.kuiper_p < alpha)).sum())} pass")
       HD cells, Table S1  HD units in data set  pass criteria (b)  simultaneous HD pairs in data set  MEC cells, Table S1  MEC pairs, Table S1
R024                    5                     5                  5                                  3                   32                  116
R027                    3                     3                  3                                  3                    8                   15
R029                   41                    40                 40                                 68                   63                  141
R030                    0                     0                  0                                  0                    9                    3
R035                   17                    17                 17                                 12                   43                   73
R039                    6                     6                  6                                  4                   16                   31
R084                    2                     2                  2                                  1                    2                    1
R130                    1                     1                  1                                  0                    6                    3
R157                   25                    25                 23                                 45                   68                   50
R176                    1                     1                  1                                  0                    2                    1
R357                    8                     8                  5                                  7                   10                   14
R521                    3                     3                  3                                  1                   53                   76
R523                    1                     2                  2                                  1                    7                    1
R848                    2                     2                  2                                  1                   20                   18
R850                    0                     0                  0                                  0                   14                   13
total                 115                   115                110                                146                  353                  556

Rats with head-direction units: 13
Reading (a): head-direction units 115 (expected 115 +/- 11.5); MEC units in the data set 115 (expected 353, the other MEC units are not deposited); simultaneously recorded pairs 146 (all of them head-direction pairs; expected 556 MEC pairs, and 142 head-direction pairs in Figure 4)
Reading (b): units passing the head-direction criteria 110 of 115
Failing units:
          unit  rate_SA1  rayleigh_r  rayleigh_p  rayleigh_p_36  rayleigh_p_spikes  kuiper_V  kuiper_p  rat  session  passes
1020R357-P10C1    1.7817      0.0218      0.4331         0.9832                0.0    0.0428    0.0506 R357 1020R357   False
 1024R357-P9C2    1.4999      0.0384      0.2954         0.9490                0.0    0.0615    0.0542 R357 1024R357   False
 1024R357-P9C3    1.3092      0.0531      0.2812         0.9047                0.0    0.1445    0.0000 R357 1024R357   False
1026R157-P11C2   13.7681      0.0780      0.0000         0.8054                0.0    0.0748    0.0000 R157 1026R157   False
1026R157-P11C3   11.8979      0.1352      0.0000         0.5211                0.0    0.0829    0.0000 R157 1026R157   False
Variant, n = 36 bins: 83 pass
Variant, Rayleigh test on the spike directions: 110 pass

The two R523 units (Table S1 lists one R523 and 41 R029 head-direction cells):
         unit              file_SA1           file_RA_rm              file_SA2
1001R523-P1C1 1001SA1R523-cl.P1C1Rm 1001RAR523-cl.P1C1Rm 1001SA2R523-cl.P1C1Rm
1001R523-P9C1 1001SA1R523-cl.P9C1Rm 1001RAR523-cl.P9C1Rm 1001SA2R523-cl.P9C1Rm

Rates in stable1 (AP/s): min 0.02, max 13.77; Rayleigh p max 0.43; Kuiper p max 0.054
  at p < 0.01: 105 pass
  at p < 0.001: 105 pass

Result: partially reproduced. The data set holds 115 head-direction units from 13 rats, matching the paper's count; their per-rat numbers match Table S1 except R029 (40 against 41) and R523 (2 against 1). Both R523 units are named R523 in all their files (session 1001R523), so the files do not show which unit the table counts under another rat. Applying the paper's criteria at p < 0.05, with the Rayleigh test of the tuning curve's vector, 110 of the 115 pass: two units fire above 10 AP/s in stable1 (13.8 and 11.9 AP/s), two have a Kuiper p of 0.051 and 0.054, and three have a Rayleigh p of 0.28 to 0.43 (two of them among the Kuiper failures). With n = 36 bins in the Rayleigh test 83 pass, and with the Rayleigh test of the raw spike directions 110. The 115 are within tolerance under reading (a) and 110 under reading (b), which is circular since the deposited units were selected as head-direction cells. The 353 MEC cells and 556 MEC cell pairs of Table S1 cannot be counted: only the head-direction cells are deposited. The units form 146 simultaneously recorded pairs, against the 142 head-direction pairs the paper analyses in Figure 4.

hd-cell-rate¶

The head-direction cells have long-duration spikes and a mean firing rate of 1.41 ± 0.20 AP/s.

Mean over units of spike count over trial duration, (a) stable1, (b) the mean over the three trials. Spike width cannot be tested (no waveforms).

In [9]:
rate = pd.DataFrame({tr: {u: data[u][tr]["n"].sum() / TRIALDUR[(u, tr)] for u in U} for tr in ["SA1", "RA_rm", "SA2"]})
rate.columns = ["stable1", "rotating", "stable2"]
ra = rate.stable1.mean()
rb = rate.mean(axis=1).mean()
print(f"(a) stable1: mean {ra:.3f} AP/s, SEM {rate.stable1.sem():.3f}, median {rate.stable1.median():.3f}, "
      f"range {rate.stable1.min():.3f} to {rate.stable1.max():.3f}")
print(f"(b) mean over three trials: {rb:.3f} AP/s, SEM {rate.mean(axis=1).sem():.3f}")
print("Expected 1.41 +/- 0.20 AP/s; within under (a):", abs(ra - 1.41) <= 0.2, "; under (b):", abs(rb - 1.41) <= 0.2)
print("Units at or above 10 AP/s in stable1:", int((rate.stable1 >= 10).sum()))
print("\nBy rat (stable1):")
print(rate.join(units.set_index("unit").rat).groupby("rat").stable1.agg(["size", "mean", "median"]).round(2).T.to_string())
(a) stable1: mean 1.392 AP/s, SEM 0.207, median 0.668, range 0.019 to 13.768
(b) mean over three trials: 1.433 AP/s, SEM 0.233
Expected 1.41 +/- 0.20 AP/s; within under (a): True ; under (b): True
Units at or above 10 AP/s in stable1: 2

By rat (stable1):
rat     R024  R027   R029   R035  R039  R084  R130   R157  R176  R357  R521  R523  R848
size    5.00  3.00  40.00  17.00  6.00  2.00  1.00  25.00  1.00  8.00  3.00  2.00  2.00
mean    0.62  0.88   0.85   0.98  0.60  1.48  1.94   2.95  0.71  1.25  0.77  3.95  0.28
median  0.64  0.54   0.43   0.70  0.41  1.48  1.94   1.15  0.71  1.40  0.55  3.95  0.28

Result: reproduced. The mean stable1 rate is 1.392 AP/s (reading (a)) and the mean over the three trials 1.433 AP/s (reading (b)), both within 1.41 ± 0.20 AP/s. The median is 0.668 AP/s, and two units fire above 10 AP/s in stable1, the paper's upper limit for these cells.

fig1a-avoidance-learning¶

Blocked, data missing. The learning curves are over the pretraining and training sessions. The data set's tracker files hold only the 44 recording sessions (stable1, rotating, stable2), one triad per session, with 1 to 12 sessions per rat; the training sessions are not deposited.

fig1c-speed¶

Rotation did not change locomotor speed relative to stable1, measured in either frame, but speed was lower in stable2 than in the other conditions.

Mean speed per session in stable1, rotating room frame, rotating arena frame and stable2 from the 30 Hz TSD positions (pixels, 2.1333 pixels/cm from the tracker headers), samples with x = y = 0 left out. Readings: (a) displacement between successive tracked samples, (b) displacement over 1 s steps (30 samples). Repeated-measures ANOVA on sessions, Greenhouse-Geisser when Mauchly's test is significant, and Tukey HSD. The paper ran its tests in JMP and names Tukey-Kramer HSD after repeated-measures ANOVAs; the post hoc test here uses the repeated-measures error term of the ANOVA (hd20.tukey_rm, an assumption), and the between-groups Tukey-Kramer HSD, which ignores the pairing, is a variant. The four sessions with duplicated tracking are left out of the main test and kept in a variant.

In [10]:
def speed(x, step):
    ok = ~((x["x"] == 0) & (x["y"] == 0))
    px, py = x["x"].astype(float), x["y"].astype(float)
    px[~ok] = np.nan
    py[~ok] = np.nan
    dist = np.hypot(px[step:] - px[:-step], py[step:] - py[:-step])
    return np.nanmean(dist) / 2.1333 * x["fs"] / step   # cm/s


SPEED_COND = {"SA1": "stable1", "RA_rm": "rotating room", "RA_ar": "rotating arena", "SA2": "stable2"}
dup_sessions = {s for s, _ in DUP_TRACK}
for label, step in [("(a) successive samples", 1), ("(b) 1 s steps", 30)]:
    sp = pd.DataFrame({SPEED_COND[tr]: {s: speed(data[us[0]][tr], step) for s, us in SESS.items()} for tr in TR})
    for name, w in [("main, duplicated-tracking sessions left out", sp.drop(index=sorted(dup_sessions))),
                    ("variant, all sessions", sp)]:
        r = hd20.rm_anova(w)
        print(f"{label}, {name}: means (cm/s)", w.mean().round(2).to_dict())
        print("  ANOVA", hd20.fmt_anova(r))
        print("  Tukey HSD with the repeated-measures error term (main):")
        print(hd20.tukey_rm(w).round(4).to_string(index=False))
        print("  Tukey-Kramer HSD between groups (variant):")
        print(hd20.tukey(w).round(4).to_string(index=False))
        pt = []
        for c in ["stable1", "rotating room", "rotating arena"]:
            t = stats.ttest_rel(w[c], w["stable2"])
            pt.append(f"{c} vs stable2 paired t p = {t.pvalue:.2g}, stable2 lower in {int((w['stable2'] < w[c]).sum())}/{len(w)}")
        print("  " + "; ".join(pt))
    if step == 1:
        sp_a = sp
print("\nSpeed range over sessions and conditions, reading (a): %.2f to %.2f cm/s" % (sp_a.min().min(), sp_a.max().max()))
fig, ax = plt.subplots(figsize=(5, 3))
ax.boxplot([sp_a[c] for c in sp_a.columns], tick_labels=list(sp_a.columns))
ax.set_ylabel("speed (cm/s), reading (a)")
plt.show()
(a) successive samples, main, duplicated-tracking sessions left out: means (cm/s) {'stable1': 15.54, 'rotating room': 14.63, 'rotating arena': 15.6, 'stable2': 10.76}
  ANOVA F(1.94, 75.59) = 64.80, p = 7.59e-17 (n = 40, Mauchly p = 1.08e-34, GG applied, epsilon 0.65)
  Tukey HSD with the repeated-measures error term (main):
        group1         group2  meandiff       q  p-adj  df
       stable1  rotating room   -0.9090  3.1886 0.1149 117
       stable1 rotating arena    0.0569  0.1996 0.9990 117
       stable1        stable2   -4.7875 16.7942 0.0000 117
 rotating room rotating arena    0.9659  3.3882 0.0835 117
 rotating room        stable2   -3.8786 13.6055 0.0000 117
rotating arena        stable2   -4.8444 16.9937 0.0000 117
  Tukey-Kramer HSD between groups (variant):
        group1        group2  meandiff  p-adj  reject
rotating arena rotating room   -0.9659 0.3777   False
rotating arena       stable1   -0.0569 0.9997   False
rotating arena       stable2   -4.8444 0.0000    True
 rotating room       stable1    0.9090 0.4326   False
 rotating room       stable2   -3.8786 0.0000    True
       stable1       stable2   -4.7875 0.0000    True
  stable1 vs stable2 paired t p = 2.9e-11, stable2 lower in 38/40; rotating room vs stable2 paired t p = 2.6e-12, stable2 lower in 36/40; rotating arena vs stable2 paired t p = 3.4e-15, stable2 lower in 37/40
(a) successive samples, variant, all sessions: means (cm/s) {'stable1': 15.3, 'rotating room': 14.64, 'rotating arena': 15.67, 'stable2': 10.82}
  ANOVA F(1.92, 82.39) = 64.63, p = 3.27e-17 (n = 44, Mauchly p = 4.03e-25, GG applied, epsilon 0.64)
  Tukey HSD with the repeated-measures error term (main):
        group1         group2  meandiff       q  p-adj  df
       stable1  rotating room   -0.6597  2.3778 0.3377 129
       stable1 rotating arena    0.3676  1.3249 0.7851 129
       stable1        stable2   -4.4766 16.1349 0.0000 129
 rotating room rotating arena    1.0273  3.7028 0.0481 129
 rotating room        stable2   -3.8168 13.7570 0.0000 129
rotating arena        stable2   -4.8441 17.4598 0.0000 129
  Tukey-Kramer HSD between groups (variant):
        group1        group2  meandiff  p-adj  reject
rotating arena rotating room   -1.0273 0.2739   False
rotating arena       stable1   -0.3676 0.9167   False
rotating arena       stable2   -4.8441 0.0000    True
 rotating room       stable1    0.6597 0.6528   False
 rotating room       stable2   -3.8168 0.0000    True
       stable1       stable2   -4.4766 0.0000    True
  stable1 vs stable2 paired t p = 3.2e-11, stable2 lower in 40/44; rotating room vs stable2 paired t p = 2.5e-13, stable2 lower in 39/44; rotating arena vs stable2 paired t p = 3.7e-17, stable2 lower in 41/44
(b) 1 s steps, main, duplicated-tracking sessions left out: means (cm/s) {'stable1': 8.88, 'rotating room': 9.22, 'rotating arena': 8.25, 'stable2': 5.91}
  ANOVA F(1.87, 72.82) = 55.86, p = 6.88e-15 (n = 40, Mauchly p = 2e-17, GG applied, epsilon 0.62)
  Tukey HSD with the repeated-measures error term (main):
        group1         group2  meandiff       q  p-adj  df
       stable1  rotating room    0.3310  1.6596 0.6447 117
       stable1 rotating arena   -0.6377  3.1971 0.1133 117
       stable1        stable2   -2.9735 14.9071 0.0000 117
 rotating room rotating arena   -0.9688  4.8568 0.0045 117
 rotating room        stable2   -3.3046 16.5667 0.0000 117
rotating arena        stable2   -2.3358 11.7099 0.0000 117
  Tukey-Kramer HSD between groups (variant):
        group1        group2  meandiff  p-adj  reject
rotating arena rotating room    0.9688 0.0747   False
rotating arena       stable1    0.6377 0.3798   False
rotating arena       stable2   -2.3358 0.0000    True
 rotating room       stable1   -0.3310 0.8391   False
 rotating room       stable2   -3.3046 0.0000    True
       stable1       stable2   -2.9735 0.0000    True
  stable1 vs stable2 paired t p = 1.1e-09, stable2 lower in 37/40; rotating room vs stable2 paired t p = 1.2e-16, stable2 lower in 40/40; rotating arena vs stable2 paired t p = 3.1e-11, stable2 lower in 35/40
(b) 1 s steps, variant, all sessions: means (cm/s) {'stable1': 8.74, 'rotating room': 9.24, 'rotating arena': 8.33, 'stable2': 5.98}
  ANOVA F(1.86, 79.81) = 55.81, p = 2.9e-15 (n = 44, Mauchly p = 1.76e-16, GG applied, epsilon 0.62)
  Tukey HSD with the repeated-measures error term (main):
        group1         group2  meandiff       q  p-adj  df
       stable1  rotating room    0.5062  2.6196 0.2540 129
       stable1 rotating arena   -0.4088  2.1157 0.4429 129
       stable1        stable2   -2.7560 14.2623 0.0000 129
 rotating room rotating arena   -0.9150  4.7353 0.0058 129
 rotating room        stable2   -3.2622 16.8818 0.0000 129
rotating arena        stable2   -2.3471 12.1466 0.0000 129
  Tukey-Kramer HSD between groups (variant):
        group1        group2  meandiff  p-adj  reject
rotating arena rotating room    0.9150 0.0768   False
rotating arena       stable1    0.4088 0.7009   False
rotating arena       stable2   -2.3471 0.0000    True
 rotating room       stable1   -0.5062 0.5390   False
 rotating room       stable2   -3.2622 0.0000    True
       stable1       stable2   -2.7560 0.0000    True
  stable1 vs stable2 paired t p = 1.4e-09, stable2 lower in 39/44; rotating room vs stable2 paired t p = 6.7e-18, stable2 lower in 44/44; rotating arena vs stable2 paired t p = 1.1e-12, stable2 lower in 39/44

Speed range over sessions and conditions, reading (a): 2.03 to 21.04 cm/s
No description has been provided for this image

Result: reproduced. With the 40 sessions whose tracking is not duplicated, speed differs across conditions (reading (a): F(1.94, 75.59) = 64.80, p = 7.6e-17; reading (b): F(1.87, 72.82) = 55.86, p = 6.9e-15). Under reading (a) stable2 is lower than each other condition by Tukey HSD with the repeated-measures error term (adjusted p below 0.0001; 10.76 against 14.63 to 15.60 cm/s), and stable1 and the two rotating frames do not differ (adjusted p 0.08 to 1.00). Under reading (b) the room and arena frames differ (adjusted p = 0.0045), so only reading (a) gives the claimed pattern. With the between-groups Tukey-Kramer HSD (variant) both readings give it (others adjusted p 0.07 to 1.00). Reading (a) gives the pattern under either error term, so the outcome does not rest on that choice. With all 44 sessions, reading (a) gives a room-arena difference at adjusted p = 0.048 under the repeated-measures error term, and the pattern under the between-groups variant.

fig1c-lfp-power¶

Blocked, data missing: the data set holds no LFP.

fig1c-firing-rate¶

Firing rates of the head-direction cells were maintained across stable1, rotating and stable2.

Mean rate per unit and trial; repeated-measures ANOVA over the three trials, Greenhouse-Geisser when Mauchly's test is significant. A claim of absence: reproduced when p ≥ 0.05.

In [11]:
r = hd20.rm_anova(rate)
print("Mean rate (AP/s):", rate.mean().round(3).to_dict(), "; median:", rate.median().round(3).to_dict())
print("ANOVA", hd20.fmt_anova(r), "; uncorrected p =", round(r["p_uncorrected"], 4))
print("Mean change rotating - stable1: %.3f AP/s; stable2 - stable1: %.3f AP/s" %
      ((rate.rotating - rate.stable1).mean(), (rate.stable2 - rate.stable1).mean()))
print("Wilcoxon signed-rank (variant): rotating vs stable1 p = %.3g; stable2 vs stable1 p = %.3g" %
      (stats.wilcoxon(rate.rotating, rate.stable1).pvalue, stats.wilcoxon(rate.stable2, rate.stable1).pvalue))
print("Without unit 1024R157-P9C1:", hd20.fmt_anova(hd20.rm_anova(rate.drop(index="1024R157-P9C1"))))
hi = rate.rotating.idxmax()
print(f"Highest rotating rate: {hi}, {rate.loc[hi].round(2).to_dict()} AP/s; without it:",
      hd20.fmt_anova(hd20.rm_anova(rate.drop(index=hi))), "; without it and 1024R157-P9C1:",
      hd20.fmt_anova(hd20.rm_anova(rate.drop(index=[hi, "1024R157-P9C1"]))))
print("Log rates (variant):", hd20.fmt_anova(hd20.rm_anova(np.log(rate + 0.01))))
print("\nBy rat, mean rate per trial:")
print(rate.join(units.set_index("unit").rat).groupby("rat").mean().round(2).T.to_string())
Mean rate (AP/s): {'stable1': 1.392, 'rotating': 1.71, 'stable2': 1.198} ; median: {'stable1': 0.668, 'rotating': 0.535, 'stable2': 0.56}
ANOVA F(1.35, 154.10) = 1.76, p = 0.184 (n = 115, Mauchly p = 9.4e-17, GG applied, epsilon 0.68) ; uncorrected p = 0.1738
Mean change rotating - stable1: 0.318 AP/s; stable2 - stable1: -0.194 AP/s
Wilcoxon signed-rank (variant): rotating vs stable1 p = 0.02; stable2 vs stable1 p = 0.125
Without unit 1024R157-P9C1: F(1.35, 152.73) = 1.74, p = 0.188 (n = 114, Mauchly p = 1.29e-16, GG applied, epsilon 0.68)
Highest rotating rate: 1001R523-P9C1, {'stable1': 7.81, 'rotating': 40.14, 'stable2': 5.37} AP/s; without it: F(1.83, 206.35) = 1.29, p = 0.275 (n = 114, Mauchly p = 0.00368, GG applied, epsilon 0.91) ; without it and 1024R157-P9C1: F(1.83, 204.54) = 1.24, p = 0.29 (n = 113, Mauchly p = 0.0039, GG applied, epsilon 0.91)
Log rates (variant): F(2.00, 228.00) = 6.70, p = 0.00149 (n = 115, Mauchly p = 0.761, GG not applied, epsilon 1.00)

By rat, mean rate per trial:
rat       R024  R027  R029  R035  R039  R084  R130  R157  R176  R357  R521   R523  R848
stable1   0.62  0.88  0.85  0.98  0.60  1.48  1.94  2.95  0.71  1.25  0.77   3.95  0.28
rotating  0.43  1.68  0.66  0.83  0.94  1.28  1.35  2.90  0.02  3.14  0.47  20.09  0.07
stable2   0.85  1.93  0.58  0.85  1.05  0.47  2.60  2.43  0.01  1.48  0.61   2.71  0.15

Result: reproduced. Mean rates are 1.392, 1.710 and 1.198 AP/s in stable1, rotating and stable2; the repeated-measures ANOVA with Greenhouse-Geisser correction gives F(1.35, 154.10) = 1.76, p = 0.184 (the paper: F(1.34, 153.21) = 1.89, p = 0.17). The mean change from stable1 is +0.318 AP/s in rotation and -0.194 AP/s in stable2. Leaving out the unit with the highest rotating rate (1001R523-P9C1, 40.1 AP/s in rotation against 7.8 in stable1) gives p = 0.275, and leaving out it and 1024R157-P9C1 p = 0.29, so the absence does not rest on that unit. A Wilcoxon test (variant) finds rotating different from stable1 (p = 0.02), and on log rates the ANOVA is significant (p = 0.0015), so the absence rests on the paper's test on raw rates.

fig1c-directionality¶

Directional tuning of head-direction cells was strongly degraded during rotation in both frames, more in the arena frame than in the room frame, and returned in stable2.

Directionality is the Rayleigh vector length of the 10 degree tuning curve, per unit in four conditions. Repeated-measures ANOVA and Tukey HSD with the ANOVA's repeated-measures error term (the paper's F(3, 342) on 115 cells implies a within-cell error term; that the post hoc test used it is an assumption). The between-groups Tukey-Kramer HSD and Bonferroni-corrected paired t-tests are variants.

In [12]:
curves = {u: {tr: hd20.tuning(data[u][tr]) for tr in TR} for u in U}
dirn = pd.DataFrame({hd20.TRIAL_NAMES[tr]: {u: hd20.resultant(curves[u][tr][2])[0] for u in U} for tr in TR})
r = hd20.rm_anova(dirn)
print("Directionality mean:", dirn.mean().round(3).to_dict())
print("median:", dirn.median().round(3).to_dict())
print("ANOVA", hd20.fmt_anova(r))
print("Tukey HSD with the repeated-measures error term (main):")
print(hd20.tukey_rm(dirn).round(5).to_string(index=False))
print("Tukey-Kramer HSD between groups (variant):")
print(hd20.tukey(dirn).round(5).to_string(index=False))
pt = {f"{a} vs {b}": stats.ttest_rel(dirn[a], dirn[b]).pvalue for a, b in
      [("stable1", "stable2"), ("stable1", "rotating room"), ("stable2", "rotating room"), ("rotating room", "rotating arena"),
       ("stable1", "rotating arena"), ("stable2", "rotating arena")]}
print("Paired t-tests (variant), and Bonferroni-corrected over the 6 pairs:",
      {k: f"{v:.2g} / {min(6 * v, 1):.2g}" for k, v in pt.items()})
print("Units with room > arena directionality: %d of %d" % ((dirn["rotating room"] > dirn["rotating arena"]).sum(), len(dirn)))
print("\nBy rat, mean directionality:")
print(dirn.join(units.set_index("unit").rat).groupby("rat").mean().round(3).T.to_string())
print("Range of directionality: %.3f to %.3f" % (dirn.min().min(), dirn.max().max()))
fig, ax = plt.subplots(figsize=(6, 3))
ax.boxplot([dirn[c] for c in dirn.columns], tick_labels=list(dirn.columns))
ax.set_ylabel("Rayleigh vector length")
plt.show()
Directionality mean: {'stable1': 0.46, 'rotating room': 0.344, 'rotating arena': 0.17, 'stable2': 0.421}
median: {'stable1': 0.419, 'rotating room': 0.263, 'rotating arena': 0.151, 'stable2': 0.386}
ANOVA F(2.77, 315.60) = 72.66, p = 8.88e-34 (n = 115, Mauchly p = 0.00424, GG applied, epsilon 0.92)
Tukey HSD with the repeated-measures error term (main):
        group1         group2  meandiff        q   p-adj  df
       stable1  rotating room  -0.11635  7.70576 0.00000 342
       stable1 rotating arena  -0.29028 19.22568 0.00000 342
       stable1        stable2  -0.03888  2.57516 0.26523 342
 rotating room rotating arena  -0.17394 11.51992 0.00000 342
 rotating room        stable2   0.07747  5.13060 0.00186 342
rotating arena        stable2   0.25140 16.65052 0.00000 342
Tukey-Kramer HSD between groups (variant):
        group1        group2  meandiff  p-adj  reject
rotating arena rotating room    0.1739 0.0000    True
rotating arena       stable1    0.2903 0.0000    True
rotating arena       stable2    0.2514 0.0000    True
 rotating room       stable1    0.1163 0.0009    True
 rotating room       stable2    0.0775 0.0553   False
       stable1       stable2   -0.0389 0.5795   False
Paired t-tests (variant), and Bonferroni-corrected over the 6 pairs: {'stable1 vs stable2': '0.023 / 0.14', 'stable1 vs rotating room': '6.3e-08 / 3.8e-07', 'stable2 vs rotating room': '0.00081 / 0.0048', 'rotating room vs rotating arena': '2.3e-11 / 1.4e-10', 'stable1 vs rotating arena': '3.7e-25 / 2.2e-24', 'stable2 vs rotating arena': '1.1e-19 / 6.7e-19'}
Units with room > arena directionality: 82 of 115

By rat, mean directionality:
rat              R024   R027   R029   R035   R039   R084   R130   R157   R176   R357   R521   R523   R848
stable1         0.469  0.650  0.626  0.538  0.385  0.429  0.324  0.245  0.324  0.191  0.449  0.402  0.401
rotating room   0.535  0.695  0.429  0.448  0.167  0.391  0.180  0.166  0.605  0.177  0.279  0.313  0.196
rotating arena  0.160  0.135  0.206  0.188  0.113  0.132  0.232  0.118  0.223  0.116  0.268  0.108  0.271
stable2         0.373  0.519  0.569  0.531  0.328  0.394  0.318  0.191  0.586  0.187  0.370  0.670  0.409
Range of directionality: 0.006 to 0.996
No description has been provided for this image

Result: reproduced, resting on the assumed error term of the post hoc test. Directionality differs across conditions (F(2.77, 315.60) = 72.66, p = 8.9e-34; the paper F(3, 342) = 70.36). With Tukey HSD on the repeated-measures error term, stable1 and stable2 do not differ (p = 0.27), the room frame is below stable1 (p below 0.0001) and stable2 (p = 0.0019), and the arena frame is below the room frame (p below 0.0001), every required pair at p < 0.01. With the between-groups Tukey-Kramer HSD (variant), which ignores the pairing of the conditions within a cell, the room frame is not below stable2 at p < 0.01 (p = 0.055), so that variant gives the partial outcome. Bonferroni-corrected paired t-tests agree with the main reading (stable2 against room p = 0.0048, stable1 against stable2 p = 0.14).

fig1d-preference-change and fig1d-instability¶

The change in preferred direction differs across trial pairs (stable1-stable2 = stable1-rotating room frame > stable1-rotating arena frame), and is greater for every trial pair than between the two halves of stable1.

Directional instability (the KLD between tuning curves) differs across trial pairs and is greater for every trial pair than between the two halves of stable1.

Preferred direction: the bin of maximum rate; change: absolute circular difference. KLD of the Krichevsky-Trofimov probabilities, readings (a) spike counts per bin, (b) rates per bin. Halves of stable1: first and second 15 min (claims file). Repeated-measures ANOVA over the three trial pairs with Tukey HSD (repeated-measures error term; the between-groups Tukey-Kramer HSD as a variant); one-way ANOVA of the four groups with Dunnett's test against the halves. A variant of KLD (b) rescales each rate curve to sum to the cell's spike count before the Krichevsky-Trofimov estimate, since adding 0.5 to rates far below 1 makes the probabilities nearly uniform.

In [13]:
PAIRS = {"s1-s2": ("SA1", "SA2"), "s1-room": ("SA1", "RA_rm"), "s1-arena": ("SA1", "RA_ar")}
halves = {}
for u in U:
    n = len(data[u]["SA1"]["d"])
    halves[u] = (hd20.tuning(data[u]["SA1"], slice(0, n // 2)), hd20.tuning(data[u]["SA1"], slice(n // 2, n)))
pref, kl_c, kl_r, kl_s = {}, {}, {}, {}
for u in U:
    c = curves[u]
    pref[u] = {k: float(hd20.circ_absdiff(hd20.preferred(c[a][2]), hd20.preferred(c[b][2]))) for k, (a, b) in PAIRS.items()}
    pref[u]["halves"] = float(hd20.circ_absdiff(hd20.preferred(halves[u][0][2]), hd20.preferred(halves[u][1][2])))
    kl_c[u] = {k: hd20.kld(c[a][0], c[b][0]) for k, (a, b) in PAIRS.items()}
    kl_c[u]["halves"] = hd20.kld(halves[u][0][0], halves[u][1][0])
    kl_r[u] = {k: hd20.kld(c[a][2], c[b][2]) for k, (a, b) in PAIRS.items()}
    kl_r[u]["halves"] = hd20.kld(halves[u][0][2], halves[u][1][2])
    # variant: rates rescaled to sum to the spike count, so that the Krichevsky-Trofimov 0.5 acts on
    # the scale of counts (low rates otherwise put most of the probability in the 0.5 terms)
    sc = lambda cv: cv[2] * cv[0].sum() / cv[2].sum() if cv[2].sum() > 0 else cv[2]
    kl_s[u] = {k: hd20.kld(sc(c[a]), sc(c[b])) for k, (a, b) in PAIRS.items()}
    kl_s[u]["halves"] = hd20.kld(sc(halves[u][0]), sc(halves[u][1]))
pref, kl_c, kl_r, kl_s = pd.DataFrame(pref).T, pd.DataFrame(kl_c).T, pd.DataFrame(kl_r).T, pd.DataFrame(kl_s).T


def fig1d_tests(w, name):
    tri = w[["s1-s2", "s1-room", "s1-arena"]]
    r1 = hd20.rm_anova(tri)
    r2 = hd20.oneway({c: w[c] for c in w.columns})
    dn = hd20.dunnett({c: w[c] for c in w.columns}, "halves")
    print(f"{name}: means", w.mean().round(4).to_dict(), "; medians", w.median().round(4).to_dict())
    print("  trial pairs, RM ANOVA", hd20.fmt_anova(r1))
    print("  Tukey HSD with the repeated-measures error term (main):")
    print(hd20.tukey_rm(tri).round(5).to_string(index=False))
    print("  Tukey-Kramer HSD between groups (variant):")
    print(hd20.tukey(tri).round(5).to_string(index=False))
    print(f"  four groups, one-way ANOVA F({r2['df1']}, {r2['df2']}) = {r2['F']:.2f}, p = {r2['p']:.3g}")
    print(dn.round(5).to_string(index=False))
    return r1, r2, dn


res_pref = fig1d_tests(pref, "Preferred direction change (degrees)")
print()
res_klc = fig1d_tests(kl_c, "KLD, reading (a) spike counts")
print()
res_klr = fig1d_tests(kl_r, "KLD, reading (b) rates")
print()
res_kls = fig1d_tests(kl_s, "KLD, variant: rates rescaled to the spike count")
print("\nBy rat, mean preferred-direction change and KLD (a):")
print(pref.join(units.set_index("unit").rat).groupby("rat").mean().round(1).T.to_string())
print(kl_c.join(units.set_index("unit").rat).groupby("rat").mean().round(3).T.to_string())
print("Ranges: preference change %.0f to %.0f degrees; KLD (a) %.4f to %.4f; KLD (b) %.4f to %.4f" %
      (pref.min().min(), pref.max().max(), kl_c.min().min(), kl_c.max().max(), kl_r.min().min(), kl_r.max().max()))
Preferred direction change (degrees): means {'s1-s2': 58.087, 's1-room': 60.2609, 's1-arena': 91.3043, 'halves': 39.4783} ; medians {'s1-s2': 40.0, 's1-room': 40.0, 's1-arena': 90.0, 'halves': 20.0}
  trial pairs, RM ANOVA F(2.00, 228.00) = 17.80, p = 6.56e-08 (n = 115, Mauchly p = 0.538, GG not applied, epsilon 0.99)
  Tukey HSD with the repeated-measures error term (main):
 group1   group2  meandiff       q   p-adj  df
  s1-s2  s1-room   2.17391 0.49357 0.93508 228
  s1-s2 s1-arena  33.21739 7.54178 0.00000 228
s1-room s1-arena  31.04348 7.04820 0.00000 228
  Tukey-Kramer HSD between groups (variant):
  group1  group2  meandiff  p-adj  reject
s1-arena s1-room  -31.0435  0.000    True
s1-arena   s1-s2  -33.2174  0.000    True
 s1-room   s1-s2   -2.1739  0.949   False
  four groups, one-way ANOVA F(3, 456) = 19.62, p = 5.55e-12
   group     mean  control_mean  statistic       p
   s1-s2 58.08696      39.47826    2.71391 0.01903
 s1-room 60.26087      39.47826    3.03096 0.00730
s1-arena 91.30435      39.47826    7.55837 0.00000

KLD, reading (a) spike counts: means {'s1-s2': 0.2555, 's1-room': 0.2184, 's1-arena': 0.3481, 'halves': 0.1592} ; medians {'s1-s2': 0.1783, 's1-room': 0.1735, 's1-arena': 0.2568, 'halves': 0.1277}
  trial pairs, RM ANOVA F(1.60, 182.42) = 11.74, p = 7.22e-05 (n = 115, Mauchly p = 8.83e-08, GG applied, epsilon 0.80)
  Tukey HSD with the repeated-measures error term (main):
 group1   group2  meandiff       q   p-adj  df
  s1-s2  s1-room  -0.03710 1.90163 0.37201 228
  s1-s2 s1-arena   0.09265 4.74944 0.00264 228
s1-room s1-arena   0.12974 6.65107 0.00001 228
  Tukey-Kramer HSD between groups (variant):
  group1  group2  meandiff  p-adj  reject
s1-arena s1-room   -0.1297 0.0003    True
s1-arena   s1-s2   -0.0926 0.0158    True
 s1-room   s1-s2    0.0371 0.5064   False
  four groups, one-way ANOVA F(3, 456) = 13.74, p = 1.36e-08
   group    mean  control_mean  statistic       p
   s1-s2 0.25545       0.15921    3.18530 0.00442
 s1-room 0.21836       0.15921    1.95748 0.12739
s1-arena 0.34810       0.15921    6.25185 0.00000

KLD, reading (b) rates: means {'s1-s2': 0.058, 's1-room': 0.0491, 's1-arena': 0.082, 'halves': 0.0369} ; medians {'s1-s2': 0.0293, 's1-room': 0.0307, 's1-arena': 0.0502, 'halves': 0.0251}
  trial pairs, RM ANOVA F(1.60, 182.29) = 8.47, p = 0.000842 (n = 115, Mauchly p = 8.23e-08, GG applied, epsilon 0.80)
  Tukey HSD with the repeated-measures error term (main):
 group1   group2  meandiff       q   p-adj  df
  s1-s2  s1-room  -0.00888 1.51783 0.53164 228
  s1-s2 s1-arena   0.02403 4.10738 0.01123 228
s1-room s1-arena   0.03291 5.62521 0.00027 228
  Tukey-Kramer HSD between groups (variant):
  group1  group2  meandiff  p-adj  reject
s1-arena s1-room   -0.0329 0.0491    True
s1-arena   s1-s2   -0.0240 0.1977   False
 s1-room   s1-s2    0.0089 0.7998   False
  four groups, one-way ANOVA F(3, 456) = 4.83, p = 0.00256
   group    mean  control_mean  statistic       p
   s1-s2 0.05799        0.0369    1.71708 0.20755
 s1-room 0.04911        0.0369    0.99413 0.62887
s1-arena 0.08202        0.0369    3.67345 0.00078

KLD, variant: rates rescaled to the spike count: means {'s1-s2': 0.2, 's1-room': 0.1911, 's1-arena': 0.3354, 'halves': 0.1431} ; medians {'s1-s2': 0.1307, 's1-room': 0.1179, 's1-arena': 0.2263, 'halves': 0.1167}
  trial pairs, RM ANOVA F(1.47, 167.57) = 19.73, p = 6.29e-07 (n = 115, Mauchly p = 1.06e-11, GG applied, epsilon 0.73)
  Tukey HSD with the repeated-measures error term (main):
 group1   group2  meandiff       q   p-adj  df
  s1-s2  s1-room  -0.00891 0.48953 0.93611 228
  s1-s2 s1-arena   0.13542 7.43722 0.00000 228
s1-room s1-arena   0.14433 7.92674 0.00000 228
  Tukey-Kramer HSD between groups (variant):
  group1  group2  meandiff  p-adj  reject
s1-arena s1-room   -0.1443 0.0001    True
s1-arena   s1-s2   -0.1354 0.0002    True
 s1-room   s1-s2    0.0089 0.9613   False
  four groups, one-way ANOVA F(3, 456) = 15.11, p = 2.16e-09
   group    mean  control_mean  statistic       p
   s1-s2 0.19998       0.14312    1.89367 0.14582
 s1-room 0.19107       0.14312    1.59684 0.25933
s1-arena 0.33540       0.14312    6.40329 0.00000

By rat, mean preferred-direction change and KLD (a):
rat       R024  R027  R029  R035  R039  R084  R130   R157   R176  R357   R521  R523   R848
s1-s2     40.0  10.0  33.5  63.5  93.3  80.0  20.0  102.0   70.0  51.2   30.0  40.0   45.0
s1-room   24.0  10.0  46.5  54.7  71.7  10.0  30.0   87.2  120.0  82.5   43.3  85.0  125.0
s1-arena  98.0  90.0  92.2  88.2  96.7  30.0  70.0  104.0  120.0  76.2  103.3  40.0   60.0
halves    62.0  13.3  17.8  37.6  28.3  45.0  30.0   71.2   20.0  78.8   10.0  30.0   15.0
rat        R024   R027   R029   R035   R039   R084   R130   R157   R176   R357   R521   R523   R848
s1-s2     0.360  0.065  0.208  0.354  0.307  0.333  0.722  0.286  0.239  0.190  0.095  0.180  0.123
s1-room   0.159  0.065  0.257  0.235  0.118  0.101  0.231  0.213  0.306  0.198  0.223  0.129  0.288
s1-arena  0.286  0.520  0.527  0.377  0.142  0.173  0.567  0.194  0.176  0.165  0.189  0.178  0.263
halves    0.169  0.054  0.110  0.115  0.149  0.152  0.381  0.249  0.080  0.252  0.113  0.181  0.181
Ranges: preference change 0 to 180 degrees; KLD (a) 0.0190 to 1.7293; KLD (b) 0.0007 to 1.1106

Result: partially reproduced (fig1d-preference-change). The change in preferred direction differs across trial pairs (F(2, 228) = 17.80, p = 6.6e-08; the paper F(2, 228) = 10.54) and in the four-group ANOVA (F(3, 456) = 19.62, p = 5.6e-12), and every trial pair exceeds the stable1 halves by Dunnett's test (p = 0.019, 0.0073 and below 0.0001). Stable1-stable2 and stable1-room do not differ (Tukey p = 0.94 on the repeated-measures error term, 0.95 between groups), as in the legend, but the stable1-arena change is larger than the other two (91 against 58 and 60 degrees, p below 0.0001), where the legend orders it below them. Whether the legend's order is garbled is asked of a reader (questions/park-2019.yaml).

Result: partially reproduced (fig1d-instability). With KLD on spike counts (reading (a)) both ANOVAs are significant (trial pairs F(1.60, 182.42) = 11.74, p = 7.2e-05; the paper F(1.62, 184.22) = 7.78; four groups F(3, 456) = 13.74, p = 1.4e-08), and stable1-stable2 and stable1-arena exceed the halves by Dunnett's test (p = 0.0044 and below 0.0001), but stable1-room does not (p = 0.13). With KLD on rates (reading (b)) only stable1-arena exceeds the halves (p = 0.0008). With the rates rescaled to the spike count before the Krichevsky-Trofimov estimate (variant) the same holds (stable1-arena p below 0.0001, the others 0.15 and 0.26). The criterion has no partial form; partially reproduced is a judgement outside it, made because the ANOVAs and two of the three comparisons with the halves hold under reading (a). Read strictly, the claim is not reproduced.

fig2-decoding-stable-vs-rotating¶

Head direction decoded from stable1 ensemble tuning is relatively accurate in stable2 and relatively inaccurate and abruptly changing in both frames during rotation, although for some ensembles room-frame decoding is similar to stable2; seven ensembles of at least five head-direction cells were analysed.

The decoder of HD_Max_likelihood.py (helper fit_decoder, decode): trained on stable1, applied to stable2 and to the rotating trial in room and arena coordinates; the estimate is the start of the winning 10 degree bin, as the code's angs. Windows of 20 samples (660 ms; main) and 4 samples (133 ms; variant). Error measures (a) median and (b) mean absolute circular error per ensemble and condition.

In [14]:
ENS = {s: us for s, us in SESS.items() if len(us) >= 5}
print("Sessions with at least 5 head-direction units:", len(ENS), {s: len(us) for s, us in ENS.items()})
DEC = {}
for w in [20, 4]:
    for s, cells in ENS.items():
        dtr, ctr = hd20.ensemble_windows(data, cells, "SA1", w)
        lam = hd20.fit_decoder(dtr, ctr)
        for tr in ["SA2", "RA_rm", "RA_ar"]:
            dte, cte = hd20.ensemble_windows(data, cells, tr, w)
            est = hd20.decode(lam, cte)
            DEC[(w, s, tr)] = {"dir": dte, "est": est, "err": hd20.signed_error(est, dte)}
Sessions with at least 5 head-direction units: 7 {'0930R029': 6, '1004R029': 5, '1022R029': 6, '1023R029': 6, '1026R157': 5, '1117R157': 5, '1121R157': 6}
In [15]:
rows = []
for (w, s, tr), v in DEC.items():
    ok = ~np.isnan(v["err"])
    e = np.abs(v["err"][ok])
    rows.append({"window": w, "ensemble": s, "cells": len(ENS[s]), "trial": tr, "decoded": int(ok.sum()),
                 "windows": len(v["err"]), "median_abs_err": np.median(e), "mean_abs_err": e.mean(),
                 "frac_within_30": np.mean(e <= 30), "change_gt_90": np.mean(np.abs((np.diff(v["est"][ok]) + 180) % 360 - 180) > 90)})
dec = pd.DataFrame(rows)
print("Chance level: absolute error uniform on 0-180 degrees has median and mean 90.")
for w in [20, 4]:
    print(f"\nWindow of {w} samples ({w / 30.02 * 1000:.0f} ms):")
    t = dec[dec.window == w].pivot_table(index=["ensemble", "cells"], columns="trial",
                                         values=["median_abs_err", "mean_abs_err", "decoded"])
    print(t.round(1).to_string())
    for m in ["median_abs_err", "mean_abs_err"]:
        p = dec[dec.window == w].pivot(index="ensemble", columns="trial", values=m)
        print(f"  {m}: stable2 below arena in {int((p.SA2 < p.RA_ar).sum())} of {len(p)}, "
              f"below room in {int((p.SA2 < p.RA_rm).sum())} of {len(p)}; "
              f"room below arena in {int((p.RA_rm < p.RA_ar).sum())} of {len(p)}")
ref = []
for s, cells in ENS.items():
    dtr, ctr = hd20.ensemble_windows(data, cells, "SA1", 20)
    h = len(dtr) // 2
    e = np.abs(hd20.signed_error(hd20.decode(hd20.fit_decoder(dtr[:h], ctr[:, :h]), ctr[:, h:]), dtr[h:]))
    ref.append({"ensemble": s, "first half -> second half of stable1, median abs err": np.nanmedian(e),
                "mean": np.nanmean(e)})
print("\nReference: decoding the second half of stable1 from its first half (20 samples):")
print(pd.DataFrame(ref).round(1).to_string(index=False))
print("\nFraction of successive decoded windows whose estimate jumps by more than 90 degrees (20 samples):")
print(dec[dec.window == 20].pivot(index="ensemble", columns="trial", values="change_gt_90").round(3).to_string())
Chance level: absolute error uniform on 0-180 degrees has median and mean 90.

Window of 20 samples (666 ms):
               decoded                 mean_abs_err              median_abs_err              
trial            RA_ar   RA_rm     SA2        RA_ar RA_rm    SA2          RA_ar  RA_rm    SA2
ensemble cells                                                                               
0930R029 6      1380.0  1383.0  1488.0         85.4  46.5   44.3           80.6   26.7   23.2
1004R029 5      2343.0  2353.0  2136.0         87.0  60.2   50.1           84.6   34.9   31.9
1022R029 6      1600.0  1601.0  1430.0        109.0  89.7   82.2          115.0  103.0   84.5
1023R029 6      1495.0  1491.0  1633.0         86.7  80.0   41.4           87.1   74.7   25.8
1026R157 5      2237.0  2253.0  2321.0         92.8  80.4  113.5           95.2   71.3  135.3
1117R157 5      2104.0  2117.0  2313.0         85.0  82.4   94.0           80.5   77.8  102.1
1121R157 6      2172.0  2183.0  1044.0         83.7  92.6  105.3           79.7   94.7  120.1
  median_abs_err: stable2 below arena in 4 of 7, below room in 4 of 7; room below arena in 6 of 7
  mean_abs_err: stable2 below arena in 4 of 7, below room in 4 of 7; room below arena in 6 of 7

Window of 4 samples (133 ms):
               decoded                 mean_abs_err               median_abs_err              
trial            RA_ar   RA_rm     SA2        RA_ar  RA_rm    SA2          RA_ar  RA_rm    SA2
ensemble cells                                                                                
0930R029 6      3018.0  3042.0  3397.0         83.7   36.9   32.4           79.5   18.5   17.0
1004R029 5      6943.0  7034.0  5574.0         84.9   64.1   49.8           80.8   41.0   36.0
1022R029 6      2456.0  2476.0  2165.0        112.7   78.8   77.6          119.7   85.2   81.8
1023R029 6      2693.0  2674.0  3033.0         85.7   78.4   34.4           85.7   73.3   22.5
1026R157 5      8547.0  8767.0  7187.0         92.5   81.1  103.3           93.5   74.0  129.3
1117R157 5      7737.0  7861.0  7796.0         84.6   86.4   93.7           82.0   83.0   97.7
1121R157 6      6913.0  7021.0  3583.0         88.7  105.3  114.6           89.5  111.0  135.0
  median_abs_err: stable2 below arena in 4 of 7, below room in 4 of 7; room below arena in 5 of 7
  mean_abs_err: stable2 below arena in 4 of 7, below room in 4 of 7; room below arena in 5 of 7

Reference: decoding the second half of stable1 from its first half (20 samples):
ensemble  first half -> second half of stable1, median abs err  mean
0930R029                                                  27.5  54.6
1004R029                                                  30.9  56.9
1022R029                                                  23.9  35.6
1023R029                                                  23.2  40.5
1026R157                                                 116.4 102.6
1117R157                                                  65.0  75.3
1121R157                                                  79.9  84.8

Fraction of successive decoded windows whose estimate jumps by more than 90 degrees (20 samples):
trial     RA_ar  RA_rm    SA2
ensemble                     
0930R029  0.217  0.216  0.202
1004R029  0.312  0.311  0.191
1022R029  0.119  0.119  0.225
1023R029  0.169  0.170  0.137
1026R157  0.216  0.215  0.147
1117R157  0.288  0.288  0.192
1121R157  0.236  0.236  0.201

Result: reproduced, resting on the claims file's assumption of a majority. Seven sessions hold at least five head-direction units. With 20-sample windows the stable2 error is below the arena-frame error in 4 of 7 ensembles and below the room-frame error in 4 of 7, by the median and by the mean absolute error, and the same counts hold with 4-sample windows. Stable2 decoding is close to or worse than chance (90 degrees) in 1026R157, 1117R157 and 1121R157 (median 102 to 135 degrees), where decoding the second half of stable1 from its first half is also poor (65 to 116 degrees), so these ensembles carry little decodable direction. The room frame is decoded better than the arena frame in 6 of 7.

figs2-frame-preference¶

During rotation, frame-specific directional discharge alternated between signaling room and arena direction; four of seven ensembles showed an overall room preference and two of seven an arena preference.

Idir per cell and 133 ms interval (4 samples) of the rotating trial, in room and in arena directions; ΔIdir the room sum over cells minus the arena sum. Readings named by the criterion: direction bins of 10 or 45 degrees; probabilities from the rotating trial itself or from stable1; the SD of the 2 SD rule from the ensemble's ΔIdir series or from its stable1 Idir sum; the no-preference margin, the two probabilities within a factor of 2, or both below 0.05.

In [16]:
IDIR = {}
for bins in [10, 45]:
    for src in ["rotating", "stable1"]:
        for s, cells in ENS.items():
            n_ra = min(len(data[c]["RA_rm"]["d"]) for c in cells)
            d_rm, c_ra = hd20.ensemble_windows(data, cells, "RA_rm", 4)
            d_ar, _ = hd20.ensemble_windows(data, cells, "RA_ar", 4)
            d_s1, c_s1 = hd20.ensemble_windows(data, cells, "SA1", 4)
            room = np.zeros(len(d_rm))
            arena = np.zeros(len(d_rm))
            s1 = np.zeros(len(d_s1))
            for i in range(len(cells)):
                if src == "rotating":
                    room += hd20.idir(c_ra[i], d_rm, c_ra[i], d_rm, bins)
                    arena += hd20.idir(c_ra[i], d_ar, c_ra[i], d_ar, bins)
                else:
                    room += hd20.idir(c_ra[i], d_rm, c_s1[i], d_s1, bins)
                    arena += hd20.idir(c_ra[i], d_ar, c_s1[i], d_s1, bins)
                s1 += hd20.idir(c_s1[i], d_s1, c_s1[i], d_s1, bins)
            IDIR[(bins, src, s)] = {"room": room, "arena": arena, "delta": room - arena, "s1": s1,
                                    "d_rm": d_rm, "d_ar": d_ar}
In [17]:
pref_rows = []
for (bins, src, s), v in IDIR.items():
    dl = v["delta"][~np.isnan(v["delta"])]
    for sd_name, sd in [("delta series", np.std(dl)), ("stable1 Idir", np.nanstd(v["s1"]))]:
        p_room, p_arena = np.mean(dl > 2 * sd), np.mean(dl < -2 * sd)
        pref_rows.append({"bins": bins, "probabilities": src, "sd": sd_name, "ensemble": s,
                          "intervals": len(dl), "p_room": p_room, "p_arena": p_arena})
pr = pd.DataFrame(pref_rows)


def label(r, margin):
    hi, lo = max(r.p_room, r.p_arena), min(r.p_room, r.p_arena)
    if margin == "factor 2" and (lo > 0 and hi / lo < 2 or hi == 0):
        return "none"
    if margin == "both < 0.05" and hi < 0.05:
        return "none"
    return "room" if r.p_room > r.p_arena else ("arena" if r.p_arena > r.p_room else "none")


summ = []
for margin in ["factor 2", "both < 0.05"]:
    pr[margin] = pr.apply(lambda r: label(r, margin), axis=1)
    for key, g in pr.groupby(["bins", "probabilities", "sd"]):
        summ.append({"bins": key[0], "probabilities": key[1], "sd": key[2], "margin": margin,
                     "room": int((g[margin] == "room").sum()), "arena": int((g[margin] == "arena").sum()),
                     "none": int((g[margin] == "none").sum())})
summ = pd.DataFrame(summ)
summ["matches 4 and 2"] = (summ.room == 4) & (summ.arena == 2)
summ["room > arena"] = summ.room > summ.arena
print(summ.to_string(index=False))
print("\nReadings giving 4 room and 2 arena:", int(summ["matches 4 and 2"].sum()), "of", len(summ),
      "; readings with more room- than arena-preferring ensembles:", int(summ["room > arena"].sum()))
for b_ in [10, 45]:
    print(f"\nPer ensemble, {b_} degree bins, rotating-trial probabilities:")
    print(pr[(pr.bins == b_) & (pr.probabilities == "rotating")].round(3).to_string(index=False))
 bins probabilities           sd      margin  room  arena  none  matches 4 and 2  room > arena
   10      rotating delta series    factor 2     3      1     3            False          True
   10      rotating stable1 Idir    factor 2     4      0     3            False          True
   10       stable1 delta series    factor 2     2      0     5            False          True
   10       stable1 stable1 Idir    factor 2     0      0     7            False         False
   45      rotating delta series    factor 2     3      1     3            False          True
   45      rotating stable1 Idir    factor 2     3      0     4            False          True
   45       stable1 delta series    factor 2     3      0     4            False          True
   45       stable1 stable1 Idir    factor 2     1      0     6            False          True
   10      rotating delta series both < 0.05     3      1     3            False          True
   10      rotating stable1 Idir both < 0.05     3      1     3            False          True
   10       stable1 delta series both < 0.05     0      0     7            False         False
   10       stable1 stable1 Idir both < 0.05     5      1     1            False          True
   45      rotating delta series both < 0.05     4      2     1             True          True
   45      rotating stable1 Idir both < 0.05     4      0     3            False          True
   45       stable1 delta series both < 0.05     1      0     6            False          True
   45       stable1 stable1 Idir both < 0.05     5      1     1            False          True

Readings giving 4 room and 2 arena: 1 of 16 ; readings with more room- than arena-preferring ensembles: 14

Per ensemble, 10 degree bins, rotating-trial probabilities:
 bins probabilities           sd ensemble  intervals  p_room  p_arena factor 2 both < 0.05
   10      rotating delta series 0930R029      12650   0.302    0.000     room        room
   10      rotating stable1 Idir 0930R029      12650   0.269    0.000     room        room
   10      rotating delta series 1004R029      12734   0.280    0.000     room        room
   10      rotating stable1 Idir 1004R029      12734   0.229    0.000     room        room
   10      rotating delta series 1022R029      12428   0.149    0.000     room        room
   10      rotating stable1 Idir 1022R029      12428   0.115    0.000     room        room
   10      rotating delta series 1023R029      11867   0.003    0.135    arena       arena
   10      rotating stable1 Idir 1023R029      11867   0.000    0.000     none        none
   10      rotating delta series 1026R157      12363   0.031    0.027     none        none
   10      rotating stable1 Idir 1026R157      12363   0.001    0.000     room        none
   10      rotating delta series 1117R157      12239   0.028    0.038     none        none
   10      rotating stable1 Idir 1117R157      12239   0.025    0.028     none        none
   10      rotating delta series 1121R157      12184   0.025    0.046     none        none
   10      rotating stable1 Idir 1121R157      12184   0.083    0.133     none       arena

Per ensemble, 45 degree bins, rotating-trial probabilities:
 bins probabilities           sd ensemble  intervals  p_room  p_arena factor 2 both < 0.05
   45      rotating delta series 0930R029      12650   0.605    0.000     room        room
   45      rotating stable1 Idir 0930R029      12650   0.175    0.000     room        room
   45      rotating delta series 1004R029      12734   0.291    0.000     room        room
   45      rotating stable1 Idir 1004R029      12734   0.227    0.000     room        room
   45      rotating delta series 1022R029      12428   0.199    0.000     room        room
   45      rotating stable1 Idir 1022R029      12428   0.121    0.000     room        room
   45      rotating delta series 1023R029      11867   0.000    0.367    arena       arena
   45      rotating stable1 Idir 1023R029      11867   0.000    0.000     none        none
   45      rotating delta series 1026R157      12363   0.033    0.021     none        none
   45      rotating stable1 Idir 1026R157      12363   0.000    0.000     none        none
   45      rotating delta series 1117R157      12239   0.054    0.030     none        room
   45      rotating stable1 Idir 1117R157      12239   0.028    0.016     none        none
   45      rotating delta series 1121R157      12184   0.041    0.061     none       arena
   45      rotating stable1 Idir 1121R157      12184   0.071    0.063     none        room

Result: reproduced under one reading of sixteen. The counts of 4 room- and 2 arena-preferring ensembles are found with 45 degree bins, probabilities from the rotating trial, the SD of the ΔIdir series and the "both below 0.05" margin. Under that reading the room-preferring ensembles are 0930R029, 1004R029, 1022R029 and 1117R157 (p above 2 SD 0.605, 0.291, 0.199 and 0.054 against 0.000, 0.000, 0.000 and 0.030 below) and the arena-preferring 1023R029 (0.000 against 0.367) and 1121R157 (0.041 against 0.061); two of the six labels rest on differences of 0.02 to 0.03. The other 15 readings give 0 to 5 room-preferring and 0 to 1 arena-preferring ensembles; 14 of 16 give more room- than arena-preferring ensembles, which is the claim's partial form. The outcome rests on the choice of reading, which the paper does not fix.

fig2c-proximity-anticorrelation¶

The rat's relative proximity to one shock zone versus the other is anti-correlated with frame-specific directional information ... (mean r = -0.141 ± 0.029, all p < 0.0001) and for ΔIdir (r = -0.18, p < 0.05, in the exemplar).

Relative proximity at each 133 ms interval from the mean tracked position in room coordinates (distance to the room zone) and in arena coordinates (distance to the arena zone); zone geometry from the tracker headers (data check). Readings (a) (d_arena - d_room) / (d_arena + d_room), (b) d_arena - d_room, positive when nearer the room zone. Pearson r of the room Idir sum with proximity and of the arena Idir sum with minus proximity (14 values), and of ΔIdir with proximity; under each Idir reading of figs2. The paper does not say how the distance to a zone is measured, so three are run: to the zone's centre, to its nearest point (0 inside the zone), and the angle about the arena centre between the rat and the zone's centre direction.

In [18]:
def interval_xy(x, n, w=4):
    nw = n // w
    px = x["x"][: nw * w].astype(float).reshape(nw, w)
    py = x["y"][: nw * w].astype(float).reshape(nw, w)
    ok = ~((px == 0) & (py == 0))
    with np.errstate(invalid="ignore"):
        return np.where(ok, px, 0).sum(1) / ok.sum(1), np.where(ok, py, 0).sum(1) / ok.sum(1)


def zone_distance(x, y, z_, kind):
    """Distance (pixels, or degrees for 'angle') from positions to a sector zone (centre angle, width,
    inner, outer radius; angles counted with y up): to its centre, to its nearest point (0 inside),
    or the angle about the arena centre between the position and the zone's centre direction."""
    dx, dy = x - 127.5, -(y - 127.5)
    if kind == "centre":
        cx, cy = zone_xy(z_)
        return np.hypot(x - cx, y - cy)
    th = np.rad2deg(np.arctan2(dy, dx)) % 360
    if kind == "angle":
        return hd20.circ_absdiff(th, z_[0])
    r = np.hypot(dx, dy)
    inside = hd20.circ_absdiff(th, z_[0]) <= z_[1] / 2
    d_in = np.maximum.reduce([z_[2] - r, r - z_[3], np.zeros_like(r)])
    d_edge = []
    for phi in np.deg2rad([z_[0] - z_[1] / 2, z_[0] + z_[1] / 2]):
        t = np.clip(dx * np.cos(phi) + dy * np.sin(phi), z_[2], z_[3])   # nearest point on the edge segment
        d_edge.append(np.hypot(dx - t * np.cos(phi), dy - t * np.sin(phi)))
    return np.where(inside, d_in, np.minimum(*d_edge))


PROX = {}
for s, cells in ENS.items():
    n = min(len(data[c]["RA_rm"]["d"]) for c in cells)
    rx, ry = interval_xy(data[cells[0]]["RA_rm"], n)
    ax_, ay_ = interval_xy(data[cells[0]]["RA_ar"], n)
    for kind in ["centre", "edge", "angle"]:
        d_room = zone_distance(rx, ry, zones[s]["room"], kind)
        d_arena = zone_distance(ax_, ay_, zones[s]["arena"], kind)
        with np.errstate(invalid="ignore", divide="ignore"):
            PROX[(s, kind, "a")] = np.where(d_arena + d_room > 0, (d_arena - d_room) / (d_arena + d_room), 0.0)
        PROX[(s, kind, "b")] = d_arena - d_room
rows = []
for (bins, src, s), v in IDIR.items():
    for kind in ["centre", "edge", "angle"]:
        for pr_name in ["a", "b"]:
            prox = PROX[(s, kind, pr_name)]
            for name, y, sign in [("room Idir", v["room"], 1), ("arena Idir", v["arena"], -1), ("delta Idir", v["delta"], 1)]:
                ok = ~np.isnan(y) & ~np.isnan(prox)
                r_, p_ = stats.pearsonr(y[ok], sign * prox[ok])
                rows.append({"bins": bins, "probabilities": src, "distance": kind, "proximity": pr_name, "ensemble": s,
                             "series": name, "r": r_, "p": p_, "n": int(ok.sum())})
cor = pd.DataFrame(rows)
KEYS = ["bins", "probabilities", "distance", "proximity"]
fs_ = cor[cor.series != "delta Idir"].assign(neg_sig=lambda x: (x.r < 0) & (x.p < 1e-4))
g = fs_.groupby(KEYS, sort=False).agg(mean_r=("r", "mean"), sem_r=("r", "sem"), n_neg=("r", lambda r: int((r < 0).sum())),
                                      n=("r", "size"), n_neg_sig=("neg_sig", "sum")).reset_index()
dg = cor[cor.series == "delta Idir"].assign(neg05=lambda x: (x.r < 0) & (x.p < 0.05)).groupby(KEYS, sort=False).agg(
    delta_mean_r=("r", "mean"), delta_n_neg_p05=("neg05", "sum")).reset_index()
g = g.merge(dg)
g["mean within -0.141 +/- 0.029"] = (g.mean_r - -0.141).abs() <= 0.029
g["mean within -0.132 +/- 0.024"] = (g.mean_r - -0.132).abs() <= 0.024
g["all 14 negative, p < 1e-4"] = g.n_neg_sig == 14
print("Frame-specific Idir against relative proximity, 7 ensembles x 2 frames; distance to the zone's centre,")
print("its nearest point (edge) or the angle about the arena centre to the zone's centre direction:")
print(g.round(4).to_string(index=False))
print("\nReadings with the mean within either tolerance:", int((g["mean within -0.141 +/- 0.029"] | g["mean within -0.132 +/- 0.024"]).sum()),
      "of", len(g), "; with all 14 negative at p < 1e-4:", int(g["all 14 negative, p < 1e-4"].sum()),
      "; mean r from %.3f to %.3f" % (g.mean_r.min(), g.mean_r.max()))
print("\nPer ensemble, 10 degree bins, rotating-trial probabilities, proximity (a), each distance:")
print(cor[(cor.bins == 10) & (cor.probabilities == "rotating") & (cor.proximity == "a")]
      .pivot(index="ensemble", columns=["distance", "series"], values="r").round(3).to_string())
print("Proximity (a) range, distance to centre: %.2f to %.2f" % (
    np.nanmin(np.concatenate([v for k, v in PROX.items() if k[1:] == ("centre", "a")])),
    np.nanmax(np.concatenate([v for k, v in PROX.items() if k[1:] == ("centre", "a")]))))
Frame-specific Idir against relative proximity, 7 ensembles x 2 frames; distance to the zone's centre,
its nearest point (edge) or the angle about the arena centre to the zone's centre direction:
 bins probabilities distance proximity  mean_r  sem_r  n_neg  n  n_neg_sig  delta_mean_r  delta_n_neg_p05  mean within -0.141 +/- 0.029  mean within -0.132 +/- 0.024  all 14 negative, p < 1e-4
   10      rotating   centre         a -0.0698 0.0210     12 14         10       -0.0913                5                         False                         False                      False
   10      rotating   centre         b -0.0829 0.0234     12 14          9       -0.1090                5                         False                         False                      False
   10      rotating     edge         a -0.0605 0.0206     11 14         10       -0.0789                4                         False                         False                      False
   10      rotating     edge         b -0.0813 0.0236     12 14          9       -0.1071                5                         False                         False                      False
   10      rotating    angle         a -0.0635 0.0238     11 14         11       -0.0813                4                         False                         False                      False
   10      rotating    angle         b -0.0719 0.0262     11 14         10       -0.0933                5                         False                         False                      False
   10       stable1   centre         a -0.0729 0.0308     11 14          9       -0.1035                5                         False                         False                      False
   10       stable1   centre         b -0.0762 0.0367     10 14          8       -0.1070                4                         False                         False                      False
   10       stable1     edge         a -0.0684 0.0271     11 14          7       -0.0972                5                         False                         False                      False
   10       stable1     edge         b -0.0763 0.0366     10 14          8       -0.1068                4                         False                         False                      False
   10       stable1    angle         a -0.0758 0.0278     11 14          8       -0.1059                5                         False                         False                      False
   10       stable1    angle         b -0.0774 0.0322     11 14          8       -0.1063                4                         False                         False                      False
   45      rotating   centre         a -0.0516 0.0273     11 14          7       -0.0546                4                         False                         False                      False
   45      rotating   centre         b -0.0657 0.0288     11 14          9       -0.0727                5                         False                         False                      False
   45      rotating     edge         a -0.0425 0.0276     10 14          7       -0.0431                4                         False                         False                      False
   45      rotating     edge         b -0.0643 0.0295     11 14          9       -0.0713                5                         False                         False                      False
   45      rotating    angle         a -0.0433 0.0302      9 14          7       -0.0404                4                         False                         False                      False
   45      rotating    angle         b -0.0532 0.0324     10 14          8       -0.0545                4                         False                         False                      False
   45       stable1   centre         a -0.0846 0.0303     11 14         10       -0.1264                6                         False                         False                      False
   45       stable1   centre         b -0.0869 0.0366     11 14         10       -0.1282                5                         False                         False                      False
   45       stable1     edge         a -0.0805 0.0265     11 14         11       -0.1205                6                         False                         False                      False
   45       stable1     edge         b -0.0871 0.0363     11 14         10       -0.1283                5                         False                         False                      False
   45       stable1    angle         a -0.0830 0.0274     11 14         11       -0.1214                5                         False                         False                      False
   45       stable1    angle         b -0.0820 0.0319     11 14          9       -0.1173                5                         False                         False                      False

Readings with the mean within either tolerance: 0 of 24 ; with all 14 negative at p < 1e-4: 0 ; mean r from -0.087 to -0.043

Per ensemble, 10 degree bins, rotating-trial probabilities, proximity (a), each distance:
distance    centre                            edge                           angle                      
series   room Idir arena Idir delta Idir room Idir arena Idir delta Idir room Idir arena Idir delta Idir
ensemble                                                                                                
0930R029    -0.135     -0.118     -0.169    -0.115     -0.113     -0.149    -0.139     -0.134     -0.179
1004R029    -0.092     -0.198     -0.152    -0.093     -0.173     -0.144    -0.103     -0.206     -0.165
1022R029    -0.163     -0.095     -0.189    -0.144     -0.081     -0.166    -0.162     -0.074     -0.180
1023R029    -0.080     -0.108     -0.137    -0.072     -0.101     -0.126    -0.072     -0.087     -0.114
1026R157     0.091     -0.027      0.056     0.103     -0.037      0.058     0.115     -0.040      0.066
1117R157    -0.054      0.046     -0.013    -0.063      0.064     -0.008    -0.036      0.071      0.020
1121R157    -0.008     -0.036     -0.036     0.011     -0.031     -0.017     0.032     -0.051     -0.018
Proximity (a) range, distance to centre: -0.94 to 0.99

Result: partially reproduced. Under every reading (Idir bins and probabilities, proximity (a) or (b), and distance to the zone's centre, its nearest point or its direction) the mean correlation of frame-specific Idir with relative proximity is negative (-0.043 to -0.087 over 14 values), but none of the 24 is within -0.141 ± 0.029 or -0.132 ± 0.024; 9 to 12 of the 14 correlations are negative and 7 to 11 are negative with p < 0.0001, never all 14. ΔIdir correlates negatively with proximity in 4 to 6 of 7 ensembles at p < 0.05 (mean r -0.040 to -0.128). In the per-ensemble table (10 degree bins, rotating-trial probabilities, proximity (a)), 1026R157 and 1117R157 give positive or near-zero correlations (-0.063 to 0.115) under every distance. The way the distance is measured does not change the outcome.

figs3-no-head-direction-bias¶

The frame preference ΔIdir does not vary systematically with head direction; its polar distribution over head direction in either frame is not biased toward the shock zones and does not differ from uniform.

Per ensemble and frame, the mean ΔIdir in 10 degree head-direction bins, normalised to 0 to 1 (adding the magnitude of the minimum and dividing by the maximum, Figure S3 legend), and a Rayleigh test with the normalised values as weights; n is (a) the number of bins or (b) the sum of the weights. A claim of absence: reproduced when every test has p ≥ 0.05. Run under each Idir reading of figs2.

In [19]:
rows = []
for (bins, src, s), v in IDIR.items():
    for frame, dirs in [("room", v["d_rm"]), ("arena", v["d_ar"])]:
        ok = ~np.isnan(v["delta"]) & ~np.isnan(dirs)
        b = (dirs[ok] // 10).astype(int) % 36
        m = np.bincount(b, weights=v["delta"][ok], minlength=36) / np.maximum(np.bincount(b, minlength=36), 1)
        wts = m + abs(m.min())
        wts = wts / wts.max()
        r_, _ = hd20.resultant(wts)
        rows.append({"bins": bins, "probabilities": src, "ensemble": s, "frame": frame, "r": r_,
                     "p_n_bins": hd20.rayleigh_p(r_, 36), "p_n_weights": hd20.rayleigh_p(r_, wts.sum())})
s3 = pd.DataFrame(rows)
print(s3.groupby(["bins", "probabilities"]).agg(
    mean_r=("r", "mean"), sem_r=("r", "sem"), min_p_n_bins=("p_n_bins", "min"),
    n_sig_n_bins=("p_n_bins", lambda p: int((p < 0.05).sum())), min_p_n_weights=("p_n_weights", "min"),
    n_sig_n_weights=("p_n_weights", lambda p: int((p < 0.05).sum())), tests=("r", "size")).round(4).to_string())
print("\nPer ensemble and frame, 10 degree Idir bins, rotating-trial probabilities:")
print(s3[(s3.bins == 10) & (s3.probabilities == "rotating")].round(4).to_string(index=False))
                    mean_r   sem_r  min_p_n_bins  n_sig_n_bins  min_p_n_weights  n_sig_n_weights  tests
bins probabilities                                                                                     
10   rotating       0.1660  0.0229        0.0142             1           0.3493                0     14
     stable1        0.2338  0.0333        0.0001             4           0.0310                1     14
45   rotating       0.1801  0.0403        0.0000             3           0.0403                1     14
     stable1        0.2640  0.0397        0.0000             5           0.0133                3     14

Per ensemble and frame, 10 degree Idir bins, rotating-trial probabilities:
 bins probabilities ensemble frame      r  p_n_bins  p_n_weights
   10      rotating 0930R029  room 0.1064    0.6682       0.8167
   10      rotating 0930R029 arena 0.0657    0.8576       0.8927
   10      rotating 1004R029  room 0.1767    0.3273       0.6100
   10      rotating 1004R029 arena 0.1446    0.4739       0.6295
   10      rotating 1022R029  room 0.1635    0.3845       0.7584
   10      rotating 1022R029 arena 0.1886    0.2797       0.4988
   10      rotating 1023R029  room 0.2254    0.1609       0.4803
   10      rotating 1023R029 arena 0.2602    0.0867       0.3735
   10      rotating 1026R157  room 0.2262    0.1589       0.4859
   10      rotating 1026R157 arena 0.0540    0.9016       0.9412
   10      rotating 1117R157  room 0.2118    0.1997       0.6466
   10      rotating 1117R157 arena 0.0315    0.9654       0.9771
   10      rotating 1121R157  room 0.3410    0.0142       0.3493
   10      rotating 1121R157 arena 0.1281    0.5572       0.6764

Result: reproduced, resting on an assumption. With 10 degree Idir bins and probabilities from the rotating trial, the average Rayleigh r is 0.166 (expected 0.17 ± 0.02). With n the sum of the weights, none of the 14 tests is significant (smallest p = 0.35); with n the number of bins, one is (1121R157, room frame, p = 0.014). The other Idir readings give average r of 0.180 to 0.264 and 1 to 5 significant tests of 14. Under the Idir reading that reproduces figs2-frame-preference (45 degree bins, rotating-trial probabilities), 1 of 14 tests is significant even with n the sum of the weights (smallest p = 0.040), so the claim would not be reproduced under it. The outcome rests on taking n as the sum of the weights and on the 10 degree, rotating-trial Idir reading, the first the figs2 criterion lists.

fig3-hd-pair-correlations-preserved¶

The sub-second temporal coupling of head-direction cell pairs (Kendall correlations of spike counts at 40, 250 and 1000 ms) was maintained across stable1, rotating and stable2.

Spike counts in 40, 250 and 1000 ms bins over each trial (from the spike times), Kendall's tau for each simultaneously recorded pair, Fisher z-transformed; one-way ANOVA of the three conditions at each timescale. A claim of absence: reproduced when p ≥ 0.05 at all three.

In [20]:
PAIRS_HD = [(us[i], us[j]) for s, us in SESS.items() for i in range(len(us)) for j in range(i + 1, len(us))]
KT = []
for a, b in PAIRS_HD:
    for tr in ["SA1", "RA_rm", "SA2"]:
        t_end = min(len(data[a][tr]["d"]) / data[a][tr]["fs"], len(data[b][tr]["d"]) / data[b][tr]["fs"])
        for bs in [0.04, 0.25, 1.0]:
            ca = hd20.spike_count_series(data[a][tr], bs, t_end)
            cb = hd20.spike_count_series(data[b][tr], bs, t_end)
            tau = stats.kendalltau(ca, cb).statistic if ca.any() and cb.any() else np.nan
            KT.append({"pair": f"{a}|{b}", "trial": tr, "bin_ms": int(bs * 1000), "tau": tau})
KT = pd.DataFrame(KT)
KT["z"] = np.arctanh(KT.tau)
In [21]:
print("Pairs:", len(PAIRS_HD), "; pairs with an undefined tau (a cell without spikes):",
      KT[KT.tau.isna()].pair.nunique())
ft = pd.DataFrame([{"session": s, "trial": tr, "units": len(us), "first timestamps": len({data[u][tr]["first_ts"] for u in us})}
                   for s, us in SESS.items() for tr in ["SA1", "RA_rm", "SA2"]])
print("Session trials whose units differ in first timestamp (counts are binned from each unit's own):",
      int((ft["first timestamps"] > 1).sum()), "of", len(ft))
print("Units of session 1017R035 (whose stable2 header states 2000 samples/s and a first timestamp of 5):",
      SESS["1017R035"], "; its pairs:", [p_ for p_ in PAIRS_HD if "1017R035" in p_[0]])
for bs in [40, 250, 1000]:
    k = KT[KT.bin_ms == bs].pivot(index="pair", columns="trial", values="z")[["SA1", "RA_rm", "SA2"]]
    r = hd20.oneway({c: k[c] for c in k.columns})
    rm = hd20.rm_anova(k)
    r1 = stats.pearsonr(*k[["SA1", "RA_rm"]].dropna().T.values)[0]
    r2 = stats.pearsonr(*k[["SA1", "SA2"]].dropna().T.values)[0]
    print(f"{bs} ms: mean z {k.mean().round(4).to_dict()}; one-way ANOVA F({r['df1']}, {r['df2']}) = {r['F']:.3f}, "
          f"p = {r['p']:.3g}; RM ANOVA (variant) {hd20.fmt_anova(rm)}; Pearson r of tau stable1 vs rotating {r1:.3f}, "
          f"vs stable2 {r2:.3f}")
k = KT[KT.bin_ms == 250].pivot(index="pair", columns="trial", values="z")
k_rat = k.assign(rat=[p.split("|")[0].split("-")[0][4:] for p in k.index])
print("\nBy rat, mean z at 250 ms (pairs):")
print(k_rat.groupby("rat")[["SA1", "RA_rm", "SA2"]].mean().round(3).join(k_rat.groupby("rat").size().rename("pairs")).to_string())
print("z range (all timescales): %.3f to %.3f" % (KT.z.min(), KT.z.max()))
fig, ax = plt.subplots(1, 2, figsize=(7, 3))
ax[0].scatter(k.SA1, k.RA_rm, s=6)
ax[0].set_xlabel("z stable1, 250 ms")
ax[0].set_ylabel("z rotating")
ax[1].scatter(k.SA1, k.SA2, s=6)
ax[1].set_xlabel("z stable1, 250 ms")
ax[1].set_ylabel("z stable2")
plt.tight_layout()
plt.show()
Pairs: 146 ; pairs with an undefined tau (a cell without spikes): 0
Session trials whose units differ in first timestamp (counts are binned from each unit's own): 0 of 132
Units of session 1017R035 (whose stable2 header states 2000 samples/s and a first timestamp of 5): ['1017R035-P11C2'] ; its pairs: []
40 ms: mean z {'SA1': 0.03, 'RA_rm': 0.0299, 'SA2': 0.0248}; one-way ANOVA F(2, 435) = 0.098, p = 0.907; RM ANOVA (variant) F(1.79, 259.91) = 2.48, p = 0.0918 (n = 146, Mauchly p = 0.000142, GG applied, epsilon 0.90); Pearson r of tau stable1 vs rotating 0.967, vs stable2 0.973
250 ms: mean z {'SA1': 0.0583, 'RA_rm': 0.0564, 'SA2': 0.0442}; one-way ANOVA F(2, 435) = 0.329, p = 0.72; RM ANOVA (variant) F(1.85, 267.87) = 3.53, p = 0.0341 (n = 146, Mauchly p = 0.00202, GG applied, epsilon 0.92); Pearson r of tau stable1 vs rotating 0.891, vs stable2 0.936
1000 ms: mean z {'SA1': 0.0837, 'RA_rm': 0.0819, 'SA2': 0.0623}; one-way ANOVA F(2, 435) = 0.483, p = 0.617; RM ANOVA (variant) F(1.88, 272.37) = 3.44, p = 0.0363 (n = 146, Mauchly p = 0.00808, GG applied, epsilon 0.94); Pearson r of tau stable1 vs rotating 0.849, vs stable2 0.898

By rat, mean z at 250 ms (pairs):
        SA1  RA_rm    SA2  pairs
rat                             
R024  0.359  0.347  0.480      3
R027  0.044  0.016 -0.003      3
R029  0.012  0.008  0.001     68
R035  0.022  0.026  0.007     12
R039  0.046  0.055  0.035      4
R084  0.037  0.034  0.010      1
R157  0.124  0.110  0.093     45
R357  0.076  0.154  0.085      7
R521 -0.059  0.027 -0.015      1
R523 -0.042 -0.024 -0.038      1
R848  0.018  0.017  0.013      1
z range (all timescales): -0.206 to 1.279
No description has been provided for this image

Result: reproduced. The 146 simultaneously recorded head-direction pairs give one-way ANOVAs of F(2, 435) = 0.098, p = 0.907 at 40 ms, F = 0.329, p = 0.72 at 250 ms and F = 0.483, p = 0.617 at 1000 ms (the paper F(2, 420) = 0.097, 0.305 and 0.44). The units of every session share their first timestamp in every trial (0 of 132 session trials differ), so the counts of a pair are binned on a common origin; session 1017R035, whose stable2 header states a first timestamp of 5, holds one unit and forms no pair. The tau of a pair in stable1 correlates with its tau in the rotating trial at r = 0.85 to 0.97. A repeated-measures ANOVA (variant) finds small differences at 250 and 1000 ms (p = 0.034 and 0.036), with stable2 lowest.

figs4, figs5 and figs6¶

Blocked, data missing. Figure S4 uses all 556 MEC cell pairs and Figures S5 and S6 the 921 MEC cells modelled with the Gaussian process; the data set holds only the 115 head-direction cells (data check and cell-counts).

no-angular-velocity-tuning¶

The MEC head-direction cells showed no systematic tuning of firing rate to angular head velocity.

Angular velocity from the direction change between successive tracked samples (wrapped, degrees/s). Per unit, Pearson r of the spike count per sample with (a) signed and (b) unsigned angular velocity, in stable1 (the classification trial; other trials as variants). Reproduced when the fraction of units significant at p < 0.05 does not exceed chance by a binomial test at p < 0.05 (an assumption of the claims file). The parametric p-value treats successive samples as independent; as variants, the same r is tested against circular shifts of the spike counts by at least 30 s, and again after removing the head-direction bin means from both series.

In [22]:
rows = []
for tr in ["SA1", "RA_rm", "SA2"]:
    for u in U:
        x = data[u][tr]
        d = x["d"].astype(float)
        ok = (d[1:] <= 360) & (d[:-1] <= 360)
        av = ((d[1:] - d[:-1] + 180) % 360 - 180) * x["fs"]
        n = x["n"][1:].astype(float)
        av, n = av[ok], n[ok]
        ra, pa = stats.pearsonr(n, av)
        rb, pb = stats.pearsonr(n, np.abs(av))
        rows.append({"trial": tr, "unit": u, "r_signed": ra, "p_signed": pa, "r_unsigned": rb, "p_unsigned": pb})
av_t = pd.DataFrame(rows)
for tr, g in av_t.groupby("trial", sort=False):
    out = []
    for k in ["signed", "unsigned"]:
        nsig = int((g[f"p_{k}"] < 0.05).sum())
        pb = stats.binomtest(nsig, len(g), 0.05, alternative="greater").pvalue
        out.append(f"{k}: {nsig}/{len(g)} significant (binomial p = {pb:.2g}), median r {g[f'r_{k}'].median():.4f}, "
                   f"r range {g[f'r_{k}'].min():.3f} to {g[f'r_{k}'].max():.3f}, positive {int((g[f'r_{k}'] > 0).sum())}")
    print(tr, "|", " | ".join(out))
g = av_t[av_t.trial == "SA1"]
print("\nStable1, |r| above 0.05:", int((g.r_signed.abs() > 0.05).sum()), "signed,", int((g.r_unsigned.abs() > 0.05).sum()), "unsigned")
print("Angular velocity range (deg/s) in one unit's stable1: %.0f to %.0f" % (av.min(), av.max()))

# The parametric p-values above treat the ~54,000 samples as independent. Variant: the same Pearson r
# tested against circular shifts of the spike counts relative to angular velocity by at least 30 s
# (all such shifts, computed by FFT), which keeps the serial dependence of both series; and the same
# shift test after removing from both the mean in each 10 degree head-direction bin, so that a link of
# both to head direction cannot produce a correlation.
def shift_r(a, b):
    a, b = a - a.mean(), b - b.mean()
    c = np.fft.irfft(np.fft.rfft(a) * np.conj(np.fft.rfft(b)), len(a))
    return c / np.sqrt((a * a).sum() * (b * b).sum())


def by_bin(v, hb):
    return v - (np.bincount(hb, weights=v, minlength=36) / np.maximum(np.bincount(hb, minlength=36), 1))[hb]


rows = []
for u in U:
    x = data[u]["SA1"]
    d = x["d"].astype(float)
    ok = (d[1:] <= 360) & (d[:-1] <= 360)
    av = (((d[1:] - d[:-1] + 180) % 360 - 180) * x["fs"])[ok]
    n = x["n"][1:].astype(float)[ok]
    hb = (d[1:][ok] // 10).astype(int) % 36
    m = int(30 * x["fs"])
    for k, v in [("signed", av), ("unsigned", np.abs(av))]:
        for test, (a, b) in [("shift", (n, v)), ("shift, head direction removed", (by_bin(n, hb), by_bin(v, hb)))]:
            c = shift_r(a, b)
            null = np.abs(c[m:len(c) - m])
            rows.append({"unit": u, "velocity": k, "test": test, "r": c[0],
                         "p": (1 + (null >= abs(c[0])).sum()) / (1 + len(null))})
av_s = pd.DataFrame(rows)
print("\nStable1, shift tests (variants):")
for (k, test), g in av_s.groupby(["velocity", "test"]):
    nsig = int((g.p < 0.05).sum())
    print(f"  {k}, {test}: {nsig}/{len(g)} significant (binomial p = {stats.binomtest(nsig, len(g), 0.05, alternative='greater').pvalue:.2g}), "
          f"|r| at most {g.r.abs().max():.3f}, positive {int((g.r > 0).sum())}")
SA1 | signed: 12/115 significant (binomial p = 0.013), median r 0.0014, r range -0.028 to 0.020, positive 67 | unsigned: 49/115 significant (binomial p = 5.7e-33), median r -0.0008, r range -0.068 to 0.040, positive 53
RA_rm | signed: 13/115 significant (binomial p = 0.005), median r 0.0005, r range -0.040 to 0.013, positive 60 | unsigned: 28/115 significant (binomial p = 2.3e-12), median r -0.0014, r range -0.064 to 0.029, positive 51
SA2 | signed: 18/115 significant (binomial p = 1.7e-05), median r 0.0001, r range -0.025 to 0.021, positive 58 | unsigned: 43/115 significant (binomial p = 2.4e-26), median r 0.0003, r range -0.052 to 0.091, positive 59

Stable1, |r| above 0.05: 0 signed, 3 unsigned
Angular velocity range (deg/s) in one unit's stable1: -5404 to 5374
Stable1, shift tests (variants):
  signed, shift: 11/115 significant (binomial p = 0.029), |r| at most 0.028, positive 67
  signed, shift, head direction removed: 14/115 significant (binomial p = 0.0019), |r| at most 0.029, positive 66
  unsigned, shift: 41/115 significant (binomial p = 3e-24), |r| at most 0.068, positive 53
  unsigned, shift, head direction removed: 34/115 significant (binomial p = 1.8e-17), |r| at most 0.067, positive 49

Result: not reproduced, resting on the claims file's assumed test. In stable1, 12 of 115 units correlate with signed angular velocity at p < 0.05 (binomial p = 0.013 against 5%) and 49 of 115 with unsigned angular velocity (binomial p = 5.7e-33); the other trials give the same. Testing the same correlations against circular shifts of at least 30 s, which keeps the serial dependence of the samples, gives 11 of 115 (binomial p = 0.029) and 41 of 115 (p = 3e-24), and after removing the head-direction bin means from both series 14 of 115 (p = 0.0019) and 34 of 115 (p = 1.8e-17), so the excess does not come from treating the samples as independent. The correlations are small (|r| at most 0.029 signed and 0.068 unsigned), of both signs (49 to 53 of 115 positive for unsigned), and the angular velocities reach about 5400 degrees/s, which points to tracking noise in the direction. The criterion counts significant cells; the sizes of the correlations do not show tuning.

fig4-internal-tuning-preserved¶

Internally referenced directional tuning of head-direction cell pairs (tuning of one cell to head-direction displacement since the other's spikes) was preserved across stable1, rotating and stable2; neither its instability nor its change in preference differed between trials or from the two halves of stable1.

Internally referenced tuning as Spike_triggered_FR_curve.py computes it (helper internal_tuning), for each simultaneously recorded pair with the first-listed unit of the pair as cell 1 (the code labels pair i, j with i < j). Readings of the criterion: interval 5 s (main) or 30 s; cell 2 spikes before the cell 1 spike (the code; main) or after; normalisation (a) the Methods' division by the sum of the time offsets, a single number per curve, so the curve is the spike-difference histogram (main), (b) the code's division by the occupancy of each displacement; a variant, (b rescaled), scales the (b) curve to sum to its spike count, as the Krichevsky-Trofimov 0.5 otherwise swamps values far below 1. KLD and preferred-direction change between stable1 and stable2, the rotating room frame and the rotating arena frame, and between the halves of stable1. Pairs used: those with a defined curve (at least one cell 2 spike in the window) in every condition. Four tests: RM ANOVA over the three trial pairs for KLD and for preference change, and one-way ANOVA of the four groups for each. A claim of absence: reproduced when all four have p ≥ 0.05 under the main readings.

In [23]:
INTERVALS = [3, 4, 5, 10, 20, 30, 40, 50, 60, 300, 600]
t0 = time.time()
IT = {}
for a, b in PAIRS_HD:
    for side in ["before", "after"]:
        for cond in ["SA1", "RA_rm", "RA_ar", "SA2", "half1", "half2"]:
            tr = cond if not cond.startswith("half") else "SA1"
            x, y = data[a][tr], data[b][tr]
            n = min(len(x["d"]), len(y["d"]))
            sl = slice(0, n)
            if cond == "half1":
                sl = slice(0, n // 2)
            elif cond == "half2":
                sl = slice(n // 2, n)
            wins = INTERVALS if not cond.startswith("half") else [5, 30]
            IT[(a, b, side, cond)] = hd20.internal_tuning(x["d"][sl], x["n"][sl], y["n"][sl], x["fs"], wins, side)
print(f"internally referenced tuning of {len(PAIRS_HD)} pairs computed in {time.time() - t0:.0f} s")


def it_curve(res, T, norm):
    c, o = res[T]["counts"], res[T]["occ"]
    if norm == "a":
        return c
    with np.errstate(invalid="ignore", divide="ignore"):
        b = np.where(o > 0, c / o, 0.0)
    if norm == "b":
        return b
    # variant (b rescaled): the occupancy-normalised curve scaled to sum to its spike count, so that
    # the Krichevsky-Trofimov 0.5 is added on the scale of counts, as the Methods' n_i are
    return b * c.sum() / b.sum() if b.sum() > 0 else b


IT_CENTRES = np.deg2rad(np.arange(36) * 10 - 180 + 5)
internally referenced tuning of 146 pairs computed in 266 s
In [24]:
fig4_rows = []
for T in [5, 30]:
    for side in ["before", "after"]:
        for norm in ["a", "b", "b rescaled"]:
            kl, pc, used = {}, {}, 0
            for a, b in PAIRS_HD:
                cv = {c: it_curve(IT[(a, b, side, c)], T, norm) for c in ["SA1", "RA_rm", "RA_ar", "SA2", "half1", "half2"]}
                cnt = {c: IT[(a, b, side, c)][T]["counts"].sum() for c in cv}
                if min(cnt.values()) == 0:
                    continue
                used += 1
                key = f"{a}|{b}"
                kl[key] = {"s1-s2": hd20.kld(cv["SA1"], cv["SA2"]), "s1-room": hd20.kld(cv["SA1"], cv["RA_rm"]),
                           "s1-arena": hd20.kld(cv["SA1"], cv["RA_ar"]), "halves": hd20.kld(cv["half1"], cv["half2"])}
                pk = {c: np.argmax(cv[c]) * 10 for c in cv}
                pc[key] = {"s1-s2": hd20.circ_absdiff(pk["SA1"], pk["SA2"]), "s1-room": hd20.circ_absdiff(pk["SA1"], pk["RA_rm"]),
                           "s1-arena": hd20.circ_absdiff(pk["SA1"], pk["RA_ar"]), "halves": hd20.circ_absdiff(pk["half1"], pk["half2"])}
            for mname, m in [("instability (KLD)", pd.DataFrame(kl).T), ("preference change", pd.DataFrame(pc).T.astype(float))]:
                r1 = hd20.rm_anova(m[["s1-s2", "s1-room", "s1-arena"]])
                r2 = hd20.oneway({c: m[c] for c in m.columns})
                fig4_rows.append({"T_s": T, "side": side, "norm": norm, "measure": mname, "pairs": used,
                                  "means": " ".join(f"{k} {v:.3g}" for k, v in m.mean().items()),
                                  "RM F": f"F({r1['df1']:.2f}, {r1['df2']:.2f}) = {r1['F']:.2f}", "RM p": r1["p"],
                                  "4-group F": f"F({r2['df1']}, {r2['df2']}) = {r2['F']:.2f}", "4-group p": r2["p"]})
f4 = pd.DataFrame(fig4_rows)
pd.set_option("display.max_colwidth", 120)
print(f4.to_string(index=False, formatters={"RM p": "{:.3g}".format, "4-group p": "{:.3g}".format}))
f4["all p >= 0.05"] = (f4["RM p"] >= 0.05) & (f4["4-group p"] >= 0.05)
print("\nReadings (interval, side, normalisation) with all four tests at p >= 0.05:")
print(f4.groupby(["T_s", "side", "norm"])["all p >= 0.05"].all().to_string())
main_kl = {}
for a, b in PAIRS_HD:
    cv = {c: it_curve(IT[(a, b, "before", c)], 5, "a") for c in ["SA1", "RA_rm", "RA_ar", "SA2", "half1", "half2"]}
    if min(v.sum() for v in cv.values()) == 0:
        continue
    main_kl[f"{a}|{b}"] = {"rat": a.split("-")[0][4:], "s1-s2": hd20.kld(cv["SA1"], cv["SA2"]),
                           "s1-room": hd20.kld(cv["SA1"], cv["RA_rm"]), "s1-arena": hd20.kld(cv["SA1"], cv["RA_ar"]),
                           "halves": hd20.kld(cv["half1"], cv["half2"])}
main_kl = pd.DataFrame(main_kl).T
print("\nBy rat, mean instability (KLD), main readings:")
print(main_kl.groupby("rat")[["s1-s2", "s1-room", "s1-arena", "halves"]].mean().astype(float).round(3)
      .join(main_kl.groupby("rat").size().rename("pairs")).to_string())
print("Pairs left out (no cell 2 spike in some condition's windows), 5 s before:",
      len(PAIRS_HD) - int(f4[(f4.T_s == 5) & (f4.side == "before")].pairs.iloc[0]))
 T_s   side       norm           measure  pairs                                                             means                    RM F     RM p         4-group F 4-group p
   5 before          a instability (KLD)    142             s1-s2 0.179 s1-room 0.207 s1-arena 0.148 halves 0.166 F(2.00, 282.00) = 10.20 5.29e-05  F(3, 564) = 3.76    0.0107
   5 before          a preference change    142                 s1-s2 19.9 s1-room 27.3 s1-arena 17.7 halves 18.6  F(2.00, 282.00) = 6.39  0.00193  F(3, 564) = 1.92     0.125
   5 before          b instability (KLD)    142     s1-s2 0.00105 s1-room 0.00108 s1-arena 0.00105 halves 0.00123  F(1.01, 142.98) = 0.01    0.916  F(3, 564) = 0.05     0.984
   5 before          b preference change    142                   s1-s2 78.1 s1-room 78.5 s1-arena 69 halves 65.4  F(1.80, 254.49) = 2.21    0.117  F(3, 564) = 2.12    0.0963
   5 before b rescaled instability (KLD)    142             s1-s2 0.262 s1-room 0.267 s1-arena 0.231 halves 0.252  F(1.79, 252.90) = 3.12   0.0516  F(3, 564) = 0.72     0.541
   5 before b rescaled preference change    142                   s1-s2 78.1 s1-room 78.5 s1-arena 69 halves 65.4  F(1.80, 254.49) = 2.21    0.117  F(3, 564) = 2.12    0.0963
   5  after          a instability (KLD)    140             s1-s2 0.187 s1-room 0.187 s1-arena 0.136 halves 0.165 F(1.84, 255.26) = 10.08 0.000104  F(3, 556) = 3.77    0.0107
   5  after          a preference change    140                 s1-s2 19.4 s1-room 19.1 s1-arena 17.7 halves 20.5  F(1.83, 254.92) = 0.27    0.742  F(3, 556) = 0.16     0.925
   5  after          b instability (KLD)    140  s1-s2 0.00127 s1-room 0.000726 s1-arena 0.000729 halves 0.000779  F(1.03, 143.80) = 7.32  0.00709  F(3, 556) = 1.52     0.209
   5  after          b preference change    140                   s1-s2 66.6 s1-room 69.9 s1-arena 67.9 halves 58  F(1.73, 240.61) = 0.18    0.801  F(3, 556) = 1.32     0.267
   5  after b rescaled instability (KLD)    140             s1-s2 0.265 s1-room 0.243 s1-arena 0.218 halves 0.239  F(1.83, 254.97) = 5.38  0.00646  F(3, 556) = 1.19     0.313
   5  after b rescaled preference change    140                   s1-s2 66.6 s1-room 69.9 s1-arena 67.9 halves 58  F(1.73, 240.61) = 0.18    0.801  F(3, 556) = 1.32     0.267
  30 before          a instability (KLD)    146             s1-s2 0.167 s1-room 0.157 s1-arena 0.232 halves 0.122  F(1.48, 214.79) = 8.84 0.000843  F(3, 580) = 7.29  8.31e-05
  30 before          a preference change    146                 s1-s2 33.8 s1-room 39.7 s1-arena 45.4 halves 26.4  F(1.89, 274.26) = 3.54   0.0328  F(3, 580) = 4.21   0.00586
  30 before          b instability (KLD)    146 s1-s2 0.000575 s1-room 0.000302 s1-arena 0.000498 halves 0.000411  F(1.80, 261.53) = 3.49   0.0364  F(3, 580) = 0.84     0.474
  30 before          b preference change    146                 s1-s2 63.4 s1-room 64.9 s1-arena 77.7 halves 45.1  F(2.00, 290.00) = 3.31   0.0378  F(3, 580) = 9.93  2.15e-06
  30 before b rescaled instability (KLD)    146            s1-s2 0.132 s1-room 0.126 s1-arena 0.213 halves 0.0978 F(1.52, 220.98) = 14.32 1.42e-05  F(3, 580) = 9.16  6.26e-06
  30 before b rescaled preference change    146                 s1-s2 63.4 s1-room 64.9 s1-arena 77.7 halves 45.1  F(2.00, 290.00) = 3.31   0.0378  F(3, 580) = 9.93  2.15e-06
  30  after          a instability (KLD)    146              s1-s2 0.16 s1-room 0.157 s1-arena 0.246 halves 0.134 F(1.63, 236.83) = 16.36 1.74e-06  F(3, 580) = 8.99  7.88e-06
  30  after          a preference change    146                 s1-s2 33.4 s1-room 32.3 s1-arena 48.2 halves 30.1  F(2.00, 290.00) = 8.94  0.00017  F(3, 580) = 4.27   0.00541
  30  after          b instability (KLD)    146 s1-s2 0.000529 s1-room 0.000291 s1-arena 0.000373 halves 0.000335  F(1.15, 166.53) = 4.84   0.0244  F(3, 580) = 1.29     0.278
  30  after          b preference change    146                 s1-s2 59.7 s1-room 62.6 s1-arena 91.4 halves 47.8 F(2.00, 290.00) = 18.40    3e-08 F(3, 580) = 18.58  1.61e-11
  30  after b rescaled instability (KLD)    146              s1-s2 0.124 s1-room 0.123 s1-arena 0.21 halves 0.106 F(1.60, 231.38) = 23.84 1.09e-08  F(3, 580) = 9.30  5.14e-06
  30  after b rescaled preference change    146                 s1-s2 59.7 s1-room 62.6 s1-arena 91.4 halves 47.8 F(2.00, 290.00) = 18.40    3e-08 F(3, 580) = 18.58  1.61e-11

Readings (interval, side, normalisation) with all four tests at p >= 0.05:
T_s  side    norm      
5    after   a             False
             b             False
             b rescaled    False
     before  a             False
             b              True
             b rescaled     True
30   after   a             False
             b             False
             b rescaled    False
     before  a             False
             b             False
             b rescaled    False

By rat, mean instability (KLD), main readings:
      s1-s2  s1-room  s1-arena  halves  pairs
rat                                          
R024  0.677    0.235     0.247   0.204      3
R027  0.031    0.079     0.095   0.058      3
R029  0.206    0.259     0.175   0.159     64
R035  0.192    0.146     0.133   0.081     12
R039  0.140    0.114     0.099   0.232      4
R084  0.279    0.028     0.036   0.138      1
R157  0.127    0.175     0.118   0.189     45
R357  0.097    0.131     0.081   0.210      7
R521  0.151    0.434     0.444   0.302      1
R523  0.138    0.200     0.119   0.094      1
R848  0.256    0.238     0.279   0.189      1
Pairs left out (no cell 2 spike in some condition's windows), 5 s before: 4

Result: not reproduced. Under the main readings (5 s, cell 2 spikes before, the Methods' normalisation; 142 pairs with a defined curve in every condition) instability differs across the trial pairs (F(2.00, 282.00) = 10.20, p = 5.3e-05) and in the four-group ANOVA (F(3, 564) = 3.76, p = 0.011), and the preference change differs across trial pairs (F = 6.39, p = 0.0019); only the four-group ANOVA of the preference change has p ≥ 0.05 (p = 0.125). The differences are small (mean KLD 0.148 to 0.207 against 0.166 for the halves). Of the eight readings only one (5 s, before, the code's occupancy normalisation) has all four tests at p ≥ 0.05. Its KLD is near 0 (means about 0.001) because the Krichevsky-Trofimov 0.5 swamps the normalised values; rescaled to the spike count (variant), that reading still has all four tests at p ≥ 0.05, with the instability test close to the threshold (p = 0.052).

fig4c-arena-registration-short-lived¶

The strength of internally referenced directional tuning is similar in all conditions and frames for intervals up to 10 s, but beyond 10 s it falls in the rotating arena frame (20 to 60 s; stable1 = stable2 = rotating room > rotating arena) and at 300 to 600 s also in the rotating room frame (stable1 = stable2 > rotating room > rotating arena).

Strength is the Rayleigh vector length of the internally referenced curve (claims file), per pair, condition and maximum interval (3 to 600 s), with cell 2 spikes before the cell 1 spike (the code) or after it, and normalisation (a) (main) or (b), the readings of fig4-internal-tuning-preserved. One-way ANOVA of the four conditions at each interval with Tukey-Kramer HSD (between groups, as the criterion's one-way ANOVA). The last lines check each part of the criterion under each reading.

In [25]:
COND4 = {"SA1": "stable1", "SA2": "stable2", "RA_rm": "rotating room", "RA_ar": "rotating arena"}
F4C = []
for side, norm in [("before", "a"), ("before", "b"), ("after", "a"), ("after", "b")]:
    print(f"\nCell 2 spikes {side} the cell 1 spike, normalisation ({norm}):")
    rows = []
    for T in INTERVALS:
        st = {}
        for a, b in PAIRS_HD:
            res = {c: IT[(a, b, side, c)] for c in COND4}
            if min(res[c][T]["counts"].sum() for c in COND4) == 0:
                continue
            st[f"{a}|{b}"] = {COND4[c]: hd20.resultant(it_curve(res[c], T, norm), IT_CENTRES)[0] for c in COND4}
        st = pd.DataFrame(st).T
        r = hd20.oneway({c: st[c] for c in st.columns})
        tk = hd20.tukey(st)
        sig = tk[tk["p-adj"] < 0.05]
        order = "; ".join(f"{g1} vs {g2} {d:+.3f}" for g1, g2, d in zip(sig.group1, sig.group2, sig.meandiff))
        arena_low = all(((tk.group1 == "rotating arena") & (tk.group2 == o) | (tk.group2 == "rotating arena") & (tk.group1 == o))
                        .pipe(lambda m: bool((m & tk.reject & (st[o].mean() > st["rotating arena"].mean())).any()))
                        for o in ["stable1", "stable2", "rotating room"])
        room_low = all(((tk.group1 == "rotating room") & (tk.group2 == o) | (tk.group2 == "rotating room") & (tk.group1 == o))
                       .pipe(lambda m: bool((m & tk.reject & (st[o].mean() > st["rotating room"].mean())).any()))
                       for o in ["stable1", "stable2"])
        F4C.append({"side": side, "norm": norm, "T_s": T, "p": r["p"], "arena below other three": arena_low,
                    "room below both stable": room_low})
        rows.append({"T_s": T, "pairs": len(st), **{c: round(st[c].mean(), 3) for c in st.columns},
                     "F": f"F({r['df1']}, {r['df2']}) = {r['F']:.2f}", "p": r["p"],
                     "Tukey p<0.05 (group2 - group1)": order or "none"})
    t = pd.DataFrame(rows)
    print(t.to_string(index=False, formatters={"p": "{:.3g}".format}))
F4C = pd.DataFrame(F4C)
print("\nCriterion, per reading: ANOVA p >= 0.05 at 3 to 10 s, p < 0.05 beyond, arena frame below the other three")
print("(Tukey p < 0.05) at 20 to 60 s, room frame below both stable trials at 300 and 600 s:")
for (side, norm), g in F4C.groupby(["side", "norm"], sort=False):
    short, long_ = g[g.T_s <= 10], g[g.T_s > 10]
    mid, far = g[g.T_s.between(20, 60)], g[g.T_s >= 300]
    print(f"  {side}, ({norm}): p >= 0.05 up to 10 s {bool((short.p >= 0.05).all())} "
          f"(intervals failing {list(short[short.p < 0.05].T_s)}); p < 0.05 beyond {bool((long_.p < 0.05).all())}; "
          f"arena below others at 20-60 s {bool(mid['arena below other three'].all())} "
          f"(at {list(mid[mid['arena below other three']].T_s)}); room below stable at 300-600 s {bool(far['room below both stable'].all())}; "
          f"arena below others beyond 10 s at {list(long_[long_['arena below other three']].T_s)}")
Cell 2 spikes before the cell 1 spike, normalisation (a):
 T_s  pairs  stable1  stable2  rotating room  rotating arena                 F        p                                                                                                                                               Tukey p<0.05 (group2 - group1)
   3    141    0.748    0.780          0.775           0.785  F(3, 560) = 1.91    0.126                                                                                                                                                                         none
   4    142    0.709    0.743          0.736           0.748  F(3, 564) = 1.68     0.17                                                                                                                                                                         none
   5    144    0.671    0.709          0.698           0.717  F(3, 572) = 2.00    0.113                                                                                                                                                                         none
  10    145    0.555    0.610          0.540           0.587  F(3, 576) = 3.92  0.00862                                                                                                                                              rotating room vs stable2 +0.070
  20    146    0.466    0.519          0.381           0.437 F(3, 580) = 11.66 1.98e-07                                                                           rotating arena vs stable2 +0.082; rotating room vs stable1 +0.086; rotating room vs stable2 +0.139
  30    146    0.433    0.480          0.302           0.348 F(3, 580) = 23.24 3.22e-14                                         rotating arena vs stable1 +0.085; rotating arena vs stable2 +0.132; rotating room vs stable1 +0.132; rotating room vs stable2 +0.178
  40    146    0.410    0.452          0.267           0.281 F(3, 580) = 32.31 2.52e-19                                         rotating arena vs stable1 +0.129; rotating arena vs stable2 +0.171; rotating room vs stable1 +0.143; rotating room vs stable2 +0.185
  50    146    0.396    0.435          0.250           0.234 F(3, 580) = 39.09 5.09e-23                                         rotating arena vs stable1 +0.162; rotating arena vs stable2 +0.201; rotating room vs stable1 +0.146; rotating room vs stable2 +0.185
  60    146    0.386    0.422          0.245           0.210 F(3, 580) = 42.07  1.3e-24                                         rotating arena vs stable1 +0.176; rotating arena vs stable2 +0.212; rotating room vs stable1 +0.141; rotating room vs stable2 +0.177
 300    146    0.344    0.327          0.212           0.142 F(3, 580) = 34.29 2.05e-20 rotating arena vs rotating room +0.070; rotating arena vs stable1 +0.202; rotating arena vs stable2 +0.186; rotating room vs stable1 +0.132; rotating room vs stable2 +0.116
 600    146    0.334    0.310          0.207           0.126 F(3, 580) = 32.22 2.82e-19 rotating arena vs rotating room +0.080; rotating arena vs stable1 +0.208; rotating arena vs stable2 +0.184; rotating room vs stable1 +0.128; rotating room vs stable2 +0.103

Cell 2 spikes before the cell 1 spike, normalisation (b):
 T_s  pairs  stable1  stable2  rotating room  rotating arena                 F        p                                                                                                                                               Tukey p<0.05 (group2 - group1)
   3    141    0.354    0.363          0.348           0.394  F(3, 560) = 0.78    0.503                                                                                                                                                                         none
   4    142    0.344    0.340          0.332           0.380  F(3, 564) = 0.89    0.446                                                                                                                                                                         none
   5    144    0.356    0.339          0.325           0.377  F(3, 572) = 0.98      0.4                                                                                                                                                                         none
  10    145    0.354    0.336          0.282           0.335  F(3, 576) = 2.12   0.0961                                                                                                                                                                         none
  20    146    0.335    0.311          0.234           0.273  F(3, 580) = 5.24  0.00141                                                                                                             rotating room vs stable1 +0.101; rotating room vs stable2 +0.077
  30    146    0.322    0.297          0.212           0.225  F(3, 580) = 8.68 1.21e-05                                         rotating arena vs stable1 +0.097; rotating arena vs stable2 +0.072; rotating room vs stable1 +0.111; rotating room vs stable2 +0.086
  40    146    0.313    0.284          0.204           0.180 F(3, 580) = 13.28 2.16e-08                                         rotating arena vs stable1 +0.134; rotating arena vs stable2 +0.104; rotating room vs stable1 +0.109; rotating room vs stable2 +0.080
  50    146    0.309    0.272          0.199           0.142 F(3, 580) = 19.09 8.11e-12                                         rotating arena vs stable1 +0.167; rotating arena vs stable2 +0.130; rotating room vs stable1 +0.110; rotating room vs stable2 +0.073
  60    146    0.307    0.267          0.195           0.112 F(3, 580) = 26.90 2.65e-16 rotating arena vs rotating room +0.083; rotating arena vs stable1 +0.195; rotating arena vs stable2 +0.155; rotating room vs stable1 +0.112; rotating room vs stable2 +0.072
 300    146    0.297    0.242          0.181           0.074 F(3, 580) = 36.13 2.05e-21 rotating arena vs rotating room +0.107; rotating arena vs stable1 +0.223; rotating arena vs stable2 +0.168; rotating room vs stable1 +0.115; rotating room vs stable2 +0.061
 600    146    0.294    0.233          0.178           0.066 F(3, 580) = 36.74 9.55e-22       rotating arena vs rotating room +0.112; rotating arena vs stable1 +0.228; rotating arena vs stable2 +0.166; rotating room vs stable1 +0.116; stable1 vs stable2 -0.062

Cell 2 spikes after the cell 1 spike, normalisation (a):
 T_s  pairs  stable1  stable2  rotating room  rotating arena                 F        p                                                                                                                                               Tukey p<0.05 (group2 - group1)
   3    141    0.760    0.800          0.771           0.778  F(3, 560) = 2.20   0.0869                                                                                                                                                                         none
   4    141    0.712    0.759          0.724           0.742  F(3, 560) = 2.54   0.0556                                                                                                                                                                         none
   5    142    0.680    0.733          0.680           0.706  F(3, 564) = 3.32   0.0196                                                                                                                   rotating room vs stable2 +0.053; stable1 vs stable2 +0.052
  10    145    0.590    0.621          0.538           0.587  F(3, 576) = 4.87  0.00238                                                                                                                                              rotating room vs stable2 +0.084
  20    146    0.504    0.530          0.380           0.450 F(3, 580) = 15.75 7.39e-10                                   rotating arena vs rotating room -0.070; rotating arena vs stable2 +0.080; rotating room vs stable1 +0.124; rotating room vs stable2 +0.150
  30    146    0.458    0.478          0.310           0.363 F(3, 580) = 23.92 1.31e-14                                         rotating arena vs stable1 +0.095; rotating arena vs stable2 +0.115; rotating room vs stable1 +0.148; rotating room vs stable2 +0.168
  40    146    0.427    0.441          0.276           0.291 F(3, 580) = 29.42 1.02e-17                                         rotating arena vs stable1 +0.136; rotating arena vs stable2 +0.150; rotating room vs stable1 +0.151; rotating room vs stable2 +0.166
  50    146    0.408    0.421          0.250           0.234 F(3, 580) = 38.33 1.31e-22                                         rotating arena vs stable1 +0.173; rotating arena vs stable2 +0.187; rotating room vs stable1 +0.158; rotating room vs stable2 +0.171
  60    146    0.395    0.407          0.244           0.202 F(3, 580) = 42.74  5.8e-25                                         rotating arena vs stable1 +0.193; rotating arena vs stable2 +0.205; rotating room vs stable1 +0.151; rotating room vs stable2 +0.163
 300    146    0.345    0.330          0.210           0.147 F(3, 580) = 32.55 1.87e-19 rotating arena vs rotating room +0.062; rotating arena vs stable1 +0.198; rotating arena vs stable2 +0.182; rotating room vs stable1 +0.135; rotating room vs stable2 +0.120
 600    146    0.336    0.315          0.199           0.130 F(3, 580) = 32.76 1.42e-19 rotating arena vs rotating room +0.069; rotating arena vs stable1 +0.206; rotating arena vs stable2 +0.185; rotating room vs stable1 +0.137; rotating room vs stable2 +0.116

Cell 2 spikes after the cell 1 spike, normalisation (b):
 T_s  pairs  stable1  stable2  rotating room  rotating arena                 F        p                                                                                                                                               Tukey p<0.05 (group2 - group1)
   3    141    0.370    0.383          0.334           0.388  F(3, 560) = 1.11    0.343                                                                                                                                                                         none
   4    141    0.363    0.360          0.313           0.370  F(3, 560) = 1.34     0.26                                                                                                                                                                         none
   5    142    0.361    0.346          0.300           0.355  F(3, 564) = 1.58    0.194                                                                                                                                                                         none
  10    145    0.350    0.318          0.252           0.310  F(3, 576) = 3.86  0.00942                                                                                                                                              rotating room vs stable1 +0.098
  20    146    0.331    0.286          0.222           0.256  F(3, 580) = 5.91 0.000561                                                                                                            rotating arena vs stable1 +0.074; rotating room vs stable1 +0.108
  30    146    0.316    0.272          0.213           0.216  F(3, 580) = 8.09 2.74e-05                                                                                                            rotating arena vs stable1 +0.100; rotating room vs stable1 +0.103
  40    146    0.303    0.265          0.208           0.181 F(3, 580) = 10.88 5.85e-07                                                                          rotating arena vs stable1 +0.123; rotating arena vs stable2 +0.084; rotating room vs stable1 +0.095
  50    146    0.302    0.261          0.200           0.140 F(3, 580) = 19.16 7.37e-12 rotating arena vs rotating room +0.060; rotating arena vs stable1 +0.162; rotating arena vs stable2 +0.121; rotating room vs stable1 +0.102; rotating room vs stable2 +0.060
  60    146    0.297    0.259          0.197           0.115 F(3, 580) = 24.71 4.67e-15 rotating arena vs rotating room +0.082; rotating arena vs stable1 +0.181; rotating arena vs stable2 +0.143; rotating room vs stable1 +0.100; rotating room vs stable2 +0.062
 300    146    0.290    0.244          0.183           0.076 F(3, 580) = 33.91 3.32e-20 rotating arena vs rotating room +0.106; rotating arena vs stable1 +0.214; rotating arena vs stable2 +0.168; rotating room vs stable1 +0.107; rotating room vs stable2 +0.061
 600    146    0.286    0.235          0.177           0.068 F(3, 580) = 34.49  1.6e-20                                  rotating arena vs rotating room +0.109; rotating arena vs stable1 +0.217; rotating arena vs stable2 +0.167; rotating room vs stable1 +0.109

Criterion, per reading: ANOVA p >= 0.05 at 3 to 10 s, p < 0.05 beyond, arena frame below the other three
(Tukey p < 0.05) at 20 to 60 s, room frame below both stable trials at 300 and 600 s:
  before, (a): p >= 0.05 up to 10 s False (intervals failing [10]); p < 0.05 beyond True; arena below others at 20-60 s False (at []); room below stable at 300-600 s True; arena below others beyond 10 s at [300, 600]
  before, (b): p >= 0.05 up to 10 s True (intervals failing []); p < 0.05 beyond True; arena below others at 20-60 s False (at [60]); room below stable at 300-600 s False; arena below others beyond 10 s at [60, 300, 600]
  after, (a): p >= 0.05 up to 10 s False (intervals failing [5, 10]); p < 0.05 beyond True; arena below others at 20-60 s False (at []); room below stable at 300-600 s True; arena below others beyond 10 s at [300, 600]
  after, (b): p >= 0.05 up to 10 s False (intervals failing [10]); p < 0.05 beyond True; arena below others at 20-60 s False (at [50, 60]); room below stable at 300-600 s False; arena below others beyond 10 s at [50, 60, 300, 600]

Result: not reproduced, resting on a reading of the criterion. No reading of window side and normalisation gives the claimed pattern. The arena frame is below all three other conditions at none of 20 to 60 s with the Methods' normalisation (either side) and only at 60 s (cell 2 before) or at 50 and 60 s (after) with the code's normalisation. With the Methods' normalisation the room frame falls as far as or further than the arena frame at 20 to 50 s (before, 40 s: 0.267 and 0.281 against 0.410 and 0.452). With the code's normalisation the room frame falls first (with cell 2 before, below both stable trials at 20 s, where the arena frame is not), and the arena frame is lower from 40 s (0.180 against 0.204 before, 0.181 against 0.208 after) and below the room frame from 50 s (after) or 60 s (before). The conditions differ already at 10 s in three readings (p = 0.0086, 0.0024 and 0.0094) and at 5 s with cell 2 after (p = 0.020); only the code's normalisation with cell 2 before has no difference up to 10 s (p = 0.096 to 0.50). Every reading differs at every interval beyond 10 s (p below 0.002), and at 300 and 600 s the arena frame is below the three others. The room frame is below both stable trials at 300 and 600 s with the Methods' normalisation, as reported, but not at 600 s with the code's. The criterion's partial form reads "the arena frame falls below the others beyond 10 s and not before, but the room-frame order at long intervals is not found". The code's normalisation with cell 2 before meets those words: no difference up to 10 s, differences at every later interval, the arena frame below the other three at 60, 300 and 600 s, and the room frame not below stable2 at 600 s. The outcome here takes "beyond 10 s" as from 20 s, the arena-frame part of the full criterion (20 to 60 s), since the partial form names only the room-frame order as missing and the paper writes that arena-frame tuning "abruptly decreased after 10 s" while registration to the room frame was kept. Under that reading the partial form is not met in any reading of window side and normalisation, and the outcome is not reproduced. This is an assumption: read as any interval beyond 10 s, the outcome would be partially reproduced.

fig5-error-inhomogeneous¶

The angular distribution of decoding error is inhomogeneous in the room frame (resultant r = 0.589) and the arena frame (r = 0.653) and differs from the distribution of sampled head directions, which is itself biased in both frames (r = 0.147 room, r = 0.378 arena).

Decoding error during rotation (decoder of fig2, 20 samples main, 4 samples variant) in each frame. A reader amended the criterion on 2026-11-13 in answer to a question (questions/park-2019.yaml): it now names three readings of what the error distribution is a distribution over, (i) the mean absolute error in each 10 degree bin of the rat's head direction, taken as weights over the bin centres, (ii) the head directions of the windows decoded within 15, 30 or 45 degrees, (iii) the signed error angles, the only reading run before the answer. For each: the resultant length and Rayleigh test (n the number of decoded windows for (i), as the paper's z = 236.36 at r = 0.589 implies about 680; n = 36 bins shown as a variant), Kuiper's test against the sampled head directions of the same windows (for (i), the error weights against the head-direction occupancy over the same bins, hd20.kuiper_binned, an assumption as the paper does not say how the test was applied), and the resultant length of the sampled head directions. Pooling readings: (a) all seven ensembles pooled, (b) the exemplar ensemble with the most cells (four ensembles tie at six cells; each is shown), (c) each ensemble apart, with the median r.

In [26]:
def circ_r(deg):
    deg = np.asarray(deg, float)
    deg = deg[~np.isnan(deg)]
    return float(abs(np.exp(1j * np.deg2rad(deg)).mean())), len(deg)


def error_distributions(err, hd):
    """The three distribution readings of the criterion, each as (r, n for Rayleigh, Kuiper V, Kuiper p)."""
    out = {}
    b = (hd // 10).astype(int) % 36
    occ = np.bincount(b, minlength=36)
    # (i) mean absolute error per 10 degree head-direction bin, as weights over the bin centres
    mean_err = np.bincount(b, weights=np.abs(err), minlength=36) / np.maximum(occ, 1)
    r, _ = hd20.resultant(mean_err)
    out["(i) error by head direction"] = (r, len(err), *hd20.kuiper_binned(mean_err, occ, len(err), len(err)),
                                          int((occ > 0).sum()))
    # (ii) head directions of windows decoded within 15, 30 or 45 degrees
    for thr in [15, 30, 45]:
        acc = hd[np.abs(err) <= thr]
        r, n = circ_r(acc)
        out[f"(ii) head direction, error <= {thr}"] = (r, n, *hd20.kuiper_two_sample(acc, hd), None)
    # (iii) the signed error angles
    r, n = circ_r(err)
    out["(iii) signed error"] = (r, n, *hd20.kuiper_two_sample(err, hd), None)
    return out


rows = []
for w in [20, 4]:
    for s in list(ENS) + ["pooled"]:
        ss = list(ENS) if s == "pooled" else [s]
        recs = {}
        for tr, fr in [("RA_rm", "room"), ("RA_ar", "arena")]:
            err = np.concatenate([DEC[(w, e, tr)]["err"] for e in ss])
            hd = np.concatenate([DEC[(w, e, tr)]["dir"] for e in ss])
            rh, nh = circ_r(hd)
            ok = ~np.isnan(err) & ~np.isnan(hd)
            for reading, (r, n, v, pk, nbins) in error_distributions(err[ok], hd[ok]).items():
                rec = recs.setdefault(reading, {"window": w, "ensemble": s, "reading": reading})
                rec.update({f"{fr} err r": r, f"{fr} err n": n, f"{fr} err p": hd20.rayleigh_p(r, n),
                            f"{fr} kuiper V": v, f"{fr} kuiper p": pk, f"{fr} hd r": rh, f"{fr} hd n": nh,
                            f"{fr} hd p": hd20.rayleigh_p(rh, nh)})
                if nbins is not None:
                    rec[f"{fr} err p (n = bins)"] = hd20.rayleigh_p(r, nbins)
        rows.extend(recs.values())
f5 = pd.DataFrame(rows)
EXP5 = {"room err r": 0.589, "arena err r": 0.653, "room hd r": 0.147, "arena hd r": 0.378}
f5["r within tolerance"] = [sum(abs(r[k] - v) <= 0.1 * v for k, v in EXP5.items()) for _, r in f5.iterrows()]
f5["tests hold"] = (f5[["room err p", "arena err p", "room kuiper p", "arena kuiper p", "room hd p", "arena hd p"]]
                    < 0.05).all(axis=1)
cols = ["window", "ensemble", "reading", "room err r", "room err n", "room err p", "room kuiper p",
        "arena err r", "arena err n", "arena err p", "arena kuiper p", "room hd r", "room hd p", "arena hd r",
        "arena hd p", "tests hold", "r within tolerance"]
fmt = lambda v: f"{v:.3g}"
for w in [20, 4]:
    print(f"Window of {w} samples ({w / 30.02 * 1000:.0f} ms):")
    print(f5[f5.window == w][cols].drop(columns="window").to_string(index=False, float_format=fmt))
    print()
print("Reading (i) with n the number of occupied bins (36) in place of the number of windows:")
print(f5[f5.reading.str.startswith("(i)")][["window", "ensemble", "room err r", "room err p (n = bins)", "arena err r",
                                             "arena err p (n = bins)"]].to_string(index=False, float_format=fmt))
print("\nReading (c), median over ensembles of r:")
print(f5[f5.ensemble != "pooled"].groupby(["window", "reading"])[list(EXP5)].median().round(3).to_string())
print("\nExpected:", EXP5, "(tolerance 10%)")
best = f5.sort_values(["tests hold", "r within tolerance"], ascending=False)
print("\nCombinations (window, pooling, reading) where every test holds:", int(f5["tests hold"].sum()), "of", len(f5),
      "; with all four r within tolerance:", int((f5["tests hold"] & (f5["r within tolerance"] == 4)).sum()))
print("Most r within tolerance where every test holds:",
      int(f5[f5["tests hold"]]["r within tolerance"].max()) if f5["tests hold"].any() else None)
print(f5.groupby(["window", "tests hold"])["r within tolerance"].value_counts().unstack(fill_value=0).to_string())
# the sample sizes the paper's Rayleigh z values imply (z = n r^2), compared with the counts here
from itertools import combinations
IMPL = {"room error": 236.36 / 0.589**2, "arena error": 289.63 / 0.653**2, "room head direction": 230.6 / 0.147**2,
        "arena head direction": 153.2 / 0.378**2}
print("\nn implied by the paper's z values:", {k: round(v) for k, v in IMPL.items()})
cnt = []
for w in [20, 4]:
    for s in ENS:
        cnt.append({"window": w, "ensemble": s, **{f"{tr} {k}": int(np.sum(~np.isnan(DEC[(w, s, tr)][f]))) for tr in ["RA_rm", "RA_ar"]
                                                    for k, f in [("decoded", "err"), ("tracked", "dir")]}})
cnt = pd.DataFrame(cnt)
print(cnt.to_string(index=False))
near_ = lambda v, t: abs(v - t) <= 0.1 * t
hits = []
for w in [20, 4]:
    c = cnt[cnt.window == w].set_index("ensemble")
    for k in range(1, len(ENS) + 1):
        for sub in combinations(ENS, k):
            tot = c.loc[list(sub)].sum()
            for col, target in [("RA_rm decoded", "room error"), ("RA_ar decoded", "arena error"),
                                ("RA_rm tracked", "room head direction"), ("RA_ar tracked", "arena head direction")]:
                if near_(tot[col], IMPL[target]):
                    hits.append({"window": w, "ensembles": len(sub), "count": col, "n": int(tot[col]), "implied": target})
hits = pd.DataFrame(hits)
print("\nSubsets of the seven ensembles whose summed counts are within 10% of an implied n:")
print(hits.groupby(["window", "count", "implied"]).size().rename("subsets").to_string() if len(hits) else "none")
both = f5[f5["room err n"].apply(lambda v: near_(v, IMPL["room error"])) & f5["arena err n"].apply(lambda v: near_(v, IMPL["arena error"]))]
print("Rows above with both error n within 10% of the implied 681 and 679:", len(both))
print("Rows with the room error n within 10% of 681:")
print(f5[f5["room err n"].apply(lambda v: near_(v, IMPL["room error"]))][["window", "ensemble", "reading", "room err n", "arena err n"]]
      .to_string(index=False))
Window of 20 samples (666 ms):
ensemble                          reading  room err r  room err n  room err p  room kuiper p  arena err r  arena err n  arena err p  arena kuiper p  room hd r  room hd p  arena hd r  arena hd p  tests hold  r within tolerance
0930R029      (i) error by head direction       0.329        1383    9.06e-68      8.31e-114         0.13         1380     7.37e-11        2.14e-56     0.0718   9.93e-07        0.36   4.18e-156        True                   1
0930R029 (ii) head direction, error <= 15       0.604         489    5.43e-87        9.8e-13        0.484          100     1.63e-11          0.0111     0.0718   9.93e-07        0.36   4.18e-156        True                   2
0930R029 (ii) head direction, error <= 30       0.555         747   1.57e-109       7.32e-10        0.543          221     1.91e-31        0.000881     0.0718   9.93e-07        0.36   4.18e-156        True                   2
0930R029 (ii) head direction, error <= 45       0.519         915   2.75e-116       1.48e-07        0.568          372     8.76e-58        1.96e-07     0.0718   9.93e-07        0.36   4.18e-156        True                   1
0930R029               (iii) signed error        0.56        1383   1.33e-206       1.79e-88        0.144         1380     3.27e-13        6.52e-57     0.0718   9.93e-07        0.36   4.18e-156        True                   2
1004R029      (i) error by head direction      0.0299        2353       0.122       6.52e-11       0.0812         2343      1.9e-07        5.11e-75     0.0873   1.32e-09       0.388   2.47e-182       False                   1
1004R029 (ii) head direction, error <= 15       0.158         662    6.37e-08       3.34e-06         0.46          220     4.24e-22        4.27e-06     0.0873   1.32e-09       0.388   2.47e-182        True                   1
1004R029 (ii) head direction, error <= 30       0.134        1088    2.62e-09       1.02e-05        0.464          432     1.49e-43         1.5e-08     0.0873   1.32e-09       0.388   2.47e-182        True                   1
1004R029 (ii) head direction, error <= 45       0.111        1333    7.15e-08        0.00162        0.452          621     7.57e-59        4.22e-08     0.0873   1.32e-09       0.388   2.47e-182        True                   1
1004R029               (iii) signed error        0.38        2353   3.58e-154      7.08e-163       0.0554         2343     0.000741        4.58e-70     0.0873   1.32e-09       0.388   2.47e-182        True                   1
1022R029      (i) error by head direction       0.426        1601   2.96e-133        7.3e-27        0.284         1600     4.96e-58        2.46e-14      0.278   1.68e-92        0.44   5.73e-238        True                   0
1022R029 (ii) head direction, error <= 15       0.298         208    6.49e-09       6.19e-34        0.397           34      0.00407        1.53e-09      0.278   1.68e-92        0.44   5.73e-238        True                   0
1022R029 (ii) head direction, error <= 30       0.317         387    5.32e-18       2.25e-48        0.546          111     2.69e-16         1.7e-39      0.278   1.68e-92        0.44   5.73e-238        True                   0
1022R029 (ii) head direction, error <= 45       0.328         471    2.64e-23       3.08e-55        0.462          181     1.74e-18        6.58e-55      0.278   1.68e-92        0.44   5.73e-238        True                   0
1022R029               (iii) signed error       0.273        1601    1.51e-53       7.84e-54         0.35         1600     1.32e-88       5.59e-150      0.278   1.68e-92        0.44   5.73e-238        True                   0
1023R029      (i) error by head direction       0.147        1491    9.78e-15        3.1e-49       0.0878         1495     9.62e-06        2.21e-57      0.278   1.59e-92       0.336    4.4e-136        True                   0
1023R029 (ii) head direction, error <= 15       0.596         168    2.18e-29       3.54e-12         0.44          119     3.09e-11           0.092      0.278   1.59e-92       0.336    4.4e-136       False                   1
1023R029 (ii) head direction, error <= 30       0.564         320    5.34e-49       4.38e-13        0.483          249     1.56e-27         0.00454      0.278   1.59e-92       0.336    4.4e-136        True                   1
1023R029 (ii) head direction, error <= 45       0.505         475     3.7e-57       9.14e-09        0.462          368     6.61e-37        0.000596      0.278   1.59e-92       0.336    4.4e-136        True                   0
1023R029               (iii) signed error       0.139        1491    3.18e-13       4.12e-32        0.043         1495        0.063        5.17e-47      0.278   1.59e-92       0.336    4.4e-136       False                   0
1026R157      (i) error by head direction       0.208        2253     1.2e-43       2.31e-41        0.221         2237     5.87e-49        4.82e-09     0.0895   4.87e-10        0.14     2.4e-23        True                   0
1026R157 (ii) head direction, error <= 15       0.423         259     7.7e-22       8.39e-26        0.251          218     8.71e-07        1.19e-21     0.0895   4.87e-10        0.14     2.4e-23        True                   0
1026R157 (ii) head direction, error <= 30       0.413         512    2.51e-40       1.05e-31        0.372          386     9.33e-25        2.15e-42     0.0895   4.87e-10        0.14     2.4e-23        True                   0
1026R157 (ii) head direction, error <= 45       0.413         749    8.81e-59       5.99e-31        0.383          537     2.96e-36        5.01e-52     0.0895   4.87e-10        0.14     2.4e-23        True                   0
1026R157               (iii) signed error       0.135        2253    1.46e-18        8.2e-15       0.0992         2237     2.66e-10        1.36e-05     0.0895   4.87e-10        0.14     2.4e-23        True                   0
1117R157      (i) error by head direction      0.0799        2117    1.31e-06       2.16e-37       0.0826         2104     5.64e-07        1.58e-16      0.174   1.52e-35       0.143    3.55e-24        True                   0
1117R157 (ii) head direction, error <= 15       0.348         217    1.79e-12       0.000474        0.249          180     1.24e-05        1.18e-06      0.174   1.52e-35       0.143    3.55e-24        True                   0
1117R157 (ii) head direction, error <= 30       0.318         413    2.33e-19       8.79e-05        0.118          364      0.00597        1.51e-11      0.174   1.52e-35       0.143    3.55e-24        True                   0
1117R157 (ii) head direction, error <= 45       0.303         627    2.97e-26       0.000101        0.139          580     1.41e-05        5.87e-08      0.174   1.52e-35       0.143    3.55e-24        True                   0
1117R157               (iii) signed error       0.119        2117    1.03e-13       7.72e-13        0.101         2104      3.8e-10        1.28e-30      0.174   1.52e-35       0.143    3.55e-24        True                   0
1121R157      (i) error by head direction      0.0314        2183       0.115       2.64e-23       0.0753         2172     4.41e-06        8.68e-13      0.273   3.54e-88      0.0827    1.35e-08       False                   0
1121R157 (ii) head direction, error <= 15       0.261         186    2.55e-06       2.83e-05        0.213          203     9.33e-05        1.27e-09      0.273   3.54e-88      0.0827    1.35e-08        True                   0
1121R157 (ii) head direction, error <= 30       0.239         356    1.14e-09       1.39e-05        0.233          454      1.5e-11        3.87e-10      0.273   3.54e-88      0.0827    1.35e-08        True                   0
1121R157 (ii) head direction, error <= 45       0.224         519    3.33e-12       0.000158        0.216          675     1.38e-14        2.64e-06      0.273   3.54e-88      0.0827    1.35e-08        True                   0
1121R157               (iii) signed error      0.0496        2183     0.00469       1.41e-44        0.144         2172        3e-20         8.6e-07      0.273   3.54e-88      0.0827    1.35e-08        True                   0
  pooled      (i) error by head direction      0.0322       13381    9.05e-07       6.58e-17       0.0314        13331     1.91e-06       3.42e-128     0.0255   5.31e-06       0.264           0        True                   0
  pooled (ii) head direction, error <= 15       0.156        2189    6.45e-24       4.99e-19        0.183         1074     1.72e-16        8.83e-08     0.0255   5.31e-06       0.264           0        True                   0
  pooled (ii) head direction, error <= 30       0.129        3823    1.33e-28       2.35e-17         0.16         2217     1.28e-25        6.58e-18     0.0255   5.31e-06       0.264           0        True                   0
  pooled (ii) head direction, error <= 45       0.105        5089    2.76e-25       2.12e-12        0.179         3334     1.26e-47        8.29e-16     0.0255   5.31e-06       0.264           0        True                   0
  pooled               (iii) signed error       0.173       13381   4.15e-176      6.27e-116       0.0149        13331       0.0526       8.86e-170     0.0255   5.31e-06       0.264           0       False                   0

Window of 4 samples (133 ms):
ensemble                          reading  room err r  room err n  room err p  room kuiper p  arena err r  arena err n  arena err p  arena kuiper p  room hd r  room hd p  arena hd r  arena hd p  tests hold  r within tolerance
0930R029      (i) error by head direction       0.411        3042   6.77e-234              0        0.172         3018      7.4e-40       2.67e-172     0.0885   2.35e-44       0.366           0        True                   1
0930R029 (ii) head direction, error <= 15       0.711        1293           0       4.72e-40        0.536          206     1.53e-28        6.37e-13     0.0885   2.35e-44       0.366           0        True                   1
0930R029 (ii) head direction, error <= 30       0.679        2066           0       3.37e-23         0.56          423     9.33e-64        2.89e-19     0.0885   2.35e-44       0.366           0        True                   1
0930R029 (ii) head direction, error <= 45       0.659        2351           0        7.8e-13        0.571          682    8.52e-107        4.51e-27     0.0885   2.35e-44       0.366           0        True                   1
0930R029               (iii) signed error       0.676        3042           0         4e-318        0.238         3018     4.91e-76       9.46e-196     0.0885   2.35e-44       0.366           0        True                   1
1004R029      (i) error by head direction       0.127        7034    3.01e-50      2.81e-104       0.0796         6943     7.64e-20       1.65e-297     0.0923   6.34e-49        0.39           0        True                   1
1004R029 (ii) head direction, error <= 15        0.24        1667    5.58e-43       2.77e-54        0.573          718    3.65e-113        3.45e-45     0.0923   6.34e-49        0.39           0        True                   1
1004R029 (ii) head direction, error <= 30       0.247        2922    1.73e-79       1.61e-36        0.553         1389    5.73e-202        3.29e-41     0.0923   6.34e-49        0.39           0        True                   1
1004R029 (ii) head direction, error <= 45       0.251        3678   9.48e-103       7.78e-28        0.539         2005    5.43e-275        3.14e-33     0.0923   6.34e-49        0.39           0        True                   1
1004R029               (iii) signed error       0.332        7034           0      6.74e-308       0.0833         6943     1.06e-21       9.36e-319     0.0923   6.34e-49        0.39           0        True                   1
1022R029      (i) error by head direction       0.416        2476   2.59e-195       5.31e-79        0.272         2456     4.49e-81        1.24e-17      0.266          0       0.454           0        True                   0
1022R029 (ii) head direction, error <= 15       0.226         429    2.18e-10       6.72e-58        0.509           99     1.32e-12        3.37e-33      0.266          0       0.454           0        True                   0
1022R029 (ii) head direction, error <= 30       0.158         735    9.93e-09       7.39e-57        0.494          156     2.46e-18        3.25e-46      0.266          0       0.454           0        True                   0
1022R029 (ii) head direction, error <= 45       0.127         871    8.06e-07       1.43e-58        0.409          251     8.52e-20        8.01e-64      0.266          0       0.454           0        True                   0
1022R029               (iii) signed error       0.252        2476    5.32e-70      2.83e-122        0.348         2456    7.51e-134       6.73e-184      0.266          0       0.454           0        True                   0
1023R029      (i) error by head direction       0.204        2674    1.95e-49        1.9e-82        0.158         2693     2.93e-30       7.97e-149      0.266          0        0.33           0        True                   0
1023R029 (ii) head direction, error <= 15        0.61         294    1.56e-53       9.02e-21        0.535          232     6.78e-32        4.11e-10      0.266          0        0.33           0        True                   1
1023R029 (ii) head direction, error <= 30       0.602         586   3.69e-103        1.9e-26        0.548          459     7.69e-66        1.33e-23      0.266          0        0.33           0        True                   1
1023R029 (ii) head direction, error <= 45       0.577         850   7.53e-136       1.79e-30        0.578          689    1.03e-110        5.12e-27      0.266          0        0.33           0        True                   1
1023R029               (iii) signed error       0.167        2674    2.19e-33       1.52e-72       0.0919         2693     1.29e-10       3.03e-133      0.266          0        0.33           0        True                   0
1026R157      (i) error by head direction       0.196        8767   3.13e-148       3.3e-144        0.202         8547    3.25e-154        7.52e-40     0.0917   3.94e-47       0.142   4.32e-110        True                   0
1026R157 (ii) head direction, error <= 15       0.412        1030    2.48e-80      8.86e-101        0.208          791     1.03e-15        7.43e-81     0.0917   3.94e-47       0.142   4.32e-110        True                   0
1026R157 (ii) head direction, error <= 30       0.422        1979    3.8e-161      3.49e-131        0.272         1531      7.4e-51       4.39e-139     0.0917   3.94e-47       0.142   4.32e-110        True                   0
1026R157 (ii) head direction, error <= 45       0.407        2918   1.47e-219      3.52e-116        0.304         2095     5.84e-87       1.34e-157     0.0917   3.94e-47       0.142   4.32e-110        True                   0
1026R157               (iii) signed error       0.124        8767    3.33e-59       2.55e-58       0.0873         8547     4.77e-29        4.72e-39     0.0917   3.94e-47       0.142   4.32e-110        True                   0
1117R157      (i) error by head direction      0.0782        7861    1.25e-21      1.98e-167       0.0928         7737     1.04e-29        1.1e-114      0.167  1.79e-152       0.134    1.32e-96        True                   0
1117R157 (ii) head direction, error <= 15       0.342         783     8.2e-42       3.24e-19        0.367          735     2.35e-45        5.73e-56      0.167  1.79e-152       0.134    1.32e-96        True                   0
1117R157 (ii) head direction, error <= 30       0.323        1476    3.23e-69       2.01e-15        0.302         1410     5.51e-58        2.69e-46      0.167  1.79e-152       0.134    1.32e-96        True                   0
1117R157 (ii) head direction, error <= 45       0.314        2228    1.28e-98       9.99e-07        0.249         2151     8.94e-60        2.81e-34      0.167  1.79e-152       0.134    1.32e-96        True                   0
1117R157               (iii) signed error      0.0551        7861    4.12e-11       1.22e-92        0.106         7737     1.16e-38       9.99e-101      0.167  1.79e-152       0.134    1.32e-96        True                   0
1121R157      (i) error by head direction       0.182        7021   4.26e-102       4.58e-25        0.207         6913    2.13e-130       1.87e-142      0.277          0      0.0917    2.55e-45        True                   0
1121R157 (ii) head direction, error <= 15       0.139         327      0.0017       2.64e-29        0.529          594     1.18e-78        1.67e-99      0.277          0      0.0917    2.55e-45        True                   0
1121R157 (ii) head direction, error <= 30       0.138         650    4.27e-06       3.66e-52        0.549         1237    3.34e-177       3.93e-151      0.277          0      0.0917    2.55e-45        True                   0
1121R157 (ii) head direction, error <= 45        0.12         982    6.68e-07       1.36e-62        0.542         1835    9.06e-255       9.51e-147      0.277          0      0.0917    2.55e-45        True                   0
1121R157               (iii) signed error       0.211        7021   1.93e-137      3.37e-240        0.124         6913     2.98e-47        2.41e-11      0.277          0      0.0917    2.55e-45        True                   0
  pooled      (i) error by head direction      0.0506       38875    5.88e-44       1.5e-148       0.0208        38307     5.99e-08               0     0.0261   6.97e-27       0.267           0        True                   0
  pooled (ii) head direction, error <= 15       0.221        5823   1.47e-125          1e-91        0.283         3375    6.64e-121        1.61e-21     0.0261   6.97e-27       0.267           0        True                   0
  pooled (ii) head direction, error <= 30       0.204       10414    3.1e-191      1.26e-103         0.27         6605    9.62e-214        8.25e-14     0.0261   6.97e-27       0.267           0        True                   0
  pooled (ii) head direction, error <= 45       0.176       13878   2.41e-189       8.59e-77        0.266         9708    2.14e-303        1.85e-15     0.0261   6.97e-27       0.267           0        True                   0
  pooled               (iii) signed error       0.132       38875    1.7e-296      2.15e-172       0.0207        38307     7.52e-08               0     0.0261   6.97e-27       0.267           0        True                   0

Reading (i) with n the number of occupied bins (36) in place of the number of windows:
 window ensemble  room err r  room err p (n = bins)  arena err r  arena err p (n = bins)
     20 0930R029       0.329                  0.019         0.13                   0.549
     20 1004R029      0.0299                  0.969       0.0812                   0.791
     20 1022R029       0.426                0.00116        0.284                  0.0535
     20 1023R029       0.147                  0.464       0.0878                    0.76
     20 1026R157       0.208                  0.211        0.221                   0.172
     20 1117R157      0.0799                  0.797       0.0826                   0.784
     20 1121R157      0.0314                  0.965       0.0753                   0.817
     20   pooled      0.0322                  0.964       0.0314                   0.966
      4 0930R029       0.411                0.00191        0.172                   0.346
      4 1004R029       0.127                  0.562       0.0796                   0.798
      4 1022R029       0.416                0.00163        0.272                   0.069
      4 1023R029       0.204                  0.226        0.158                   0.408
      4 1026R157       0.196                  0.253        0.202                    0.23
      4 1117R157      0.0782                  0.805       0.0928                   0.736
      4 1121R157       0.182                  0.307        0.207                   0.216
      4   pooled      0.0506                  0.913       0.0208                   0.985

Reading (c), median over ensembles of r:
                                         room err r  arena err r  room hd r  arena hd r
window reading                                                                         
4      (i) error by head direction            0.196        0.172      0.167       0.330
       (ii) head direction, error <= 15       0.342        0.529      0.167       0.330
       (ii) head direction, error <= 30       0.323        0.548      0.167       0.330
       (ii) head direction, error <= 45       0.314        0.539      0.167       0.330
       (iii) signed error                     0.211        0.106      0.167       0.330
20     (i) error by head direction            0.147        0.088      0.174       0.336
       (ii) head direction, error <= 15       0.348        0.397      0.174       0.336
       (ii) head direction, error <= 30       0.318        0.464      0.174       0.336
       (ii) head direction, error <= 45       0.328        0.452      0.174       0.336
       (iii) signed error                     0.139        0.101      0.174       0.336

Expected: {'room err r': 0.589, 'arena err r': 0.653, 'room hd r': 0.147, 'arena hd r': 0.378} (tolerance 10%)

Combinations (window, pooling, reading) where every test holds: 75 of 80 ; with all four r within tolerance: 0
Most r within tolerance where every test holds: 2
r within tolerance   0   1  2
window tests hold            
4      True         27  13  0
20     False         3   2  0
       True         25   7  3

n implied by the paper's z values: {'room error': 681, 'arena error': 679, 'room head direction': 10671, 'arena head direction': 1072}
 window ensemble  RA_rm decoded  RA_rm tracked  RA_ar decoded  RA_ar tracked
     20 0930R029           1383           2680           1380           2671
     20 1004R029           2353           2681           2343           2670
     20 1022R029           1601           2680           1600           2679
     20 1023R029           1491           2686           1495           2682
     20 1026R157           2253           2670           2237           2653
     20 1117R157           2117           2641           2104           2623
     20 1121R157           2183           2658           2172           2647
      4 0930R029           3042          12816           3018          12650
      4 1004R029           7034          13011           6943          12844
      4 1022R029           2476          12516           2456          12428
      4 1023R029           2674          12704           2693          12603
      4 1026R157           8767          12670           8547          12385
      4 1117R157           7861          12427           7737          12239
      4 1121R157           7021          12361           6913          12184

Subsets of the seven ensembles whose summed counts are within 10% of an implied n:
window  count          implied            
20      RA_rm tracked  room head direction    35
Rows above with both error n within 10% of the implied 681 and 679: 0
Rows with the room error n within 10% of 681:
 window ensemble                          reading  room err n  arena err n
     20 0930R029 (ii) head direction, error <= 30         747          221
     20 1004R029 (ii) head direction, error <= 15         662          220
     20 1026R157 (ii) head direction, error <= 45         749          537
     20 1117R157 (ii) head direction, error <= 45         627          580
      4 1022R029 (ii) head direction, error <= 30         735          156
      4 1121R157 (ii) head direction, error <= 30         650         1237

Result: partially reproduced. Every test holds (all four distributions non-uniform and both Kuiper's tests at p < 0.05) in 75 of the 80 combinations of window, pooling and distribution reading, but none has all four r within tolerance; the most is two. With the six-cell ensemble 0930R029 (reading (b)) and 20-sample windows, the head directions of windows decoded within 15 degrees (reading (ii)) give a room-frame r of 0.604 (expected 0.589) and those within 30 degrees 0.555, and the signed errors (reading (iii)) 0.560, all within tolerance, with the arena-frame head-direction r 0.360 (expected 0.378); the arena-frame r under these readings is 0.484, 0.543 and 0.144 (expected 0.653), and the room-frame head-direction r 0.072 (expected 0.147). Reading (i) gives error r of 0.031 to 0.426 at 20 samples. Pooled (reading (a)) no r is within tolerance under any distribution reading, and the medians over ensembles (reading (c)) reach at most 0.348 in the room frame (reading (ii), 20 samples) and 0.548 in the arena frame (reading (ii), 4 samples). The answer adds readings (i) and (ii); they bring the arena-frame error r closer to 0.653 but not within tolerance, and the outcome is the one reading (iii) gave. The paper's z values imply about 681 and 679 windows for the two error distributions and 10,671 and 1,072 samples for the two head-direction distributions, a tenfold difference between frames of the same trials. No row has both error counts within 10% of 681 and 679, and no single ensemble or sum of ensembles matches the head-direction counts in both frames (35 sums of 20-sample windows match the room frame's 10,671 only), so which windows the paper pooled cannot be recovered from these counts.

fig5c-error-minima-at-cues¶

The room-frame decoding error histogram has strong minima at 110 and 350 degrees in the room frame ...

Readings: (a) mean absolute room-frame decoding error as a function of the room-frame head direction, 10 degree bins; (b) the histogram of the signed room-frame error in 10 degree bins. The two deepest local minima (circular), located by their bin centres; tolerance 10 degrees. Under the pooling readings of fig5 and both windows. The decoded direction is the start of the winning bin, as in the paper's code, which shifts the signed error of reading (b) by about -5 degrees. The chance rate of a match, for two minima placed at random, is printed.

In [27]:
def two_minima(y):
    y = np.asarray(y, float)
    loc = [i for i in range(36) if y[i] < y[i - 1] and y[i] < y[(i + 1) % 36]]
    depth = {i: min(y[i - 1], y[(i + 1) % 36]) - y[i] for i in loc}
    return sorted(loc, key=lambda i: y[i])[:2], depth


def near(deg, target):
    return float(hd20.circ_absdiff(deg, target)) <= 10


rows = []
for w in [20, 4]:
    for s in list(ENS) + ["pooled"]:
        ss = list(ENS) if s == "pooled" else [s]
        err = np.concatenate([DEC[(w, e, "RA_rm")]["err"] for e in ss])
        hd = np.concatenate([DEC[(w, e, "RA_rm")]["dir"] for e in ss])
        ok = ~np.isnan(err) & ~np.isnan(hd)
        b = (hd[ok] // 10).astype(int) % 36
        ya = np.bincount(b, weights=np.abs(err[ok]), minlength=36) / np.maximum(np.bincount(b, minlength=36), 1)
        yb = np.bincount(((err[ok] % 360) // 10).astype(int) % 36, minlength=36)
        if (w, s) == (20, "pooled"):
            curve_pooled = ya
        for name, y in [("(a) error by head direction", ya), ("(b) signed error histogram", yb)]:
            mins, _ = two_minima(y)
            starts = [i * 10 for i in mins]
            hit = {t: any(near(m + 5, t) for m in starts) for t in [110, 350]}   # bin centres
            rows.append({"window": w, "ensemble": s, "reading": name, "minima (bin starts)": starts,
                         "near 110": hit[110], "near 350": hit[350]})
f5c = pd.DataFrame(rows)
print(f5c.to_string(index=False))
print("\nRows with both minima near 110 and 350:", int((f5c["near 110"] & f5c["near 350"]).sum()), "of", len(f5c),
      "; with one:", int((f5c["near 110"] ^ f5c["near 350"]).sum()))
# chance: the two minima as two distinct bins drawn at random from the 36
from itertools import permutations
pairs_ = list(permutations(range(36), 2))
h = [(any(near(i * 10 + 5, 110) for i in pr_), any(near(i * 10 + 5, 350) for i in pr_)) for pr_ in pairs_]
p_both = np.mean([a and b for a, b in h])
p_one = np.mean([a != b for a, b in h])
print(f"Chance per row (two random distinct bins): both {p_both:.4f}, exactly one {p_one:.3f}; expected over "
      f"{len(f5c)} rows: both {len(f5c) * p_both:.2f}, one {len(f5c) * p_one:.1f}")
print(f"Chance that at least one of {len(f5c)} rows has both, were the rows independent (they share data, so "
      f"this is a rough figure): {1 - (1 - p_both) ** len(f5c):.2f}")
mins, depth = two_minima(curve_pooled)
print("Pooled, 20 samples, reading (a): mean absolute error by head direction from "
      f"{curve_pooled.min():.1f} to {curve_pooled.max():.1f} degrees (mean {curve_pooled.mean():.1f}); "
      "the two deepest minima at bin starts", [i * 10 for i in mins], "lie",
      [round(float(curve_pooled.mean() - curve_pooled[i]), 1) for i in mins], "degrees below the mean and",
      [round(float(depth[i]), 1) for i in mins], "below their lower neighbour")
print(f"\nNotebook run time: {(time.time() - started) / 60:.1f} min")
 window ensemble                     reading minima (bin starts)  near 110  near 350
     20 0930R029 (a) error by head direction          [300, 320]     False     False
     20 0930R029  (b) signed error histogram           [80, 170]     False     False
     20 1004R029 (a) error by head direction          [240, 120]     False     False
     20 1004R029  (b) signed error histogram           [70, 100]      True     False
     20 1022R029 (a) error by head direction           [40, 330]     False     False
     20 1022R029  (b) signed error histogram           [70, 120]     False     False
     20 1023R029 (a) error by head direction          [290, 240]     False     False
     20 1023R029  (b) signed error histogram          [130, 150]     False     False
     20 1026R157 (a) error by head direction           [70, 100]      True     False
     20 1026R157  (b) signed error histogram          [110, 150]      True     False
     20 1117R157 (a) error by head direction            [340, 0]     False      True
     20 1117R157  (b) signed error histogram          [220, 110]      True     False
     20 1121R157 (a) error by head direction          [310, 290]     False     False
     20 1121R157  (b) signed error histogram           [40, 210]     False     False
     20   pooled (a) error by head direction          [100, 340]      True      True
     20   pooled  (b) signed error histogram           [110, 70]      True     False
      4 0930R029 (a) error by head direction          [320, 170]     False     False
      4 0930R029  (b) signed error histogram          [210, 120]     False     False
      4 1004R029 (a) error by head direction           [240, 20]     False     False
      4 1004R029  (b) signed error histogram           [90, 120]     False     False
      4 1022R029 (a) error by head direction           [60, 340]     False      True
      4 1022R029  (b) signed error histogram           [90, 310]     False     False
      4 1023R029 (a) error by head direction          [300, 280]     False     False
      4 1023R029  (b) signed error histogram          [140, 190]     False     False
      4 1026R157 (a) error by head direction           [90, 130]     False     False
      4 1026R157  (b) signed error histogram          [120, 160]     False     False
      4 1117R157 (a) error by head direction          [340, 300]     False      True
      4 1117R157  (b) signed error histogram          [210, 250]     False     False
      4 1121R157 (a) error by head direction          [210, 230]     False     False
      4 1121R157  (b) signed error histogram           [30, 350]     False      True
      4   pooled (a) error by head direction          [230, 330]     False     False
      4   pooled  (b) signed error histogram           [110, 90]      True     False

Rows with both minima near 110 and 350: 1 of 32 ; with one: 10
Chance per row (two random distinct bins): both 0.0063, exactly one 0.206; expected over 32 rows: both 0.20, one 6.6
Chance that at least one of 32 rows has both, were the rows independent (they share data, so this is a rough figure): 0.18
Pooled, 20 samples, reading (a): mean absolute error by head direction from 63.2 to 91.3 degrees (mean 76.8); the two deepest minima at bin starts [100, 340] lie [13.6, 13.4] degrees below the mean and [0.1, 1.6] below their lower neighbour

Notebook run time: 7.0 min

Result: reproduced under one reading. With the seven ensembles pooled and 20-sample windows, the mean absolute room-frame error as a function of room-frame head direction (reading (a)) has its two deepest minima in the bins starting at 100 and 340 degrees (centres 105 and 345), within 10 degrees of 110 and 350 by their bin centres. This is 1 of 32 combinations of window, pooling and reading, against 0.20 expected by chance for two minima placed at random; 10 others find one of the two minima, against 6.6 expected by chance, and the pooled reading (a) with 133 ms windows finds neither. Were the 32 rows independent, at least one would match both minima by chance with probability 0.18; they share data, so this is a rough figure. The pooled curve is shallow: its Rayleigh r is 0.032 (fig5-error-inhomogeneous, reading (i)), the mean error runs from 63.2 to 91.3 degrees by head direction (mean 76.8), and the two minima lie 13.6 and 13.4 degrees below the mean but only 0.1 and 1.6 degrees below their lower neighbouring bin. The match rests on the pooled reading and is weak support for the claim.

Summary¶

Claim Outcome
cell-counts partially reproduced: 115 head-direction units from 13 rats; the other MEC cells and pairs are not deposited
hd-cell-rate reproduced: 1.39 AP/s in stable1
fig1a-avoidance-learning blocked: data missing
fig1c-speed reproduced
fig1c-lfp-power blocked: data missing
fig1c-firing-rate reproduced (p = 0.18)
fig1c-directionality reproduced, with Tukey HSD on the repeated-measures error term (assumed); partial with the between-groups variant
fig1d-preference-change partially reproduced: stable1-arena change is the largest, not the smallest
fig1d-instability partially reproduced: stable1-room does not exceed the halves (a judgement, as the criterion has no partial form)
fig2-decoding-stable-vs-rotating reproduced (assumed majority rule)
figs2-frame-preference reproduced under 1 of 16 readings (assumed)
fig2c-proximity-anticorrelation partially reproduced: negative but weaker (mean r -0.04 to -0.09) under three distance measures
figs3-no-head-direction-bias reproduced (assumed n of the Rayleigh test and Idir reading)
fig3-hd-pair-correlations-preserved reproduced
figs4-all-pair-correlations-preserved blocked: data missing
figs5-hd-cells-high-model-information blocked: data missing
figs6-subclass-correlations-preserved blocked: data missing
no-angular-velocity-tuning not reproduced (assumed test)
fig4-internal-tuning-preserved not reproduced
fig4c-arena-registration-short-lived not reproduced: the arena frame is below the other three only from 50 s or later, after the room frame has fallen (assumed reading of "beyond 10 s")
fig5-error-inhomogeneous partially reproduced
fig5c-error-minima-at-cues reproduced under one reading (assumed)

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.

How the analysis differs from the paper's. Spike width cannot be applied (no waveforms); the 115 deposited units are taken as the head-direction cells. Units are matched across trials by file name where FileNameList.xlsx is shifted. The decoder and the internally referenced tuning are ports of the paper's Python code; Idir, relative proximity, the strength of internal tuning and several test details are not fully specified and are run under the readings the claims file names. Statistics use Python in place of JMP 12, with the Greenhouse-Geisser correction applied when Mauchly's test is significant. After repeated-measures ANOVAs, Tukey HSD uses the ANOVA's repeated-measures error term (an assumption; the between-groups Tukey-Kramer HSD is shown as a variant); after one-way ANOVAs it is the between-groups Tukey-Kramer HSD.

What was found about the data set. It holds the 115 head-direction units only (no other MEC units, LFP, waveforms or training sessions). FileNameList.xlsx shifts the stable2 files of five units of session 1121R157 by one row. Two pairs of trials from different days share their tracking sample for sample (stable2 of 1015R029 and 1025R029; the room-frame rotating trial of 1211R039 and 1212R039). The stable1 file of 1024R157-P9C1 holds the spikes of its rotating trial. One header states 2000 samples/s; one stable2 file lasts 15 min; one spike train has a decreasing step; the per-rat counts differ from Table S1 for R029 and R523, though both R523 units are named R523 in all their files; samples without a direction (coded 4294967295), 4 to 73% of a file, are not documented, nor is the angle convention of the shock zones. One tracker file is named for the wrong rat.