Reproducing Rich, Liaw & Lee (2014) from CRCNS hc-31¶

Paper. Rich PD, Liaw H-P, Lee AK (2014). Large environments reveal the statistical structure governing hippocampal representations. Science 345:814-817. doi:10.1126/science.1255635. The claims file (claims/rich-2014.yaml) was written from the version of record and its supplement (Materials and Methods, Supplementary Text, Figs. S1 to S18); the last page of the article (Fig. 4 and its legend) was damaged in the copy read. In this revision the supplementary figures were rendered from the supplement PDF, and Figs. S10 and S18 are cited where they bear on a method detail (bin widths, the spacing of environment sizes); values read from a figure are marked as such and decide no number computed here.

Data set. CRCNS hc-31, "Extracellular CA1 activity from rats during exploration of a novel 48m track", data description version 0.6 (Oct 30, 2022). CRCNS data sets are not versioned, so the version is recorded as unversioned with the data set's DOI 10.6080/K0BV7DT2; this is the only published state of the data set and the paper cites none. The analysis reads one file, hc-31/live/data/resSave.mat, streamed from the public bucket crcnsarchive into memory. Its MD5 in the data set's checksums.md5 is f97e58107878c688854474519fa6be72, and the first cell checks the bytes read against it. The other files are csc_files.tar.gz (8.8 GB, one wideband LFP channel per rat), the Neuralynx import code, example_script.m and the readme. The LFP is not needed: the data set gives the PRE slow-wave sleep periods (intSWS) that the paper detected.

What the file holds. A struct array; elements 5 to 9 are the paper's five rats (resSave_readme.txt). Per unit: spike times and peak amplitudes on the four channels in PRE, RUN1, RUN2 and RUN3, and the extra sleep epochs; cluster metadata (tetrode, region, L-ratio and isolation distance fields); a unit class per epoch (ID); histological position (septotemporal st, proximodistal pd). Per animal: room and linearized positions with speed and direction for RUN1, RUN2 and RUN3; the RUN1 epoch times (sectInt) and section extents (sectExt); positions restricted to the novel section (posMazeLinNov); the paper's own fields (fieldInfoC), rate maps, field counts (numField, numFieldNovel), SWS and ripple periods of PRE.

How fields are found. Every claim rests on the place fields of RUN1. They are recomputed here from spikes and position by the paper's method (field set F-a), under the two readings of a "pass" the claims file names, P-a (a run in one direction that crosses the whole field) and P-b (any visit to the field's bins while moving in that direction). Under P-a a field that reaches the end of the positions visited in its section cannot be crossed beyond that end, so an edge within 20 cm of either end counts as reached when the run gets within 20 cm of that end (a standard choice; the first version of this notebook dropped such fields, verifier round 1, problem 2). The data set's own fields (F-b) are shown as a variant for every claim; outcomes are judged on F-a. Where P-a and P-b give different outcomes, the outcome is taken from P-a as an assumption: P-a recovers more of the data set's own fields and its per-animal means (see the data check and the summary).

Claim Tested here
cell-counts tested
figs3-cluster-quality blocked: data missing (the L-ratio and isolation distance fields are empty and the unclustered spikes are not in the data set)
fig1-recruitment-by-section, fig2-individual-poisson, fig2bc-population-bias, figs6-few-field-cells-uniform tested
fig3b-overdispersion, figs7a-mean-fields-per-animal, fig3b-negbin-fit, fig3c-recruitment-fraction, fig3c-lomax-recruitment, fig3c-extrapolation-500m, fig3d-uniform-density tested
figs10-no-track-or-speed-influence, figs11-propensity-stationary, figs11-no-boundary-remapping, figs12-pairs-uncorrelated, fig3e-memoryless-recruitment tested
figs14-field-properties, figs15-higher-threshold, figs16-anatomy, fig4a-pre-sleep-rate, fig4b-single-field-proportion, fig4c-active-subsets tested
figs5-silent-cells-low-rate, figs8-silent-cells-form-fields, figs17-propensity-across-environments tested
In [1]:
import resource
import time

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

import rich

pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)
pd.set_option("display.max_rows", 200)
started = time.time()
animals, md5 = rich.load_animals()
cells = rich.cell_table(animals)
ANIMALS = [a["animal"] for a in animals]
print(f"resSave.mat streamed from {rich.URL}")
print(f"MD5 of the bytes read {md5}; checksums.md5 gives {rich.MD5}; equal: {md5 == rich.MD5}")
print(f"loaded in {time.time() - started:.0f} s")

# Field sets. F-a: fields recomputed by the paper's method under the two pass readings.
# F-b: the data set's own novel fields (fieldInfoC, isnov = 1), a variant.
FIELDS = {"F-a/P-a": rich.track_fields(animals, "P-a"),
          "F-a/P-b": rich.track_fields(animals, "P-b"),
          "F-b": rich.dataset_field_table(animals)}
COUNTS = {k: rich.counts(v, cells) for k, v in FIELDS.items()}
MAIN = ["F-a/P-a", "F-a/P-b"]
for k, v in FIELDS.items():
    print(f"{k}: {len(v)} fields, {(COUNTS[k] > 0).sum()} cells with a field")
print(f"fields computed in {time.time() - started:.0f} s; peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
resSave.mat streamed from https://crcnsarchive.s3-us-west-2.amazonaws.com/hc-31/live/data/resSave.mat
MD5 of the bytes read f97e58107878c688854474519fa6be72; checksums.md5 gives f97e58107878c688854474519fa6be72; equal: True
loaded in 8 s
F-a/P-a: 852 fields, 162 cells with a field
F-a/P-b: 793 fields, 159 cells with a field
F-b: 887 fields, 165 cells with a field
fields computed in 18 s; peak memory 0.86 GB

Data check¶

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

In [2]:
rows = []
for a in animals:
    ep = a["sectInt"]
    rows.append({
        "animal": a["animal"], "resSave element": a["element"], "units in file": a["n_units"],
        "valid (ID<=2 in every epoch)": len(a["cells"]),
        "regions of valid units": "/".join(sorted(set(a["region"]))),
        "regions of excluded units": "/".join(sorted({r for r, keep in zip(a["region_all"], np.isin(np.arange(a["n_units"]), a["cells"])) if not keep})) or "-",
        "tetrodes": len(set(a["tetrode"])),
        "RUN1 epochs (s)": " ".join(f"{e1 - e0:.0f}" for e0, e1 in ep),
        "track end (m)": round(a["sectExt_cm"][-1, 1] / 100, 2),
        "section lengths (m)": " ".join(f"{(e1 - e0) / 100:.1f}" for e0, e1 in a["sectExt_cm"]),
        "pos dt (ms)": round(1000 * np.median(np.diff(a["t"])), 1),
    })
info = pd.DataFrame(rows)
print(info.to_string(index=False))
print("\nTotal valid units:", int(info["valid (ID<=2 in every epoch)"].sum()))
print("ID values in valid rows:", np.unique(np.concatenate([a["ID"].ravel() for a in animals])).tolist(),
      "(readme: 0 silent, 1 active, 2 place, NaN interneuron or poor quality)")
     animal  resSave element  units in file  valid (ID<=2 in every epoch) regions of valid units regions of excluded units  tetrodes  RUN1 epochs (s)  track end (m) section lengths (m)  pos dt (ms)
ANM00190422                5             63                            63                    CA1                         -        10  222 228 684 866          48.07   3.7 6.2 11.5 26.9         33.4
  ANM204878                6             58                            58                    CA1                         -         8 253 294 468 1355          48.09   3.7 6.1 11.4 27.0         33.4
  ANM212379                7             27                            24                    CA1                        DS         7 274 410 589 1836          47.97   3.8 6.1 11.6 26.7         33.4
  ANM228899                8             59                            57                    N/A                       N/A        10 301 546 939 2310          48.04   3.7 6.1 11.5 26.9         33.4
  ANM228900                9             53                            51                    CA1                       CA1         7 227 460 555 1509          47.99   3.6 6.1 11.6 26.8         33.4

Total valid units: 253
ID values in valid rows: [0.0, 1.0, 2.0] (readme: 0 silent, 1 active, 2 place, NaN interneuron or poor quality)

Units: the file holds 63, 58, 27, 59 and 53 units in elements 5 to 9; keeping the rows of ID that are at most 2 in every epoch (the readme's rule) leaves 63, 58, 24, 57 and 51, the paper's counts. The excluded rows are all NaN; in ANM212379 they are on tetrodes marked DS. The region of every unit of ANM228899 is N/A, so the CA1 localization cannot be checked from the file for that animal. Track ends lie at 47.97 to 48.09 m, consistent with the 48 m track. The section lengths from sectExt are about 3.7, 6.1, 11.5 and 26.9 m (cumulative ends 3.5, 9.6, 21.2 and 48.0 m), where the Methods give sections of 3, 7, 12 and 26 m (totals 3, 10, 22 and 48 m); the data are used as they are. Positions are sampled every 33.4 ms (30 Hz).

In [3]:
rows = []
for a in animals:
    nov = []
    for e in range(4):
        idx = rich.epoch_samples(a, e)
        x = a["x_nov_cm"][idx]
        lo, hi = a["sectExt_cm"][e]
        nov.append(np.mean((x >= lo - 1) & (x <= hi + 1)))
    allnov = np.isfinite(a["x_nov_cm"])
    in_any = np.zeros(len(a["t"]), bool)
    for e0, e1 in a["sectInt"]:
        in_any |= (a["t"] >= e0) & (a["t"] <= e1)
    ok = np.isfinite(a["v"]) & np.isfinite(a["v_dataset"])
    rows.append({
        "animal": a["animal"],
        "novel samples inside their section's sectExt": round(float(np.min(nov)), 4),
        "novel samples outside sectInt": int(np.sum(allnov & ~in_any)),
        "x range (m)": f"{np.nanmin(a['x_cm']) / 100:.2f} to {np.nanmax(a['x_cm']) / 100:.2f}",
        "speed p50/p95 (cm/s), centred 1 s": f"{np.nanmedian(np.abs(a['v'])):.1f}/{np.nanpercentile(np.abs(a['v']), 95):.1f}",
        "r with data set's speed column": round(float(np.corrcoef(np.abs(a["v"][ok]), a["v_dataset"][ok])[0, 1]), 3),
        "sign(v) > 0 when direction column = 180": round(float(np.mean((a["v"][ok] > 0) == (a["dir_dataset"][ok] == 180))), 3),
        "room x, y extent (m)": f"{np.ptp(a['xy_room'][:, 0][np.isfinite(a['xy_room'][:, 0])]) * 0.0254:.1f} x {np.ptp(a['xy_room'][:, 1][np.isfinite(a['xy_room'][:, 1])]) * 0.0254:.1f}",
    })
print(pd.DataFrame(rows).to_string(index=False))
     animal  novel samples inside their section's sectExt  novel samples outside sectInt    x range (m) speed p50/p95 (cm/s), centred 1 s  r with data set's speed column  sign(v) > 0 when direction column = 180 room x, y extent (m)
ANM00190422                                           1.0                              0 -0.18 to 48.04                         10.8/82.2                           0.996                                    0.989           13.2 x 9.3
  ANM204878                                           1.0                              0 -0.19 to 48.07                         13.0/78.8                           0.996                                    0.990           13.8 x 5.3
  ANM212379                                           1.0                              0 -0.25 to 47.94                         9.4/102.5                           0.998                                    0.989           13.8 x 5.3
  ANM228899                                           1.0                              0 -0.15 to 48.03                         10.2/88.0                           0.993                                    0.986           13.8 x 4.8
  ANM228900                                           1.0                              0 -0.10 to 47.96                         15.9/87.0                           0.997                                    0.989           13.8 x 4.8

Units of the position data, which the readme does not state: linearized and room positions are in inches (unitsPerCm 0.3937; the track ends at 1890 inches, 48 m, and the room spans 13 to 14 m by 5 to 9 m, consistent with the ~150 m2 room), and the speed column is in inches per microsecond (converted, it correlates at 0.993 to 0.998 with the speed computed here from the net displacement in a centred 1 s window). The direction column is 180 when the linearized position increases (outbound) in 98.6 to 99.0% of samples. All novel-section samples lie inside their epoch's section and inside the sectInt epoch times.

In [4]:
rows = []
for a in animals:
    xy = a["of_xy_cm"]
    okxy = np.all(np.isfinite(xy), axis=1)
    p2, p98 = np.percentile(xy[okxy], [1, 99], axis=0)
    sws_total = np.sum(np.diff(a["sws"], axis=1))
    rows.append({
        "animal": a["animal"],
        "open field duration (min)": round((a["of_t"][-1] - a["of_t"][0]) / 60, 1),
        "open field 1-99% extent (cm)": f"{p98[0] - p2[0]:.0f} x {p98[1] - p2[1]:.0f}",
        "open field units per cm": round(a["of_units_per_cm"], 3),
        "PRE length (min)": round(np.diff(a["pre_epoch"])[0] / 60, 1),
        "SWS periods": len(a["sws"]), "SWS total (min)": round(sws_total / 60, 1),
        "SWS inside PRE": bool(a["sws"].min() >= a["pre_epoch"][0] and a["sws"].max() <= a["pre_epoch"][1]),
        "SWR events": len(a["swr"]),
        "SWR per s of SWS": round(sum(np.sum((a["swr"][:, 0] >= s0) & (a["swr"][:, 0] <= s1)) for s0, s1 in a["sws"]) / sws_total, 2),
        "st range": f"{np.nanmin(a['st']):.2f} to {np.nanmax(a['st']):.2f}",
        "pd range": f"{np.nanmin(a['pd']):.2f} to {np.nanmax(a['pd']):.2f}",
        "finite L-ratio": int(np.isfinite(a["lratio"]).sum()), "finite IsoD": int(np.isfinite(a["isod"]).sum()),
    })
print(pd.DataFrame(rows).to_string(index=False))
     animal  open field duration (min) open field 1-99% extent (cm)  open field units per cm  PRE length (min)  SWS periods  SWS total (min)  SWS inside PRE  SWR events  SWR per s of SWS     st range     pd range  finite L-ratio  finite IsoD
ANM00190422                       26.6                     100 x 72                    1.732              38.8           29             21.1            True        1946              1.36 0.17 to 0.28 0.07 to 0.48               0            0
  ANM204878                       15.6                     119 x 96                    2.607              73.2           84             49.6            True        4374              1.25 0.20 to 0.32 0.23 to 0.64               0            0
  ANM212379                       18.4                     119 x 86                    2.607              48.9           70             31.7            True        1981              0.99 0.20 to 0.28 0.49 to 0.96               0            0
  ANM228899                       12.9                     118 x 95                    2.607              49.5          109             29.1            True        1533              0.84 0.16 to 0.26 0.09 to 0.36               0            0
  ANM228900                        9.2                     118 x 97                    2.607              44.1           82             26.7            True        1613              0.97 0.17 to 0.25 0.17 to 0.36               0            0

Open field: 9.2 to 26.6 min per rat, consistent with the Methods' 10 to 25 min except one rat at 9.2 min. The positions, converted with the file's unitsPerCm, span about 100 to 119 cm by 72 to 97 cm (1st to 99th percentile), larger than the Methods' oval of ~40 x 100 cm; either the scale or the description is off, and the open-field field size threshold (100 cm2) depends on it. SWS periods lie inside PRE in every animal and total 21 to 50 min. Histological coordinates are relative (0 to 1). The L-ratio and isolation distance fields are NaN for every unit.

In [5]:
# numFieldNovel against the novel fields listed in fieldInfoC, and the per-animal means.
fb = FIELDS["F-b"]
nb_list = rich.counts(fb, cells)
print("numFieldNovel equals the count of isnov fields in fieldInfoC for every cell:",
      bool(np.all(nb_list == cells.nov_dataset.values)))
print("Fields of the data set: sizes from", fb.size_cm.min().round(2), "to", fb.size_cm.max().round(2),
      "cm; field edges are whole inches (1 inch bins), e.g. sizes / 2.54 are integers:",
      bool(np.allclose(fb.size_cm / 2.54, np.round(fb.size_cm / 2.54))))
# Duplicate units: pairs of units in an animal sharing more than half their RUN1 spike times.
dups = []
for a in animals:
    for i in range(len(a["cells"])):
        for j in range(i + 1, len(a["cells"])):
            si, sj = a["run1"][i], a["run1"][j]
            if len(si) and len(sj):
                share = len(np.intersect1d(np.round(si, 4), np.round(sj, 4))) / min(len(si), len(sj))
                if share > 0.5:
                    dups.append((a["animal"], i, j, round(share, 2)))
print("Pairs of units sharing over 50% of their RUN1 spike times:", dups if dups else "none")
print("Spikes per cell in RUN1, median and range:",
      int(np.median([len(s) for a in animals for s in a["run1"]])),
      min(len(s) for a in animals for s in a["run1"]), max(len(s) for a in animals for s in a["run1"]))
outside = sum(int(np.sum((s < a["run1_epoch"][0]) | (s > a["run1_epoch"][1]))) for a in animals for s in a["run1"])
print("RUN1 spikes outside the RUN1 epoch times:", outside)
numFieldNovel equals the count of isnov fields in fieldInfoC for every cell: True
Fields of the data set: sizes from 15.24 to 332.74 cm; field edges are whole inches (1 inch bins), e.g. sizes / 2.54 are integers: True
Pairs of units sharing over 50% of their RUN1 spike times: none
Spikes per cell in RUN1, median and range: 490 0 6280
RUN1 spikes outside the RUN1 epoch times: 0

The data set's field counts (numFieldNovel) equal the number of novel fields listed in fieldInfoC for every cell. The data set's field edges are whole inches: its rate maps use 1 inch bins, where the Methods give 1 cm bins; the recomputed fields here use 1 cm. No two units share more than half their RUN1 spike times, so no unit is deposited twice.

In [6]:
# Clock check: spatial information (bits per second, summed over cells, directions and epochs)
# of the RUN1 rate maps with spike times shifted against position. If spikes and position share
# a clock, information peaks at zero shift.
def spatial_info(a, shift):
    info_sum = 0.0
    for k in range(len(a["cells"])):
        for e in range(4):
            sh = dict(a)
            sh["run1"] = list(a["run1"])
            sh["run1"][k] = a["run1"][k] + shift
            c, maps, _ = rich.directional_maps(sh, k, e)
            for m in maps.values():
                r, o = np.nan_to_num(m["rate"]), m["occ"]
                p = o / o.sum() if o.sum() else o
                mr = np.sum(p * r)
                if mr > 0:
                    nz = r > 0
                    info_sum += np.sum(p[nz] * r[nz] * np.log2(r[nz] / mr))
    return info_sum

# Spikes against the data set's sharp-wave ripple periods (PRE): rate of all cells inside
# intSWR, at its own times and with the periods shifted by 1 and 5 s.
for a in animals:
    swr = a["swr"]
    dur = np.sum(swr[:, 1] - swr[:, 0])
    out = []
    for sh in (0, 1, 5):
        n = 0
        for sp in a["pre"]:
            i = np.searchsorted(swr[:, 0] + sh, sp, side="right") - 1
            n += int(np.sum((i >= 0) & (sp <= swr[np.clip(i, 0, None), 1] + sh)))
        out.append(n / dur / len(a["cells"]))
    print(f"{a['animal']}: mean rate per cell inside SWR periods {out[0]:.2f} Hz; periods shifted 1 s {out[1]:.2f} Hz, "
          f"5 s {out[2]:.2f} Hz; mean SWR length {1000 * dur / len(swr):.0f} ms")

shifts = [-20, -10, -5, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 5, 10, 20]
clock = pd.DataFrame({a["animal"]: [spatial_info(a, s) for s in shifts] for a in animals}, index=shifts)
clock.index.name = "spike shift (s)"
print((clock / clock.loc[0]).round(3).to_string())
print("Shift of peak information per animal:", clock.idxmax().to_dict())
ANM00190422: mean rate per cell inside SWR periods 1.91 Hz; periods shifted 1 s 0.36 Hz, 5 s 0.37 Hz; mean SWR length 42 ms
ANM204878: mean rate per cell inside SWR periods 0.76 Hz; periods shifted 1 s 0.17 Hz, 5 s 0.17 Hz; mean SWR length 41 ms
ANM212379: mean rate per cell inside SWR periods 0.83 Hz; periods shifted 1 s 0.16 Hz, 5 s 0.15 Hz; mean SWR length 41 ms
ANM228899: mean rate per cell inside SWR periods 1.30 Hz; periods shifted 1 s 0.14 Hz, 5 s 0.13 Hz; mean SWR length 46 ms
ANM228900: mean rate per cell inside SWR periods 1.42 Hz; periods shifted 1 s 0.20 Hz, 5 s 0.20 Hz; mean SWR length 43 ms
                 ANM00190422  ANM204878  ANM212379  ANM228899  ANM228900
spike shift (s)                                                         
-20.00                 0.570      0.550      0.642      0.513      0.521
-10.00                 0.549      0.565      0.598      0.512      0.545
-5.00                  0.606      0.645      0.629      0.558      0.607
-2.00                  0.759      0.764      0.828      0.658      0.734
-1.00                  0.867      0.891      0.944      0.822      0.840
-0.50                  0.944      0.966      0.994      0.908      0.923
-0.25                  0.978      0.997      0.986      0.958      0.970
 0.00                  1.000      1.000      1.000      1.000      1.000
 0.25                  0.995      0.997      1.018      1.008      1.000
 0.50                  0.970      0.972      0.998      0.969      0.959
 1.00                  0.897      0.920      0.914      0.862      0.878
 2.00                  0.773      0.802      0.834      0.707      0.747
 5.00                  0.626      0.617      0.631      0.541      0.569
 10.00                 0.584      0.541      0.652      0.481      0.553
 20.00                 0.568      0.557      0.646      0.496      0.533
Shift of peak information per animal: {'ANM00190422': 0.0, 'ANM204878': 0.0, 'ANM212379': 0.25, 'ANM228899': 0.25, 'ANM228900': 0.0}

Clock: spatial information of the RUN1 maps peaks at a shift of 0 or 0.25 s in every animal and falls to 0.48 to 0.65 of its peak at 10 to 20 s shifts, so spikes and position share a clock. Spike rates inside the data set's ripple periods are 0.76 to 1.91 Hz per cell against 0.13 to 0.37 Hz with the periods shifted by 1 or 5 s, so the ripple periods share the PRE spike clock. The SWS periods come from the same processing and are taken to share it.

In [7]:
# Units are taken as the same cell in PRE, RUN1 and RUN3, as the data set gives one cluster per
# unit. Check: each unit's mean peak amplitude on the four channels in PRE, against every unit of
# its tetrode in RUN1 and RUN3; the nearest one should be itself.
rows = []
for a in animals:
    amp = a["mean_amplitude"]  # units x (PRE, RUN1, RUN3) x 4 channels
    for k in range(len(a["cells"])):
        same = np.flatnonzero(a["tetrode"] == a["tetrode"][k])
        res = {}
        for j, name in ((1, "RUN1"), (2, "RUN3")):
            ok = same[np.all(np.isfinite(amp[same, j]), axis=1)]
            if not np.all(np.isfinite(amp[k, 0])) or k not in ok or len(ok) < 2:
                res[name] = np.nan
                continue
            d = np.linalg.norm(amp[ok, j] - amp[k, 0], axis=1)
            res[name] = float(ok[np.argmin(d)] == k)
        change = np.linalg.norm(amp[k, 1] - amp[k, 0]) / np.linalg.norm(amp[k, 0])
        rows.append(dict(animal=a["animal"], nearest_is_self_RUN1=res["RUN1"], nearest_is_self_RUN3=res["RUN3"], rel_change_RUN1=change))
amp_t = pd.DataFrame(rows)
print(amp_t.groupby("animal").agg(units=("animal", "size"), self_RUN1=("nearest_is_self_RUN1", "mean"),
                                 self_RUN3=("nearest_is_self_RUN3", "mean"),
                                 median_rel_change_PRE_to_RUN1=("rel_change_RUN1", "median")).round(3).to_string())
print("units testable (another unit on the tetrode): RUN1", int(amp_t.nearest_is_self_RUN1.notna().sum()),
      ", RUN3", int(amp_t.nearest_is_self_RUN3.notna().sum()), "of", len(amp_t))
             units  self_RUN1  self_RUN3  median_rel_change_PRE_to_RUN1
animal                                                                 
ANM00190422     63      0.968      0.966                          0.106
ANM204878       58      0.942      0.957                          0.093
ANM212379       24      1.000      1.000                          0.083
ANM228899       57      0.930      0.936                          0.115
ANM228900       51      0.980      0.892                          0.089
units testable (another unit on the tetrode): RUN1 243 , RUN3 207 of 253

Unit identity across epochs: for 89 to 100% of the units that share a tetrode with another unit, the unit nearest in mean peak amplitude to its own PRE amplitudes is itself, in RUN1 and in RUN3, and the median change of the amplitude vector from PRE to RUN1 is 8 to 12%. This is consistent with each unit being the same cell across epochs, which the analysis assumes as the data set gives it.

In [8]:
# How the data set's own field records count passes (fieldInfoC passStart), against the two
# pass readings, on the same field extents (single-direction fields of the data set).
rows = []
for _, r in FIELDS["F-b"][FIELDS["F-b"].direction < 3].iterrows():
    a = animals[r.ai]
    sign = 1 if r.direction == 2 else -1  # data set direction 2 is outbound (shown above)
    n_a, n_b = rich.pass_counts(a, r.epoch, sign, r.start_cm, r.end_cm)
    xs = np.interp(r.pass_start, a["t"], a["x_cm"]) if r.n_pass else np.array([])
    rows.append(dict(dataset=r.n_pass, Pa=n_a, Pb=n_b, starts_inside=int(np.sum((xs > r.start_cm + 5) & (xs < r.end_cm - 5)))))
pc = pd.DataFrame(rows)
print(f"{len(pc)} single-direction fields of the data set. Passes per field, mean: data set {pc.dataset.mean():.2f}, "
      f"P-a {pc.Pa.mean():.2f}, P-b {pc.Pb.mean():.2f}")
print(f"exact agreement with the data set's count: P-a {np.mean(pc.dataset == pc.Pa):.3f}, P-b {np.mean(pc.dataset == pc.Pb):.3f}; "
      f"mean absolute difference: P-a {np.mean(np.abs(pc.dataset - pc.Pa)):.2f}, P-b {np.mean(np.abs(pc.dataset - pc.Pb)):.2f}")
print(f"fields where a data-set pass starts more than 5 cm inside the field: {np.mean(pc.starts_inside > 0):.3f}")
# direction coding of the data set's fields, from fields found in both sets
m = FIELDS["F-a/P-a"][["ai", "cell", "epoch", "loc_m", "direction"]].merge(FIELDS["F-b"][["ai", "cell", "epoch", "loc_m", "direction"]], on=["ai", "cell", "epoch"], suffixes=("_a", "_b"))
m = m[(np.abs(m.loc_m_a - m.loc_m_b) < 0.1) & (m.direction_a < 3) & (m.direction_b < 3)]
print("F-a direction (1 outbound, 2 inbound) against the data set's direction code, matched fields:")
print(pd.crosstab(m.direction_a, m.direction_b).to_string())
720 single-direction fields of the data set. Passes per field, mean: data set 6.03, P-a 4.97, P-b 8.28
exact agreement with the data set's count: P-a 0.503, P-b 0.392; mean absolute difference: P-a 1.16, P-b 2.25
fields where a data-set pass starts more than 5 cm inside the field: 0.232
F-a direction (1 outbound, 2 inbound) against the data set's direction code, matched fields:
direction_b    1    2
direction_a          
1              0  310
2            296    1

Passes: the data set's field records list the passes it counted for each field (passStart). Over its 720 single-direction fields it counts 6.03 passes on average, between P-a (4.97) and P-b (8.28); it agrees exactly with P-a for 0.503 of fields and with P-b for 0.392, and differs by 1.16 against 2.25 on average. In 0.232 of fields one of its passes starts more than 5 cm inside the field, which P-a does not count, so the data set's rule matches neither reading exactly. The data set's direction code 1 is inbound and 2 outbound (crosstab of matched fields).

In [9]:
# Fields at the ends of a novel section, and the fields of the data set the recomputation misses
# (verifier round 1, problems 2 and 3). "P-a, first version" counts a P-a pass only when the run
# goes beyond both field edges, so a field reaching the end of the positions visited cannot pass.
FIRST_PA = rich.track_fields(animals, "P-a", edge_cm=False)
for name, f in [("P-a, first version", FIRST_PA), ("F-a/P-a", FIELDS["F-a/P-a"]), ("F-a/P-b", FIELDS["F-a/P-b"])]:
    c = rich.counts(f, cells)
    print(f"{name}: {len(f)} fields, {int(f.touches_end.sum())} reach an end of their section's map; "
          f"mean per cell {c.mean():.3f}; per animal {pd.Series(c).groupby(cells.animal.values, sort=False).mean().round(3).to_dict()}")
print(f"data set (F-b): {len(FIELDS['F-b'])} fields; mean per cell {COUNTS['F-b'].mean():.3f}")
MATCH = {}
for k, rule in (("F-a/P-a", "P-a"), ("F-a/P-b", "P-b")):
    m = rich.match_dataset_fields(animals, FIELDS[k], rule)
    MATCH[k] = m
    print(f"{k}: data set fields overlapped by a recomputed field {int(m.matched.sum())} of {len(m)}; "
          f"median peak shift {m.shift_cm.median():.1f} cm; missed, by the step that rejects them: "
          f"{m[~m.matched].step.value_counts().to_dict()}")
    fa = FIELDS[k]
    fb = FIELDS["F-b"]
    extra = 0
    for _, r in fa.iterrows():
        g = fb[(fb.ai == r.ai) & (fb.cell == r.cell) & (fb.epoch == r.epoch)]
        extra += int(not np.any((g.start_cm < r.end_cm) & (g.end_cm > r.start_cm)))
    print(f"     recomputed fields with no data set field overlapping: {extra} of {len(fa)}")
# Variant: 1 inch (2.54 cm) bins, as the data set's own maps, in place of the Methods' 1 cm.
for k, rule in (("F-a/P-a", "P-a"), ("F-a/P-b", "P-b")):
    f = rich.track_fields_binned(animals, rule, 2.54)
    m = rich.match_dataset_fields(animals, f, rule)
    print(f"{k} with 1 inch bins: {len(f)} fields, data set fields overlapped {int(m.matched.sum())} of {len(m)}")
# The data set's pass counts against the readings on the same field extents, by whether the
# field reaches an end of its section (problem 2): P-a counts are now taken to the section ends.
pc_end = pc.assign(at_end=[bool(r.start_cm <= rich.epoch_bins(animals[r.ai], r.epoch)[0] + rich.EDGE_CM
                                or r.end_cm >= rich.epoch_bins(animals[r.ai], r.epoch)[-1] - rich.EDGE_CM)
                           for _, r in FIELDS["F-b"][FIELDS["F-b"].direction < 3].iterrows()])
print(pc_end.groupby("at_end").apply(lambda g: pd.Series(dict(fields=len(g), exact_Pa=np.mean(g.dataset == g.Pa),
      exact_Pb=np.mean(g.dataset == g.Pb), mad_Pa=np.mean(np.abs(g.dataset - g.Pa)), mad_Pb=np.mean(np.abs(g.dataset - g.Pb))))).round(3).to_string())
P-a, first version: 791 fields, 0 reach an end of their section's map; mean per cell 3.126; per animal {'ANM00190422': 3.762, 'ANM204878': 2.207, 'ANM212379': 2.083, 'ANM228899': 3.158, 'ANM228900': 3.843}
F-a/P-a: 852 fields, 72 reach an end of their section's map; mean per cell 3.368; per animal {'ANM00190422': 3.968, 'ANM204878': 2.379, 'ANM212379': 2.333, 'ANM228899': 3.474, 'ANM228900': 4.118}
F-a/P-b: 793 fields, 64 reach an end of their section's map; mean per cell 3.134; per animal {'ANM00190422': 3.825, 'ANM204878': 2.207, 'ANM212379': 2.125, 'ANM228899': 3.053, 'ANM228900': 3.902}
data set (F-b): 887 fields; mean per cell 3.506
F-a/P-a: data set fields overlapped by a recomputed field 842 of 887; median peak shift 2.3 cm; missed, by the step that rejects them: {'passes': 29, 'width': 16}
     recomputed fields with no data set field overlapping: 42 of 852
F-a/P-b: data set fields overlapped by a recomputed field 787 of 887; median peak shift 2.3 cm; missed, by the step that rejects them: {'passes': 84, 'width': 16}
     recomputed fields with no data set field overlapping: 37 of 793
F-a/P-a with 1 inch bins: 852 fields, data set fields overlapped 840 of 887
F-a/P-b with 1 inch bins: 794 fields, data set fields overlapped 788 of 887
        fields  exact_Pa  exact_Pb  mad_Pa  mad_Pb
at_end                                            
False    670.0     0.499     0.396   1.181   2.199
True      50.0     0.560     0.340   0.860   2.960

Fields at the section ends and the fields the recomputation misses. The first version of P-a found 791 fields, none reaching an end of its section's map; with the allowance at the ends, P-a finds 852, of which 72 reach an end, and its per-animal means (3.968, 2.379, 2.333, 3.474, 4.118) move toward the data set's (4.190, 2.483, 2.292, 3.561, 4.333). P-b finds 793 (64 at an end). Of the data set's 887 fields, a recomputed field overlaps 842 under P-a and 787 under P-b; the 45 that P-a misses are rejected by the pass rule (29) or the 15 cm width (16), and P-b loses 84 to the pass rule. 42 of the 852 P-a fields have no data set field overlapping them. With 1 inch bins, as the data set's maps, P-a gives 852 fields and overlaps 840, so the bin width does not explain the remaining difference. On fields at the section ends the data set's pass counts agree exactly with P-a for 0.560 and with P-b for 0.340 (0.499 and 0.396 elsewhere).

Reading adopted where P-a and P-b give different outcomes: P-a, as an assumption. The Methods say passes "through the field", P-a recovers 95% of the data set's own fields against 89% for P-b, it gives all five per-animal means of Fig. S7A within 10% against three for P-b, and it is closer to the data set's own pass counts (mean absolute difference 1.16 against 2.25). The data set's rule matches neither exactly. The claims affected are marked. The allowance is varied in its own section, after figs11-no-boundary-remapping.

cell-counts¶

The study analysed 253 putative pyramidal cells from dorsal CA1 of five rats, 63, 58, 24, 57 and 51 per animal, each isolated in PRE sleep and tracked over the whole experiment.

In [10]:
paper = [63, 58, 24, 57, 51]
n_per = cells.groupby("animal", sort=False).size()
print(n_per.to_string())
print("total", int(n_per.sum()), "(expected 253 +/- 25.3)")
import itertools
best = min(itertools.permutations(paper), key=lambda pm: max(abs(n - q) / q for n, q in zip(n_per.values, pm)))
print("best one-to-one assignment of the paper's counts:", dict(zip(n_per.index, best)))
print("largest relative difference under it:", max(abs(n - q) / q for n, q in zip(n_per.values, best)))
animal
ANM00190422    63
ANM204878      58
ANM212379      24
ANM228899      57
ANM228900      51
total 253 (expected 253 +/- 25.3)
best one-to-one assignment of the paper's counts: {'ANM00190422': 63, 'ANM204878': 58, 'ANM212379': 24, 'ANM228899': 57, 'ANM228900': 51}
largest relative difference under it: 0.0

Result: reproduced. 253 cells, 63, 58, 24, 57 and 51 per animal, each equal to the paper's count under the identity assignment.

figs3-cluster-quality¶

The number of fields per cell is not correlated with the cluster quality of the unit, neither its L-ratio nor its isolation distance in RUN1.

Blocked: the file's L-ratio and isolation distance fields are NaN for every unit, and the data set holds only the spikes assigned to the sorted units, not the other threshold crossings of each tetrode that both measures compare a cluster with. The cell below shows a proxy, not the paper's measure, against the other sorted units of the same tetrode.

In [11]:
print("Finite L-ratio values in the file:", int(sum(np.isfinite(a["lratio"]).sum() for a in animals)),
      "; finite isolation distances:", int(sum(np.isfinite(a["isod"]).sum() for a in animals)))
print("Each epoch's own cluster info, spEpochSep[c, k].clustInf, fields:", animals[0]["cq_fieldnames"])
for a in animals:
    print(f"  {a['animal']}: units with a finite (L-ratio, isolation distance) per epoch column (PRE, RUN1, RUN2, RUN3):",
          [a["cq_epochs"][k] for k in sorted(a["cq_epochs"])], "of", len(a["cells"]))
# Variant only, not the paper's measure: L-ratio and isolation distance of each unit against
# the RUN1 spikes of the other sorted units on its tetrode (the file holds no unclustered spikes).
rows = []
for ai, a in enumerate(animals):
    feats = a["run1_features"]
    for k in range(len(a["cells"])):
        others = [feats[j] for j in range(len(a["cells"])) if j != k and a["tetrode"][j] == a["tetrode"][k] and len(feats[j])]
        if len(feats[k]) < 10 or not others:
            rows.append((ai, k, np.nan, np.nan))
            continue
        lr, iso = rich.cluster_quality(feats[k], np.vstack(others))
        rows.append((ai, k, lr, iso))
cq = pd.DataFrame(rows, columns=["ai", "cell", "lratio_proxy", "isod_proxy"])
print("units with a proxy L-ratio:", int(cq.lratio_proxy.notna().sum()), "of", len(cq),
      "; with a proxy isolation distance:", int(cq.isod_proxy.notna().sum()))
for k in MAIN + ["F-b"]:
    for col in ["lratio_proxy", "isod_proxy"]:
        ok = cq[col].notna().values
        rho, p = stats.spearmanr(cq[col].values[ok], COUNTS[k][ok])
        print(f"  variant {k}: Spearman fields vs {col}: rho {rho:.3f}, p {p:.3g}, n {ok.sum()}")
Finite L-ratio values in the file: 0 ; finite isolation distances: 0
Each epoch's own cluster info, spEpochSep[c, k].clustInf, fields: ['epoch', 'score', 'ID', 'cellNum', 'notes', 'dataFile', 'notesFile', 'method', 'user', 'epochTimes', 'TT', 'region', 'depth', 'Lratio', 'IsoD', 'scoreNum', 'fullDataFile', 'animal', 'session', 'dataDir']
  ANM00190422: units with a finite (L-ratio, isolation distance) per epoch column (PRE, RUN1, RUN2, RUN3): [(0, 0), (0, 0), (0, 0), (0, 0)] of 63
  ANM204878: units with a finite (L-ratio, isolation distance) per epoch column (PRE, RUN1, RUN2, RUN3): [(0, 0), (0, 0), (0, 0), (0, 0)] of 58
  ANM212379: units with a finite (L-ratio, isolation distance) per epoch column (PRE, RUN1, RUN2, RUN3): [(0, 0), (0, 0), (0, 0), (0, 0)] of 24
  ANM228899: units with a finite (L-ratio, isolation distance) per epoch column (PRE, RUN1, RUN2, RUN3): [(0, 0), (0, 0), (0, 0), (0, 0)] of 57
  ANM228900: units with a finite (L-ratio, isolation distance) per epoch column (PRE, RUN1, RUN2, RUN3): [(0, 0), (0, 0), (0, 0), (0, 0)] of 51
units with a proxy L-ratio: 213 of 253 ; with a proxy isolation distance: 195
  variant F-a/P-a: Spearman fields vs lratio_proxy: rho -0.176, p 0.0102, n 213
  variant F-a/P-a: Spearman fields vs isod_proxy: rho 0.437, p 1.62e-10, n 195
  variant F-a/P-b: Spearman fields vs lratio_proxy: rho -0.165, p 0.016, n 213
  variant F-a/P-b: Spearman fields vs isod_proxy: rho 0.411, p 2.41e-09, n 195
  variant F-b: Spearman fields vs lratio_proxy: rho -0.172, p 0.0118, n 213
  variant F-b: Spearman fields vs isod_proxy: rho 0.439, p 1.39e-10, n 195

Result: blocked (data missing). The file has no finite L-ratio or isolation distance, either in the units' overall cluster info or in each epoch's own (spEpochSep, PRE, RUN1, RUN2 and RUN3: 0 of 253 units in every column), and the paper's measures need the tetrodes' unclustered spikes, which are not in the data set. The proxy, computed against other sorted units only, correlates with the number of fields (rho -0.176 and 0.437 under F-a/P-a); it measures something else and decides nothing.

fig1-recruitment-by-section¶

In each new section of track, existing place cells formed additional fields and new place cells were recruited from cells silent until then.

In [12]:
rows = []
for k in MAIN + ["F-b"]:
    f = FIELDS[k]
    for e in (1, 2, 3):
        earlier = set(map(tuple, f[f.epoch < e][["ai", "cell"]].values))
        now = set(map(tuple, f[f.epoch == e][["ai", "cell"]].values))
        for ai, an in enumerate(ANIMALS):
            ex = sum(1 for c in now if c in earlier and c[0] == ai)
            new = sum(1 for c in now if c not in earlier and c[0] == ai)
            rows.append(dict(reading=k, epoch=e + 1, animal=an, existing_with_new_field=ex, newly_recruited=new))
rec = pd.DataFrame(rows)
pooled = rec.groupby(["reading", "epoch"])[["existing_with_new_field", "newly_recruited"]].sum()
print(pooled.to_string())
print()
print(rec.pivot_table(index=["reading", "animal"], columns="epoch",
                      values=["existing_with_new_field", "newly_recruited"]).to_string())
for k in MAIN + ["F-b"]:
    ok = (pooled.loc[k] >= 1).all(axis=1)
    print(f"{k}: epochs where both counts are at least one: {int(ok.sum())} of 3")
               existing_with_new_field  newly_recruited
reading epoch                                          
F-a/P-a 2                           36               38
        3                           63               29
        4                          107               36
F-a/P-b 2                           31               31
        3                           55               31
        4                           97               43
F-b     2                           38               37
        3                           62               31
        4                          106               39

                    existing_with_new_field             newly_recruited           
epoch                                     2     3     4               2    3     4
reading animal                                                                    
F-a/P-a ANM00190422                    15.0  19.0  30.0             6.0  7.0   9.0
        ANM204878                       5.0   7.0  13.0             3.0  6.0   7.0
        ANM212379                       3.0   4.0   6.0             5.0  1.0   5.0
        ANM228899                       6.0  17.0  31.0            15.0  8.0   7.0
        ANM228900                       7.0  16.0  27.0             9.0  7.0   8.0
F-a/P-b ANM00190422                    15.0  17.0  29.0             6.0  8.0  10.0
        ANM204878                       5.0   7.0  11.0             2.0  6.0   8.0
        ANM212379                       2.0   3.0   5.0             2.0  2.0   5.0
        ANM228899                       4.0  13.0  27.0            13.0  9.0  10.0
        ANM228900                       5.0  15.0  25.0             8.0  6.0  10.0
F-b     ANM00190422                    15.0  19.0  30.0             6.0  8.0   9.0
        ANM204878                       5.0   7.0  12.0             3.0  6.0  10.0
        ANM212379                       3.0   4.0   6.0             5.0  1.0   5.0
        ANM228899                       8.0  17.0  30.0            15.0  8.0   8.0
        ANM228900                       7.0  15.0  28.0             8.0  8.0   7.0
F-a/P-a: epochs where both counts are at least one: 3 of 3
F-a/P-b: epochs where both counts are at least one: 3 of 3
F-b: epochs where both counts are at least one: 3 of 3

Result: reproduced. In each of epochs 2, 3 and 4, pooled over animals, cells with earlier fields formed new fields (36, 63 and 107 under P-a; 31, 55 and 97 under P-b) and cells without earlier fields formed their first (38, 29 and 36 under P-a; 31, 31 and 43 under P-b). Every animal has at least one of each kind in every epoch.

In [13]:
def cell_fields(f):
    """Locations of each cell's fields, in metres from the start, clipped to 0 to 48 m."""
    out = {}
    for (ai, c), g in f.groupby(["ai", "cell"]):
        out[(ai, c)] = np.sort(np.clip(g.loc_m.values, 0, rich.TRACK_M))
    return out

fig2-individual-poisson¶

For the 61 of 253 cells with at least six fields, neither the field locations nor the inter-field intervals differ from a Poisson process (uniform locations, exponential intervals); no cell is significant by the Anderson-Darling test after false discovery rate adjustment.

P-values by Monte Carlo (20000 samples per test) of the A2 statistic under the null; E-a re-estimates the mean in every null sample, E-b takes it as known.

In [14]:
rng_fig2 = np.random.default_rng(20140815)
fig2 = {}
for k in MAIN + ["F-b"]:
    cf = cell_fields(FIELDS[k])
    many = {key: v for key, v in cf.items() if len(v) >= 6}
    rows = []
    for key, loc in many.items():
        _, p_loc = rich.ad_uniform_p(loc, 0, rich.TRACK_M, rng_fig2)
        iv = np.diff(loc)
        iv = np.where(iv > 0, iv, 1e-6)
        _, p_ea = rich.ad_exponential_p(iv, rng_fig2, composite=True)
        _, p_eb = rich.ad_exponential_p(iv, rng_fig2, composite=False)
        rows.append(dict(ai=key[0], cell=key[1], n=len(loc), p_loc=p_loc, p_int_Ea=p_ea, p_int_Eb=p_eb))
    t = pd.DataFrame(rows)
    fig2[k] = t
    n6 = len(t)
    res = []
    for E in ("Ea", "Eb"):
        pi = t[f"p_int_{E}"].values
        sa_loc, sa_int = rich.bh(t.p_loc.values), rich.bh(pi)
        sb = rich.bh(np.concatenate([t.p_loc.values, pi]))
        n_sa = int(np.sum((sa_loc < 0.05) | (sa_int < 0.05)))
        n_sb = int(np.sum((sb[:n6] < 0.05) | (sb[n6:] < 0.05)))
        res.append(f"E-{E[1]}: S-a {n_sa} cells, S-b {n_sb} cells")
    print(f"{k}: cells with >= 6 fields {n6} (expected 61 +/- 6.1); per animal "
          f"{t.groupby('ai').size().reindex(range(5), fill_value=0).tolist()}; "
          f"significant after FDR: {'; '.join(res)}")
    print(f"   unadjusted p < 0.05: locations {int((t.p_loc < 0.05).sum())}, intervals E-a "
          f"{int((t.p_int_Ea < 0.05).sum())}, E-b {int((t.p_int_Eb < 0.05).sum())}; "
          f"smallest p: loc {t.p_loc.min():.4f}, E-a {t.p_int_Ea.min():.4f}, E-b {t.p_int_Eb.min():.4f}")
F-a/P-a: cells with >= 6 fields 62 (expected 61 +/- 6.1); per animal [17, 11, 3, 13, 18]; significant after FDR: E-a: S-a 0 cells, S-b 0 cells; E-b: S-a 0 cells, S-b 0 cells
   unadjusted p < 0.05: locations 7, intervals E-a 7, E-b 0; smallest p: loc 0.0097, E-a 0.0046, E-b 0.0686
F-a/P-b: cells with >= 6 fields 56 (expected 61 +/- 6.1); per animal [18, 9, 2, 11, 16]; significant after FDR: E-a: S-a 0 cells, S-b 0 cells; E-b: S-a 0 cells, S-b 0 cells
   unadjusted p < 0.05: locations 7, intervals E-a 4, E-b 0; smallest p: loc 0.0054, E-a 0.0238, E-b 0.1553
F-b: cells with >= 6 fields 61 (expected 61 +/- 6.1); per animal [18, 10, 3, 14, 16]; significant after FDR: E-a: S-a 1 cells, S-b 0 cells; E-b: S-a 1 cells, S-b 0 cells
   unadjusted p < 0.05: locations 6, intervals E-a 6, E-b 0; smallest p: loc 0.0008, E-a 0.0041, E-b 0.0617

Result: reproduced. 62 cells (P-a) and 56 (P-b) have six or more fields, within 61 +/- 6.1, and no cell is significant after the Benjamini-Hochberg adjustment under any reading (E-a or E-b, S-a or S-b). Before adjustment, 7 location tests (both readings) and up to 7 interval tests have p < 0.05. The data set's fields give 61 cells, one of them significant under S-a (none under S-b).

fig2bc-population-bias¶

Across the cells with at least six fields there is no overall bias in field location or interval; the median field location and the normalized deviation of the median inter-field interval from its exponential expectation follow the distributions expected for uniform and exponential fields.

In [15]:
rng_fig2bc = np.random.default_rng(2)
for k in MAIN + ["F-b"]:
    cf = cell_fields(FIELDS[k])
    many = [v for v in cf.values() if len(v) >= 6]
    obs_m, obs_d, null_m, null_d, pct_m, pct_d = [], [], [], [], [], []
    for loc in many:
        n = len(loc)
        iv = np.diff(loc)
        mu = iv.mean()
        om = np.median(loc)
        od = (np.median(iv) - mu * np.log(2)) / mu
        sm = np.median(rng_fig2bc.uniform(0, rich.TRACK_M, (5000, n)), axis=1)
        si = rng_fig2bc.exponential(mu, (5000, n - 1))
        sd = (np.median(si, axis=1) - si.mean(axis=1) * np.log(2)) / si.mean(axis=1)
        obs_m.append(om); obs_d.append(od); null_m.append(sm); null_d.append(sd)
        pct_m.append((np.sum(sm < om) + 0.5 * np.sum(sm == om)) / 5000)
        pct_d.append((np.sum(sd < od) + 0.5 * np.sum(sd == od)) / 5000)
    ca_m = stats.ks_2samp(obs_m, np.concatenate(null_m))
    ca_d = stats.ks_2samp(obs_d, np.concatenate(null_d))
    cb_m = stats.kstest(pct_m, "uniform")
    cb_d = stats.kstest(pct_d, "uniform")
    print(f"{k} (n = {len(many)} cells): median location, observed mean {np.mean(obs_m):.2f} m, null mean "
          f"{np.mean(np.concatenate(null_m)):.2f} m; C-a KS {ca_m.statistic:.3f} p {ca_m.pvalue:.3f}; "
          f"C-b KS {cb_m.statistic:.3f} p {cb_m.pvalue:.3f}")
    print(f"     interval deviation, observed mean {np.mean(obs_d):.3f}, null mean {np.mean(np.concatenate(null_d)):.3f}; "
          f"C-a KS {ca_d.statistic:.3f} p {ca_d.pvalue:.3f}; C-b KS {cb_d.statistic:.3f} p {cb_d.pvalue:.3f}")
F-a/P-a (n = 62 cells): median location, observed mean 23.05 m, null mean 24.02 m; C-a KS 0.122 p 0.292; C-b KS 0.133 p 0.201
     interval deviation, observed mean 0.063, null mean 0.066; C-a KS 0.061 p 0.966; C-b KS 0.060 p 0.968
F-a/P-b (n = 56 cells): median location, observed mean 23.58 m, null mean 23.99 m; C-a KS 0.105 p 0.528; C-b KS 0.098 p 0.619
     interval deviation, observed mean 0.036, null mean 0.066; C-a KS 0.105 p 0.529; C-b KS 0.091 p 0.707
F-b (n = 61 cells): median location, observed mean 23.12 m, null mean 24.01 m; C-a KS 0.108 p 0.450; C-b KS 0.097 p 0.577
     interval deviation, observed mean 0.044, null mean 0.063; C-a KS 0.073 p 0.873; C-b KS 0.065 p 0.941

Result: reproduced. Neither statistic differs from its null under either reading: for the median location, KS p 0.292 (C-a) and 0.201 (C-b) under P-a, 0.528 and 0.619 under P-b; for the interval deviation, 0.966 and 0.968 under P-a, 0.529 and 0.707 under P-b.

figs6-few-field-cells-uniform¶

For cells with fewer than six fields, the pooled field locations of cells with the same number of fields do not differ from uniform (0 of 5 groups significant).

In [16]:
rng_s6 = np.random.default_rng(6)
for k in MAIN + ["F-b"]:
    cf = cell_fields(FIELDS[k])
    ps, desc = [], []
    for n in range(1, 6):
        pooled = np.concatenate([v for v in cf.values() if len(v) == n] or [np.array([])])
        a2, p = rich.ad_uniform_p(pooled, 0, rich.TRACK_M, rng_s6)
        ps.append(p)
        desc.append(f"{n}: {len(pooled) // n} cells, A2 {a2:.2f}, p {p:.3f}")
    adj = rich.bh(ps)
    print(f"{k}: " + "; ".join(desc))
    print(f"     BH-adjusted p: {np.round(adj, 3).tolist()}; groups with adjusted p < 0.05: {int((adj < 0.05).sum())}")
F-a/P-a: 1: 32 cells, A2 0.83, p 0.467; 2: 19 cells, A2 1.11, p 0.300; 3: 22 cells, A2 2.15, p 0.075; 4: 15 cells, A2 1.31, p 0.231; 5: 12 cells, A2 1.41, p 0.194
     BH-adjusted p: [0.467, 0.375, 0.374, 0.375, 0.375]; groups with adjusted p < 0.05: 0
F-a/P-b: 1: 33 cells, A2 0.93, p 0.396; 2: 24 cells, A2 1.70, p 0.136; 3: 14 cells, A2 1.54, p 0.175; 4: 22 cells, A2 3.97, p 0.009; 5: 10 cells, A2 1.19, p 0.272
     BH-adjusted p: [0.396, 0.292, 0.292, 0.044, 0.34]; groups with adjusted p < 0.05: 1
F-b: 1: 33 cells, A2 0.62, p 0.625; 2: 24 cells, A2 1.06, p 0.325; 3: 14 cells, A2 2.72, p 0.038; 4: 17 cells, A2 1.16, p 0.284; 5: 16 cells, A2 1.55, p 0.166
     BH-adjusted p: [0.625, 0.406, 0.188, 0.406, 0.406]; groups with adjusted p < 0.05: 0

Result: reproduced, resting on the assumption P-a. Under P-a no group has an adjusted p < 0.05 (smallest 0.374). Under P-b one group, cells with four fields, has an adjusted p of 0.044, which the criterion counts as partially reproduced. The data set's fields give none (smallest 0.188).

In [17]:
def dispersion_tests(x):
    x = np.asarray(x, float)
    n, m, v = len(x), x.mean(), x.var(ddof=1)
    D = np.sum((x - m) ** 2) / m
    p_da = stats.chi2.sf(D, n - 1)
    r, p, ll_nb = rich.nbinfit(x)
    ll_po = np.sum(stats.poisson.logpmf(x, m))
    lr = max(2 * (ll_nb - ll_po), 0)
    p_db = 0.5 * stats.chi2.sf(lr, 1)
    return dict(n=n, mean=m, var=v, zeros=int(np.sum(x == 0)), zeros_poisson=n * np.exp(-m),
                D=D, p_Da=p_da, LR=lr, p_Db=p_db)

fig3b-overdispersion¶

The number of fields per cell is overdispersed relative to the equal-rate Poisson model, a few cells having many fields and many more cells than expected having few or none, so that model fits the field counts poorly, in the pooled data and in each animal.

In [18]:
for k in MAIN + ["F-b"]:
    rows = [dict(group="pooled", **dispersion_tests(COUNTS[k]))]
    for ai, an in enumerate(ANIMALS):
        rows.append(dict(group=an, **dispersion_tests(COUNTS[k][cells.ai.values == ai])))
    t = pd.DataFrame(rows)
    t["holds"] = (t["var"] > t["mean"]) & (t.zeros > t.zeros_poisson) & (t.p_Da < 0.05) & (t.p_Db < 0.05)
    print(k)
    print(t.round({"mean": 3, "var": 3, "zeros_poisson": 1, "D": 1, "LR": 1}).to_string(index=False,
          formatters={"p_Da": "{:.2e}".format, "p_Db": "{:.2e}".format}))
    print(f"   animals where it holds: {int(t.holds[1:].sum())} of 5\n")
F-a/P-a
      group   n  mean    var  zeros  zeros_poisson      D      p_Da    LR      p_Db  holds
     pooled 253 3.368 18.210     91            8.7 1362.6 1.23e-151 622.1 1.31e-137   True
ANM00190422  63 3.968 22.773     20            1.2  355.8  7.92e-43 177.6  8.18e-41   True
  ANM204878  58 2.379 19.994     33            5.4  479.0  5.18e-68 207.6  2.35e-47   True
  ANM212379  24 2.333  9.884     10            2.3   97.4  3.90e-11  36.0  9.89e-10   True
  ANM228899  57 3.474 13.254     13            1.8  213.7  2.92e-20  78.8  3.37e-19   True
  ANM228900  51 4.118 18.666     15            0.8  226.7  2.49e-24 103.2  1.50e-24   True
   animals where it holds: 5 of 5

F-a/P-b
      group   n  mean    var  zeros  zeros_poisson      D      p_Da    LR      p_Db  holds
     pooled 253 3.134 16.323     94           11.0 1312.4 9.33e-143 580.0 1.84e-128   True
ANM00190422  63 3.825 20.888     20            1.4  338.5  1.01e-39 165.5  3.59e-38   True
  ANM204878  58 2.207 17.325     33            6.4  447.5  5.61e-62 187.2  6.46e-43   True
  ANM212379  24 2.125  9.679     12            2.9  104.8  2.10e-12  40.6  9.44e-11   True
  ANM228899  57 3.053 10.729     14            2.7  196.8  1.49e-17  68.5  6.28e-17   True
  ANM228900  51 3.902 17.450     15            1.0  223.6  8.28e-24  96.3  5.00e-23   True
   animals where it holds: 5 of 5

F-b
      group   n  mean    var  zeros  zeros_poisson      D      p_Da    LR      p_Db  holds
     pooled 253 3.506 20.814     88            7.6 1496.1 1.48e-175 675.9 2.54e-149   True
ANM00190422  63 4.190 25.350     19            1.0  375.1  2.51e-46 189.2  2.39e-43   True
  ANM204878  58 2.483 23.833     31            4.8  547.2  3.10e-81 220.1  4.31e-50   True
  ANM212379  24 2.292  9.085     10            2.4   91.2  4.50e-10  33.2  4.11e-09   True
  ANM228899  57 3.561 14.108     13            1.6  221.8  1.34e-21  84.4  1.99e-20   True
  ANM228900  51 4.333 23.107     15            0.7  266.6  2.48e-31 122.1  1.11e-28   True
   animals where it holds: 5 of 5

Result: reproduced. Pooled, the variance is 18.210 against a mean of 3.368 (P-a), 91 cells have no field against 8.7 expected, and both tests give p below 1e-120. Each of the five animals meets all three conditions under both readings, with p at most 9.9e-10.

figs7a-mean-fields-per-animal¶

The mean number of fields per cell (the equal-rate Poisson rate) is 3.56, 4.19, 4.33, 2.29 and 2.48 in the five animals.

In [19]:
expected = {"ANM228899": 3.56, "ANM00190422": 4.19, "ANM228900": 4.33, "ANM212379": 2.29, "ANM204878": 2.48}
t = pd.DataFrame({k: pd.Series(COUNTS[k]).groupby(cells.animal.values).mean() for k in MAIN + ["F-b"]})
t["expected"] = pd.Series(expected)
for k in MAIN + ["F-b"]:
    t[f"within 10% ({k})"] = (t[k] - t.expected).abs() <= 0.1 * t.expected + 1e-9
print(t.round(3).to_string())
for k in MAIN + ["F-b"]:
    print(f"{k}: {int(t[f'within 10% ({k})'].sum())} of 5 within tolerance")
             F-a/P-a  F-a/P-b    F-b  expected  within 10% (F-a/P-a)  within 10% (F-a/P-b)  within 10% (F-b)
ANM00190422    3.968    3.825  4.190      4.19                  True                  True              True
ANM204878      2.379    2.207  2.483      2.48                  True                 False              True
ANM212379      2.333    2.125  2.292      2.29                  True                  True              True
ANM228899      3.474    3.053  3.561      3.56                  True                 False              True
ANM228900      4.118    3.902  4.333      4.33                  True                  True              True
F-a/P-a: 5 of 5 within tolerance
F-a/P-b: 3 of 5 within tolerance
F-b: 5 of 5 within tolerance

Result: reproduced. Under P-a all five animal means are within 10% (3.968, 2.379, 2.333, 3.474 and 4.118 against 4.19, 2.48, 2.29, 3.56 and 4.33). Under P-b three are (2.207 and 3.053 fall below 2.48 and 3.56). The data set's own counts give 4.190, 2.483, 2.292, 3.561 and 4.333. In the first version of this notebook P-a dropped fields at the section ends and gave one of five. With no allowance at the section ends one mean of five is within 10%; with any allowance from 0 to 30 cm all five are (sensitivity section).

fig3b-negbin-fit¶

The number of fields per cell is well fit by a negative binomial distribution with r = 0.57 and p = 0.14, which arises when each cell is a Poisson process whose rate is drawn from a gamma distribution.

In [20]:
NB = {}
for k in MAIN + ["F-b"]:
    r, p, ll = rich.nbinfit(COUNTS[k])
    NB[k] = (r, p)
    print(f"{k}: r {r:.4f} (expected 0.57 +/- 0.057), p {p:.4f} (expected 0.14 +/- 0.014), "
          f"mean r(1-p)/p {r * (1 - p) / p:.3f}, observed mean {COUNTS[k].mean():.3f}, n {len(COUNTS[k])}")
for k in MAIN + ["F-b"]:
    r, p = NB[k]
    x = COUNTS[k]
    obs = np.bincount(x, minlength=25)[:25]
    exp_nb = len(x) * np.exp(rich.nb_logpmf(np.arange(25), r, p))
    exp_po = len(x) * stats.poisson.pmf(np.arange(25), x.mean())
    print(k, "fields 0..12, observed:", obs[:13].tolist())
    print("     negative binomial:", np.round(exp_nb[:13], 1).tolist())
    print("     equal-rate Poisson:", np.round(exp_po[:13], 1).tolist())
fig, ax = plt.subplots(1, 3, figsize=(12, 3))
for i, k in enumerate(MAIN + ["F-b"]):
    x = COUNTS[k]
    ax[i].bar(np.arange(25), np.bincount(x, minlength=25)[:25], color="0.6")
    ax[i].plot(np.arange(25), len(x) * np.exp(rich.nb_logpmf(np.arange(25), *NB[k])), "r.-")
    ax[i].plot(np.arange(25), len(x) * stats.poisson.pmf(np.arange(25), x.mean()), "k.-")
    ax[i].set_title(k); ax[i].set_xlabel("fields per cell")
plt.show()
print("x axis 0 to 24 fields; cells beyond:", {k: int((COUNTS[k] > 24).sum()) for k in MAIN + ["F-b"]})
F-a/P-a: r 0.5626 (expected 0.57 +/- 0.057), p 0.1432 (expected 0.14 +/- 0.014), mean r(1-p)/p 3.368, observed mean 3.368, n 253
F-a/P-b: r 0.5548 (expected 0.57 +/- 0.057), p 0.1504 (expected 0.14 +/- 0.014), mean r(1-p)/p 3.134, observed mean 3.134, n 253
F-b: r 0.5653 (expected 0.57 +/- 0.057), p 0.1388 (expected 0.14 +/- 0.014), mean r(1-p)/p 3.506, observed mean 3.506, n 253
F-a/P-a fields 0..12, observed: [91, 32, 19, 22, 15, 12, 15, 8, 8, 5, 3, 6, 8]
     negative binomial: [84.8, 40.9, 27.4, 20.0, 15.3, 11.9, 9.5, 7.6, 6.2, 5.0, 4.1, 3.4, 2.8]
     equal-rate Poisson: [8.7, 29.4, 49.5, 55.5, 46.7, 31.5, 17.7, 8.5, 3.6, 1.3, 0.5, 0.1, 0.0]
F-a/P-b fields 0..12, observed: [94, 33, 24, 14, 22, 10, 9, 10, 8, 9, 4, 3, 6]
     negative binomial: [88.4, 41.7, 27.5, 19.9, 15.0, 11.6, 9.2, 7.3, 5.8, 4.7, 3.8, 3.1, 2.6]
     equal-rate Poisson: [11.0, 34.5, 54.1, 56.5, 44.3, 27.8, 14.5, 6.5, 2.5, 0.9, 0.3, 0.1, 0.0]
F-b fields 0..12, observed: [88, 33, 24, 14, 17, 16, 11, 8, 10, 5, 4, 7, 5]
     negative binomial: [82.9, 40.3, 27.2, 20.0, 15.4, 12.1, 9.7, 7.8, 6.3, 5.2, 4.3, 3.5, 2.9]
     equal-rate Poisson: [7.6, 26.6, 46.7, 54.5, 47.8, 33.5, 19.6, 9.8, 4.3, 1.7, 0.6, 0.2, 0.1]
No description has been provided for this image
x axis 0 to 24 fields; cells beyond: {'F-a/P-a': 1, 'F-a/P-b': 0, 'F-b': 2}

Result: reproduced. r = 0.563 and p = 0.143 under P-a, r = 0.555 and p = 0.150 under P-b, both within tolerance (0.57 +/- 0.057, 0.14 +/- 0.014). The data set's fields give r = 0.565 and p = 0.139.

fig3c-recruitment-fraction¶

Recruitment of cells into the representation reached only about 65% at 48 m (46 to 77% across animals), far below the equal-rate Poisson prediction; about 35% of cells stayed silent.

In [21]:
for k in MAIN + ["F-b"]:
    x = COUNTS[k]
    per = pd.Series(x > 0).groupby(cells.animal.values).mean() * 100
    pred = 100 * (1 - np.exp(-x.mean()))
    print(f"{k}: pooled {100 * np.mean(x > 0):.1f}% (expected 65 +/- 6.5); per animal "
          f"{per.round(1).to_dict()}; lowest {per.min():.1f}, highest {per.max():.1f} (inside 41.4 to 84.7: "
          f"{bool(per.min() >= 41.4 and per.max() <= 84.7)}); equal-rate prediction {pred:.1f}%")
F-a/P-a: pooled 64.0% (expected 65 +/- 6.5); per animal {'ANM00190422': 68.3, 'ANM204878': 43.1, 'ANM212379': 58.3, 'ANM228899': 77.2, 'ANM228900': 70.6}; lowest 43.1, highest 77.2 (inside 41.4 to 84.7: True); equal-rate prediction 96.6%
F-a/P-b: pooled 62.8% (expected 65 +/- 6.5); per animal {'ANM00190422': 68.3, 'ANM204878': 43.1, 'ANM212379': 50.0, 'ANM228899': 75.4, 'ANM228900': 70.6}; lowest 43.1, highest 75.4 (inside 41.4 to 84.7: True); equal-rate prediction 95.6%
F-b: pooled 65.2% (expected 65 +/- 6.5); per animal {'ANM00190422': 69.8, 'ANM204878': 46.6, 'ANM212379': 58.3, 'ANM228899': 77.2, 'ANM228900': 70.6}; lowest 46.6, highest 77.2 (inside 41.4 to 84.7: True); equal-rate prediction 97.0%

Result: reproduced. 64.0% (P-a) and 62.8% (P-b) of cells have a field (65 +/- 6.5); the animals range from 43.1 to 77.2% (P-a) and 43.1 to 75.4% (P-b), inside 41.4 to 84.7%; the equal-rate Poisson predictions are 96.6% and 95.6%.

In [22]:
def lomax_test(first, r, p, length, rng, n_mc=2000, refit=False, n_cells=None):
    """KS distance of the observed recruitment curve from the Lomax, and its Monte Carlo p.
    refit=False is K-a (surrogates from the fitted Lomax, parameters fixed); refit=True is
    K-b (counts drawn from the fitted gamma-Poisson, parameters refitted per surrogate)."""
    F = lambda x: rich.lomax_cdf(x, r, p)
    d = rich.censored_ks(first, F, length)
    n = len(first) if n_cells is None else n_cells
    null = np.empty(n_mc)
    for i in range(n_mc):
        if not refit:
            s = rich.lomax_inverse(rng.random(n), r, p)
            s[s > length] = np.nan
            null[i] = rich.censored_ks(s, F, length)
        else:
            lam = rng.gamma(r, (1 - p) / p, n)  # fields per 48 m
            cnt = rng.poisson(lam)
            rr, pp, _ = rich.nbinfit(cnt) if cnt.sum() else (r, p, 0)
            s = np.full(n, np.nan)
            has = cnt > 0
            s[has] = np.array([rng.uniform(0, rich.TRACK_M, c).min() for c in cnt[has]])
            s[s > length] = np.nan
            null[i] = rich.censored_ks(s, lambda x: rich.lomax_cdf(x, rr, pp), length)
    return d, float((np.sum(null >= d) + 1) / (n_mc + 1))

fig3c-lomax-recruitment¶

The recruitment curve (the location of each cell's field nearest the start) matches the Lomax (Pareto type II) curve predicted by the gamma-Poisson model fitted to the field counts (Kolmogorov-Smirnov statistic 0.05, P = 0.48), while the equal-rate Poisson model's exponential curve fits poorly.

In [23]:
rng_3c = np.random.default_rng(3)
FIRST = {}
for k in MAIN + ["F-b"]:
    first = rich.first_field(FIELDS[k], cells)
    first = np.clip(first, 0, rich.TRACK_M)
    FIRST[k] = first
    r, p = NB[k]
    d, p_ka = lomax_test(first, r, p, rich.TRACK_M, rng_3c)
    _, p_kb = lomax_test(first, r, p, rich.TRACK_M, rng_3c, refit=True)
    obs48 = np.mean(np.isfinite(first))
    pois48 = 1 - np.exp(-COUNTS[k].mean())
    F_pois = lambda x, m=COUNTS[k].mean(): 1 - np.exp(-m * np.asarray(x) / rich.TRACK_M)
    d_pois = rich.censored_ks(first, F_pois, rich.TRACK_M)
    print(f"{k}: KS {d:.4f} (expected 0.05 +/- 0.005), p K-a {p_ka:.3f}, p K-b {p_kb:.3f}; "
          f"observed at 48 m {obs48:.3f}, Lomax {rich.lomax_cdf(48, r, p):.3f}, equal-rate Poisson {pois48:.3f}; "
          f"KS of the Poisson curve {d_pois:.3f}")
xs = np.linspace(0, 48, 481)
plt.figure(figsize=(5, 3.5))
for k, c in zip(MAIN + ["F-b"], ["k", "b", "g"]):
    obs = [np.mean(FIRST[k] <= x) for x in xs]
    plt.plot(xs, obs, c, label=f"observed {k}")
    plt.plot(xs, rich.lomax_cdf(xs, *NB[k]), c + "--", lw=0.8)
plt.plot(xs, 1 - np.exp(-COUNTS["F-a/P-a"].mean() * xs / 48), "0.5", label="equal-rate Poisson (P-a)")
plt.xlabel("track length (m)"); plt.ylabel("fraction recruited"); plt.ylim(0, 1); plt.legend(fontsize=7)
plt.show()
print("plotted fractions lie in 0 to 1 by construction")
F-a/P-a: KS 0.0600 (expected 0.05 +/- 0.005), p K-a 0.271, p K-b 0.062; observed at 48 m 0.640, Lomax 0.665, equal-rate Poisson 0.966; KS of the Poisson curve 0.336
F-a/P-b: KS 0.0537 (expected 0.05 +/- 0.005), p K-a 0.394, p K-b 0.121; observed at 48 m 0.628, Lomax 0.650, equal-rate Poisson 0.956; KS of the Poisson curve 0.336
F-b: KS 0.0486 (expected 0.05 +/- 0.005), p K-a 0.518, p K-b 0.248; observed at 48 m 0.652, Lomax 0.672, equal-rate Poisson 0.970; KS of the Poisson curve 0.337
No description has been provided for this image
plotted fractions lie in 0 to 1 by construction

Result: partially reproduced, resting on the assumption P-a. Under P-a the KS statistic is 0.060, above the tolerance of 0.05 +/- 0.005, and p is 0.271 (K-a) and 0.062 (K-b). Under P-b the statistic is 0.054 with p 0.394 and 0.121, which the criterion counts as reproduced. Under both readings the equal-rate curve is far above the observed one at 48 m (0.966 and 0.956 against 0.640 and 0.628), with a KS distance of 0.336. The data set's fields give 0.049 (p 0.518 and 0.248). The KS statistic also depends on the end allowance of P-a: it is 0.0532, within tolerance, at 10 cm, and 0.0598 to 0.0600 from 15 cm (sensitivity section).

fig3c-extrapolation-500m¶

Extrapolated, the gamma-Poisson recruitment curve reaches 90% recruitment at about 500 m.

In [24]:
for k in MAIN + ["F-b"]:
    r, p = NB[k]
    print(f"{k}: 90% recruitment at {rich.lomax_inverse(0.9, r, p):.0f} m (expected 500 +/- 50)")
print(f"printed parameters r 0.57, p 0.14: {rich.lomax_inverse(0.9, 0.57, 0.14):.0f} m")
F-a/P-a: 90% recruitment at 472 m (expected 500 +/- 50)
F-a/P-b: 90% recruitment at 531 m (expected 500 +/- 50)
F-b: 90% recruitment at 447 m (expected 500 +/- 50)
printed parameters r 0.57, p 0.14: 436 m

Result: reproduced. The fitted Lomax reaches 90% at 472 m (P-a) and 531 m (P-b), within 500 +/- 50 m. The printed parameters give 436 m and the data set's fields 447 m, so the result rests on the fitted parameters.

fig3d-uniform-density¶

Overall field density is uniform along the track; the distribution of all fields across animals does not differ from a constant density (Kolmogorov-Smirnov statistic 0.03, P = 0.36).

In [25]:
for k in MAIN + ["F-b"]:
    loc = np.clip(FIELDS[k].loc_m.values, 0, rich.TRACK_M)
    ks = stats.kstest(loc, "uniform", args=(0, rich.TRACK_M))
    per = {an: round(float(stats.kstest(np.clip(FIELDS[k][FIELDS[k].animal == an].loc_m.values, 0, 48), "uniform", args=(0, 48)).statistic), 3) for an in ANIMALS}
    perp = {an: round(float(stats.kstest(np.clip(FIELDS[k][FIELDS[k].animal == an].loc_m.values, 0, 48), "uniform", args=(0, 48)).pvalue), 3) for an in ANIMALS}
    print(f"{k}: n {len(loc)} fields, KS {ks.statistic:.4f} (expected 0.03 +/- 0.003), p {ks.pvalue:.3f}")
    print(f"     per animal KS {per}; p {perp}")
F-a/P-a: n 852 fields, KS 0.0315 (expected 0.03 +/- 0.003), p 0.360
     per animal KS {'ANM00190422': 0.063, 'ANM204878': 0.109, 'ANM212379': 0.089, 'ANM228899': 0.062, 'ANM228900': 0.102}; p {'ANM00190422': 0.27, 'ANM204878': 0.069, 'ANM212379': 0.739, 'ANM228899': 0.419, 'ANM228900': 0.023}
F-a/P-b: n 793 fields, KS 0.0366 (expected 0.03 +/- 0.003), p 0.234
     per animal KS {'ANM00190422': 0.047, 'ANM204878': 0.108, 'ANM212379': 0.097, 'ANM228899': 0.042, 'ANM228900': 0.109}; p {'ANM00190422': 0.633, 'ANM204878': 0.095, 'ANM212379': 0.691, 'ANM228899': 0.904, 'ANM228900': 0.016}
F-b: n 887 fields, KS 0.0305 (expected 0.03 +/- 0.003), p 0.375
     per animal KS {'ANM00190422': 0.057, 'ANM204878': 0.091, 'ANM212379': 0.104, 'ANM228899': 0.067, 'ANM228900': 0.096}; p {'ANM00190422': 0.348, 'ANM204878': 0.175, 'ANM212379': 0.557, 'ANM228899': 0.302, 'ANM228900': 0.032}

Result: reproduced. Under P-a the 852 field locations do not differ from uniform (KS 0.0315, within 0.03 +/- 0.003, p 0.360). Under P-b the statistic is 0.0366, outside tolerance (p 0.234), which alone would be partially reproduced; the criterion asks for one reading. One animal, ANM228900, differs from uniform on its own (p 0.023 under P-a, 0.016 under P-b). The data set's fields give KS 0.0305, p 0.375. The statistic depends on the end allowance of P-a: within tolerance from 10 to 30 cm (0.0307 to 0.0325), outside at 0 cm (0.0341) and with none (0.0442), p above 0.05 throughout (sensitivity section).

In [26]:
def track_geometry(a, step_cm=5.0):
    """Heading of the track (degrees, room frame, outbound) per linear bin, from the animal's
    room position against its linear position in RUN1. The scale model of the track is not in
    the data set; this reconstructs its centreline."""
    x = a["x_cm"]
    xy = a["xy_room"] * 2.54
    ok = np.isfinite(x) & np.all(np.isfinite(xy), axis=1)
    edges = np.arange(0, 4800 + step_cm, step_cm)
    b = np.digitize(x[ok], edges) - 1
    cx = np.full(len(edges) - 1, np.nan)
    cy = np.full(len(edges) - 1, np.nan)
    for i in range(len(edges) - 1):
        sel = b == i
        if sel.sum():
            cx[i] = np.median(xy[ok][sel, 0]); cy[i] = np.median(xy[ok][sel, 1])
    good = np.isfinite(cx)
    centres = edges[:-1] + step_cm / 2
    cx = np.interp(centres, centres[good], cx[good]); cy = np.interp(centres, centres[good], cy[good])
    # heading from the centreline 20 cm either side (a standard smoothing)
    h = 4
    dx = np.roll(cx, -h) - np.roll(cx, h); dy = np.roll(cy, -h) - np.roll(cy, h)
    dx[:h] = cx[2 * h] - cx[0]; dy[:h] = cy[2 * h] - cy[0]
    dx[-h:] = cx[-1] - cx[-1 - 2 * h]; dy[-h:] = cy[-1] - cy[-1 - 2 * h]
    heading = np.degrees(np.arctan2(dy, dx))
    return centres, heading, cx, cy

def corners(centres, heading, threshold_deg, span_cm=50.0):
    """Corner locations (cm): local maxima of the heading change over +/- span/2 that reach the
    threshold."""
    step = centres[1] - centres[0]
    h = int(span_cm / 2 / step)
    unwrapped = np.unwrap(np.radians(heading))
    change = np.abs(np.degrees(np.roll(unwrapped, -h) - np.roll(unwrapped, h)))
    change[:h] = 0; change[-h:] = 0
    out = []
    i = 0
    while i < len(change):
        if change[i] >= threshold_deg:
            j = i
            while j < len(change) and change[j] >= threshold_deg:
                j += 1
            out.append(centres[i + int(np.argmax(change[i:j]))])
            i = j
        else:
            i += 1
    return np.array(out)

def mean_speed_bins(a, step_cm=5.0):
    """The animal's mean speed in 5 cm bins of track during novel exploration (Fig. S10C)."""
    edges = np.arange(0, 4800 + step_cm, step_cm)
    sp = np.full(len(edges) - 1, np.nan)
    idx = np.concatenate([rich.epoch_samples(a, e) for e in range(4)])
    x, v = a["x_nov_cm"][idx], np.abs(a["v"][idx])
    b = np.digitize(x, edges) - 1
    for i in range(len(edges) - 1):
        sel = (b == i) & np.isfinite(v)
        if sel.sum():
            sp[i] = v[sel].mean()
    return edges[:-1] + step_cm / 2, sp

GEOM = {a["animal"]: track_geometry(a) for a in animals}
SPEED = {a["animal"]: mean_speed_bins(a) for a in animals}
for an in ANIMALS:
    c, h, _, _ = GEOM[an]
    print(an, "corners >= 45 deg:", len(corners(c, h, 45)), "; >= 90 deg:", len(corners(c, h, 90)),
          "; mean speed per 5 cm bin, range", np.nanmin(SPEED[an][1]).round(1), "to", np.nanmax(SPEED[an][1]).round(1), "cm/s")
ANM00190422 corners >= 45 deg: 33 ; >= 90 deg: 10 ; mean speed per 5 cm bin, range 2.2 to 103.0 cm/s
ANM204878 corners >= 45 deg: 37 ; >= 90 deg: 18 ; mean speed per 5 cm bin, range 1.4 to 104.7 cm/s
ANM212379 corners >= 45 deg: 37 ; >= 90 deg: 18 ; mean speed per 5 cm bin, range 1.3 to 122.1 cm/s
ANM228899 corners >= 45 deg: 37 ; >= 90 deg: 21 ; mean speed per 5 cm bin, range 2.7 to 109.4 cm/s
ANM228900 corners >= 45 deg: 37 ; >= 90 deg: 21 ; mean speed per 5 cm bin, range 1.1 to 109.8 cm/s
In [27]:
# Reconstructed centrelines with the corners found (verifier round 1 asked for this plot). The
# track layout of Fig. 1 is not in the text read, so the plot shows the reconstruction alone.
fig, ax = plt.subplots(1, 5, figsize=(16, 3.2))
for j, an in enumerate(ANIMALS):
    c, h, cx, cy = GEOM[an]
    ax[j].plot(cx / 100, cy / 100, "0.5", lw=0.8)
    for thr, mk in ((45, "o"), (90, "x")):
        cs = corners(c, h, thr)
        ax[j].plot(np.interp(cs, c, cx) / 100, np.interp(cs, c, cy) / 100, mk, ms=4, mfc="none",
                   label=f">= {thr} deg ({len(cs)})")
    ax[j].set_title(an, fontsize=8); ax[j].set_aspect("equal"); ax[j].legend(fontsize=6)
    ax[j].set_xlabel("room x (m)")
plt.show()
for an in ANIMALS:
    c, h, cx, cy = GEOM[an]
    cs = corners(c, h, 45)
    gaps = np.diff(np.sort(cs)) / 100
    print(f"{an}: room x {cx.min() / 100:.1f} to {cx.max() / 100:.1f} m, y {cy.min() / 100:.1f} to {cy.max() / 100:.1f} m; "
          f"spacing of 45-degree corners along the track {np.median(gaps):.2f} m median, {gaps.min():.2f} to {gaps.max():.2f} m; "
          f"distance from a uniform point to the nearest corner: 95th percentile "
          f"{np.percentile(np.min(np.abs(np.linspace(0, 4800, 4801)[:, None] - cs[None, :]), axis=1), 95) / 100:.2f} m")
No description has been provided for this image
ANM00190422: room x 0.7 to 13.9 m, y 0.5 to 9.8 m; spacing of 45-degree corners along the track 1.23 m median, 0.45 to 5.50 m; distance from a uniform point to the nearest corner: 95th percentile 1.97 m
ANM204878: room x 0.8 to 14.5 m, y 0.0 to 5.3 m; spacing of 45-degree corners along the track 1.55 m median, 0.45 to 3.95 m; distance from a uniform point to the nearest corner: 95th percentile 1.21 m
ANM212379: room x 0.8 to 14.5 m, y 0.0 to 5.3 m; spacing of 45-degree corners along the track 1.52 m median, 0.45 to 4.00 m; distance from a uniform point to the nearest corner: 95th percentile 1.22 m
ANM228899: room x 0.8 to 14.6 m, y 0.5 to 5.3 m; spacing of 45-degree corners along the track 1.52 m median, 0.45 to 3.95 m; distance from a uniform point to the nearest corner: 95th percentile 1.21 m
ANM228900: room x 0.8 to 14.6 m, y 0.5 to 5.3 m; spacing of 45-degree corners along the track 1.55 m median, 0.45 to 3.90 m; distance from a uniform point to the nearest corner: 95th percentile 1.21 m

figs10-no-track-or-speed-influence¶

Field density is not influenced by local track features or running speed; the number of fields against the angle of the track in the room, the distance to the nearest corner and the animal's mean speed shows no consistent trend relative to a shuffle of field locations.

The track's scale model is not in the data set. Its centreline is reconstructed from the animal's room position in 5 cm bins of linear position, the heading taken over 20 cm either side, and corners are the local maxima of the heading change over 50 cm that reach 45 degrees (Y-a) or 90 degrees (Y-b). The shuffle places each animal's fields uniformly on its own track, 2000 times, with a generator of its own for each field set. T-b is defined for panels B and C only, so panel A is judged on T-a alone.

In [28]:
rng_s10 = np.random.default_rng(10)

def s10_values(f, which, ythr=45):
    vals, w = [], []
    for an in ANIMALS:
        g = f[f.animal == an]
        loc_cm = np.clip(g.loc_m.values, 0, 48) * 100
        c, h, _, _ = GEOM[an]
        if which == "A":
            hd = np.interp(loc_cm, c, h)
            # direction of travel of the field: outbound keeps the track heading, inbound reverses it;
            # in F-a direction 1 is outbound, 2 inbound, 3 both (half a count each)
            dirs = g.direction.values
            out_dir = 1 if "F-a" in str(f.attrs.get("name", "F-a")) else 2
            for hv, dv in zip(hd, dirs):
                if dv == 3:
                    vals += [hv % 360, (hv + 180) % 360]; w += [0.5, 0.5]
                elif dv == out_dir:
                    vals.append(hv % 360); w.append(1)
                else:
                    vals.append((hv + 180) % 360); w.append(1)
        elif which == "B":
            cs = corners(c, h, ythr)
            d = np.min(np.abs(loc_cm[:, None] - cs[None, :]), axis=1) / 100 if len(cs) else np.full(len(loc_cm), np.nan)
            vals += list(d); w += [1] * len(d)
        else:
            sc, sp = SPEED[an]
            vals += list(np.interp(loc_cm, sc, sp)); w += [1] * len(loc_cm)
    return np.array(vals), np.array(w)

def s10_hist(vals, w, which):
    if which == "A":
        edges = np.arange(0, 361, 30)
    elif which == "B":
        edges = np.arange(0, 11, 1.0)
    else:
        edges = np.arange(0, 125, 5.0)
    hist, _ = np.histogram(vals, edges, weights=w)
    return hist, edges

def s10_shuffle(f, which, ythr, n=2000, rng=None):
    """Same number of fields per animal placed uniformly on the track; directions kept."""
    rng = rng_s10 if rng is None else rng
    sims = []
    for _ in range(n):
        g = f.copy()
        g["loc_m"] = rng.uniform(0, 48, len(g))
        g.attrs = f.attrs
        v, w = s10_values(g, which, ythr)
        sims.append(s10_hist(v, w, which)[0])
    return np.array(sims)

S10 = []
for ki, k in enumerate(MAIN + ["F-b"]):
    f = FIELDS[k].copy()
    f.attrs["name"] = k
    rng_k = np.random.default_rng([10, ki])  # each field set its own shuffles
    for which, ythr in [("A", None), ("B", 45), ("B", 90), ("C", None)]:
        v, w = s10_values(f, which, ythr)
        obs, edges = s10_hist(v, w, which)
        sims = s10_shuffle(f, which, ythr, n=2000, rng=rng_k)
        lo, hi = np.percentile(sims, [2.5, 97.5], axis=0)
        out = int(np.sum((obs < lo) | (obs > hi)))
        nb = len(obs)
        p_ta = stats.binomtest(out, nb, 0.05, alternative="greater").pvalue
        if which in ("B", "C"):
            keep = sims.mean(axis=0) > 0
            rho, p_tb = stats.spearmanr((edges[:-1] + edges[1:])[keep] / 2, (obs - sims.mean(axis=0))[keep])
        else:
            rho, p_tb = np.nan, np.nan
        S10.append(dict(reading=k, panel=which + ("" if ythr is None else f" Y-{'a' if ythr == 45 else 'b'}"),
                        bins=nb, outside_95=out, p_Ta=p_ta, rho_Tb=rho, p_Tb=p_tb,
                        fields_counted=float(np.sum(w[np.isfinite(v)])),
                        beyond_axis=float(np.sum(w[np.isfinite(v)][(v[np.isfinite(v)] < edges[0]) | (v[np.isfinite(v)] >= edges[-1])]))))
s10 = pd.DataFrame(S10)
s10["passes_Ta"] = s10.p_Ta >= 0.05
# T-b is defined for panels B and C only; for A it is not applicable, not a pass (verifier round 1).
s10["passes_Tb"] = np.where(s10.p_Tb.isna(), "n/a", (s10.p_Tb >= 0.05).astype(str))
# Panel B's power: the number of 1 m distance bins that the shuffle fills at all.
s10["bins_with_null_mass"] = [int(np.sum(np.mean(s10_shuffle(FIELDS[r_], "B", 45 if "Y-a" in pn else 90, n=50), axis=0) > 0)) if pn.startswith("B") else np.nan
                              for r_, pn in zip(s10.reading, s10.panel)]
print(s10.round(3).to_string(index=False))
for k in MAIN + ["F-b"]:
    g = s10[s10.reading == k]
    verdict = []
    for panel in ("A", "B", "C"):
        h = g[g.panel.str.startswith(panel)]
        res = [str(v) for v in h.passes_Ta] + [v for v in h.passes_Tb if v != "n/a"]
        verdict.append(f"{panel}: passes {sum(v == 'True' for v in res)} of {len(res)} readings")
    print(k, "; ".join(verdict))
# Seed check of panel A, the panel that decides: bins outside the shuffle's 95% interval with five
# further sets of 2000 shuffles per field set (the observed histogram is fixed; only the null varies).
for ki, k in enumerate(MAIN + ["F-b"]):
    f = FIELDS[k].copy()
    f.attrs["name"] = k
    v, w = s10_values(f, "A", None)
    obs, _ = s10_hist(v, w, "A")
    outs = []
    for seed in range(5):
        sims = s10_shuffle(f, "A", None, n=2000, rng=np.random.default_rng([1010, ki, seed]))
        lo, hi = np.percentile(sims, [2.5, 97.5], axis=0)
        outs.append(int(np.sum((obs < lo) | (obs > hi))))
    print(f"{k} panel A, bins outside over five further null sets: {outs} (3 or more gives binomial p 0.020)")
    if k == MAIN[0]:
        exp_ = sims.mean(axis=0)
        print("     observed counts per 30 degree bin:", np.round(obs, 1).tolist())
        print("     shuffle mean:                     ", np.round(exp_, 1).tolist())

# Bin variants (verifier round 2, point b). Fig. S10 itself (supplement page 24) shows panel A in 12
# bins of 30 degrees from -pi, the partition used above; panel B in bins of 15 cm; panel C in bins of
# about 12 cm/s (read from the figure's axes). Panel A is also shown with other widths and offsets,
# and panels B and C with the figure's widths. The null is one set of 2000 shuffles per field set.
def s10_variants(f, which, ythr, specs, rng, n=2000):
    v, w = s10_values(f, which, ythr)
    sims = []
    for _ in range(n):
        g = f.copy(); g["loc_m"] = rng.uniform(0, 48, len(g)); g.attrs = f.attrs
        sims.append(s10_values(g, which, ythr))
    out = []
    for name, edges, wrap in specs:
        fold = (lambda x: (x - edges[0]) % 360 + edges[0]) if wrap else (lambda x: x)
        obs = np.histogram(fold(v), edges, weights=w)[0]
        S = np.array([np.histogram(fold(a_), edges, weights=b_)[0] for a_, b_ in sims])
        lo, hi = np.percentile(S, [2.5, 97.5], axis=0)
        k_out = int(np.sum((obs < lo) | (obs > hi)))
        out.append(dict(binning=name, bins=len(obs), outside_95=k_out,
                        p_Ta=stats.binomtest(k_out, len(obs), 0.05, alternative="greater").pvalue))
    return out, v, w, sims

specs_A = [(f"{wd} deg from {off} deg", np.arange(off, 360 + off + 0.1, wd), True)
           for wd in (20, 30, 45, 60) for off in range(0, wd, 10 if wd < 45 else 15)]
S10V = []
for ki, k in enumerate(MAIN + ["F-b"]):
    f = FIELDS[k].copy()
    f.attrs["name"] = k
    rows_, v, w, sims = s10_variants(f, "A", None, specs_A, np.random.default_rng([1011, ki]))
    S10V += [dict(reading=k, panel="A", **r_) for r_ in rows_]
    if k == MAIN[0]:
        e180 = np.arange(-180, 181, 30)
        fold = lambda x: (x + 180) % 360 - 180
        print("F-a/P-a panel A in the figure's frame (bins of 30 degrees from -180):")
        print("     observed:     ", np.round(np.histogram(fold(v), e180, weights=w)[0], 1).tolist())
        print("     shuffle mean: ", np.round(np.mean([np.histogram(fold(a_), e180, weights=b_)[0] for a_, b_ in sims], axis=0), 1).tolist())
    for which, ythr, specs in [("B", 45, [("15 cm to 1.8 m", np.arange(0, 1.81, 0.15), False)]),
                               ("B", 90, [("15 cm to 1.8 m", np.arange(0, 1.81, 0.15), False)]),
                               ("C", None, [("12 cm/s", np.arange(0, 133, 12.0), False)])]:
        rows_, *_ = s10_variants(f, which, ythr, specs, np.random.default_rng([1012, ki, ythr or 0]))
        S10V += [dict(reading=k, panel=which + ("" if ythr is None else f" Y-{'a' if ythr == 45 else 'b'}"), **r_) for r_ in rows_]
s10v = pd.DataFrame(S10V)
s10v["passes_Ta"] = s10v.p_Ta >= 0.05
print(s10v.round(3).to_string(index=False))
for k in MAIN + ["F-b"]:
    g = s10v[(s10v.reading == k) & (s10v.panel == "A")]
    print(f"{k} panel A: passes T-a under {int(g.passes_Ta.sum())} of {len(g)} binnings")
reading panel  bins  outside_95  p_Ta  rho_Tb  p_Tb  fields_counted  beyond_axis  passes_Ta passes_Tb  bins_with_null_mass
F-a/P-a     A    12           3 0.020     NaN   NaN           852.0          0.0      False       n/a                  NaN
F-a/P-a B Y-a    10           2 0.086  -0.500 0.667           852.0          0.0       True      True                  3.0
F-a/P-a B Y-b    10           1 0.401   0.286 0.493           852.0          0.0       True      True                  8.0
F-a/P-a     C    24           2 0.339  -0.115 0.593           851.0          0.0       True      True                  NaN
F-a/P-b     A    12           3 0.020     NaN   NaN           793.0          0.0      False       n/a                  NaN
F-a/P-b B Y-a    10           1 0.401  -0.500 0.667           793.0          0.0       True      True                  3.0
F-a/P-b B Y-b    10           1 0.401   0.286 0.493           793.0          0.0       True      True                  8.0
F-a/P-b     C    24           2 0.339   0.083 0.701           792.0          0.0       True      True                  NaN
    F-b     A    12           2 0.118     NaN   NaN           887.0          0.0       True       n/a                  NaN
    F-b B Y-a    10           2 0.086  -0.500 0.667           887.0          0.0       True      True                  3.0
    F-b B Y-b    10           1 0.401   0.310 0.456           887.0          0.0       True      True                  8.0
    F-b     C    24           5 0.006  -0.221 0.300           885.0          0.0      False      True                  NaN
F-a/P-a A: passes 0 of 1 readings; B: passes 4 of 4 readings; C: passes 2 of 2 readings
F-a/P-b A: passes 0 of 1 readings; B: passes 4 of 4 readings; C: passes 2 of 2 readings
F-b A: passes 1 of 1 readings; B: passes 4 of 4 readings; C: passes 1 of 2 readings
F-a/P-a panel A, bins outside over five further null sets: [3, 4, 3, 3, 3] (3 or more gives binomial p 0.020)
     observed counts per 30 degree bin: [68.0, 83.5, 68.5, 43.5, 109.0, 66.5, 53.0, 64.5, 54.5, 62.5, 109.0, 69.5]
     shuffle mean:                      [63.4, 80.0, 55.9, 46.7, 93.5, 87.1, 62.9, 79.6, 56.2, 46.6, 93.1, 87.0]
F-a/P-b panel A, bins outside over five further null sets: [3, 3, 3, 3, 3] (3 or more gives binomial p 0.020)
F-b panel A, bins outside over five further null sets: [2, 2, 2, 2, 1] (3 or more gives binomial p 0.020)
F-a/P-a panel A in the figure's frame (bins of 30 degrees from -180):
     observed:      [53.0, 64.5, 54.5, 62.5, 109.0, 69.5, 68.0, 83.5, 68.5, 43.5, 109.0, 66.5]
     shuffle mean:  [63.2, 79.4, 56.0, 46.4, 93.1, 87.2, 63.6, 80.3, 55.8, 46.5, 93.6, 87.0]
reading panel            binning  bins  outside_95  p_Ta  passes_Ta
F-a/P-a     A  20 deg from 0 deg    18           3 0.058       True
F-a/P-a     A 20 deg from 10 deg    18           3 0.058       True
F-a/P-a     A  30 deg from 0 deg    12           3 0.020      False
F-a/P-a     A 30 deg from 10 deg    12           2 0.118       True
F-a/P-a     A 30 deg from 20 deg    12           2 0.118       True
F-a/P-a     A  45 deg from 0 deg     8           1 0.337       True
F-a/P-a     A 45 deg from 15 deg     8           3 0.006      False
F-a/P-a     A 45 deg from 30 deg     8           1 0.337       True
F-a/P-a     A  60 deg from 0 deg     6           1 0.265       True
F-a/P-a     A 60 deg from 15 deg     6           1 0.265       True
F-a/P-a     A 60 deg from 30 deg     6           2 0.033      False
F-a/P-a     A 60 deg from 45 deg     6           2 0.033      False
F-a/P-a B Y-a     15 cm to 1.8 m    12           1 0.460       True
F-a/P-a B Y-b     15 cm to 1.8 m    12           1 0.460       True
F-a/P-a     C            12 cm/s    11           0 1.000       True
F-a/P-b     A  20 deg from 0 deg    18           3 0.058       True
F-a/P-b     A 20 deg from 10 deg    18           4 0.011      False
F-a/P-b     A  30 deg from 0 deg    12           3 0.020      False
F-a/P-b     A 30 deg from 10 deg    12           2 0.118       True
F-a/P-b     A 30 deg from 20 deg    12           2 0.118       True
F-a/P-b     A  45 deg from 0 deg     8           2 0.057       True
F-a/P-b     A 45 deg from 15 deg     8           3 0.006      False
F-a/P-b     A 45 deg from 30 deg     8           2 0.057       True
F-a/P-b     A  60 deg from 0 deg     6           2 0.033      False
F-a/P-b     A 60 deg from 15 deg     6           2 0.033      False
F-a/P-b     A 60 deg from 30 deg     6           2 0.033      False
F-a/P-b     A 60 deg from 45 deg     6           2 0.033      False
F-a/P-b B Y-a     15 cm to 1.8 m    12           0 1.000       True
F-a/P-b B Y-b     15 cm to 1.8 m    12           1 0.460       True
F-a/P-b     C            12 cm/s    11           1 0.431       True
    F-b     A  20 deg from 0 deg    18           5 0.002      False
    F-b     A 20 deg from 10 deg    18           3 0.058       True
    F-b     A  30 deg from 0 deg    12           2 0.118       True
    F-b     A 30 deg from 10 deg    12           2 0.118       True
    F-b     A 30 deg from 20 deg    12           3 0.020      False
    F-b     A  45 deg from 0 deg     8           2 0.057       True
    F-b     A 45 deg from 15 deg     8           2 0.057       True
    F-b     A 45 deg from 30 deg     8           2 0.057       True
    F-b     A  60 deg from 0 deg     6           1 0.265       True
    F-b     A 60 deg from 15 deg     6           2 0.033      False
    F-b     A 60 deg from 30 deg     6           2 0.033      False
    F-b     A 60 deg from 45 deg     6           3 0.002      False
    F-b B Y-a     15 cm to 1.8 m    12           3 0.020      False
    F-b B Y-b     15 cm to 1.8 m    12           1 0.460       True
    F-b     C            12 cm/s    11           2 0.102       True
F-a/P-a panel A: passes T-a under 8 of 12 binnings
F-a/P-b panel A: passes T-a under 5 of 12 binnings
F-b panel A: passes T-a under 7 of 12 binnings

Result: not reproduced. Under both pass readings the angle panel (A) has 3 of 12 bins outside the shuffle's 95% interval, more than chance allows (binomial p 0.020), and A has no other reading (T-b is defined for B and C only), so A fails under every reading it has. Five further sets of shuffles give 3 or 4 bins outside under P-a and 3 under P-b. Under P-a the observed counts lie below the shuffle mean in the bins from 150 to 240 degrees and from 330 to 360 degrees, and above it from 120 to 150 and from 270 to 330 degrees.

The partition is the paper's: Fig. S10A (supplement page 24) shows 12 bins of 30 degrees starting at -pi, the same bins. In that frame the shuffle means here (63.2, 79.4, 56.0, 46.4, 93.1, 87.2, 63.6, 80.3, 55.8, 46.5, 93.6, 87.0) follow the paper's shuffle as read from the figure (about 59, 77, 65, 52, 101, 88, 59, 77, 64, 52, 101, 89), which supports the reconstructed track headings. The failure is fragile to the binning: over 12 widths and offsets of the angle bins, panel A passes T-a under 8 (P-a) and 5 (P-b); it fails under the figure's own bins.

Panels B (both corner readings) and C pass both tests. With 1 m bins panel B has little power under Y-a: the reconstructed track has a corner of 45 degrees or more every 1.2 to 1.55 m (median), so the shuffle fills only 3 of the ten 1 m distance bins under Y-a, against 8 under Y-b. With the widths Fig. S10 shows, 15 cm distance bins (to 1.8 m) and velocity bins of about 12 cm/s, B and C also pass T-a under both pass readings (0 or 1 of 12 bins and 0 or 1 of 11 bins outside). The data set's fields pass A (2 of 12), fail panel C with 5 cm/s bins (5 of 24, p 0.006) but not with 12 cm/s bins (2 of 11, p 0.102), and fail B under Y-a with 15 cm bins (4 of 12, p 0.002).

Read from the figure, the paper's own Fig. S10 has bins outside its 95% intervals in every panel: in A one bin (pi/2 to 2 pi/3) clearly above and two at an edge, in B two (15 to 30 and 60 to 75 cm), in C two (about 12 to 24 and 37 to 49 cm/s). T-a might therefore fail the paper's own data, and the claims file says Fig. S10 gives no bin widths; both are asked of a reader (questions/rich-2014.yaml).

In [29]:
def counts_in(f, lo_m, hi_m):
    """Per cell (all 253), fields located in [lo, hi) metres, per animal bounds if arrays."""
    out = np.zeros(len(cells), int)
    key = {k: i for i, k in enumerate(zip(cells.ai, cells.cell))}
    for _, r in f.iterrows():
        lo = lo_m[r.ai] if np.ndim(lo_m) else lo_m
        hi = hi_m[r.ai] if np.ndim(hi_m) else hi_m
        if lo <= r.loc_m < hi:
            out[key[(r.ai, r.cell)]] += 1
    return out

def rank_rows(x):
    return stats.rankdata(x, axis=-1)

def spearman_rows(a, b):
    ra, rb = rank_rows(a), rank_rows(b)
    ra = ra - ra.mean(axis=-1, keepdims=True); rb = rb - rb.mean(axis=-1, keepdims=True)
    den = np.sqrt((ra ** 2).sum(-1) * (rb ** 2).sum(-1))
    return np.where(den > 0, (ra * rb).sum(-1) / np.where(den > 0, den, 1), np.nan)

# section boundaries of each animal, metres (sectExt)
BOUND = np.array([[a["sectExt_cm"][e, 1] / 100 for e in range(4)] for a in animals])
print("section ends per animal (m):", np.round(BOUND, 2).tolist())
section ends per animal (m): [[3.49, 9.69, 21.15, 48.07], [3.49, 9.64, 21.07, 48.09], [3.49, 9.61, 21.22, 47.97], [3.49, 9.61, 21.15, 48.04], [3.47, 9.61, 21.17, 47.99]]

figs11-propensity-stationary¶

Field propensities are stationary along the track; the correlation of the number of fields per cell in the first three sections with that in the last section (Spearman 0.67) does not differ from that expected under the fitted gamma-Poisson model (p = 0.95).

Sections 1 to 3 are the fields of epochs 1 to 3 and section 4 those of epoch 4 (novel fields only).

In [30]:
rng_s11 = np.random.default_rng(11)
# Each cell's simulated sections have its animal's own lengths, 0 to the end of section 3 and the
# rest of the track (sectExt; verifier round 1 noted 22 and 26 m against the data's 21.2 and 26.8 m).
len13 = BOUND[cells.ai.values, 2]
len4 = BOUND[cells.ai.values, 3] - BOUND[cells.ai.values, 2]
print(f"section 1-3 length {len13.min():.2f} to {len13.max():.2f} m, section 4 {len4.min():.2f} to {len4.max():.2f} m")
for k in MAIN + ["F-b"]:
    f = FIELDS[k]
    first3 = np.array([np.sum((f.ai == ai) & (f.cell == c) & (f.epoch <= 2)) for ai, c in zip(cells.ai, cells.cell)])
    last = np.array([np.sum((f.ai == ai) & (f.cell == c) & (f.epoch == 3)) for ai, c in zip(cells.ai, cells.cell)])
    rho = stats.spearmanr(first3, last)[0]
    r, p = NB[k]
    lam = rng_s11.gamma(r, (1 - p) / p / 48, (2000, len(cells)))  # fields per metre
    sims = spearman_rows(rng_s11.poisson(lam * len13), rng_s11.poisson(lam * len4))
    lower = np.mean(sims <= rho)
    p_qa = min(1.0, 2 * min(lower, np.mean(sims >= rho)))
    print(f"{k}: rho {rho:.3f} (expected 0.67 +/- 0.067); simulated median {np.nanmedian(sims):.3f}, 95% "
          f"{np.nanpercentile(sims, 2.5):.3f} to {np.nanpercentile(sims, 97.5):.3f}; p Q-a {p_qa:.3f}, Q-b {lower:.3f}")
section 1-3 length 21.07 to 21.22 m, section 4 26.75 to 27.03 m
F-a/P-a: rho 0.675 (expected 0.67 +/- 0.067); simulated median 0.662, 95% 0.580 to 0.739; p Q-a 0.746, Q-b 0.627
F-a/P-b: rho 0.634 (expected 0.67 +/- 0.067); simulated median 0.649, 95% 0.560 to 0.724; p Q-a 0.732, Q-b 0.366
F-b: rho 0.670 (expected 0.67 +/- 0.067); simulated median 0.669, 95% 0.582 to 0.743; p Q-a 0.973, Q-b 0.513

Result: reproduced. Spearman rho is 0.675 (P-a) and 0.634 (P-b), within 0.67 +/- 0.067, and inside the simulated 95% range (0.580 to 0.739 under P-a); p is 0.746 and 0.627 (P-a, Q-a and Q-b) and 0.732 and 0.366 (P-b). The simulation now uses each animal's own section lengths (21.07 to 21.22 m and 26.75 to 27.03 m).

figs11-no-boundary-remapping¶

There is no change in field propensity at section boundaries; the correlation of the number of fields per cell across a section boundary does not differ from that within a section (sections 3 and 4, 0.50 against 0.38, p = 0.07; sections 2 and 3, 0.32 against 0.34, p = 0.84; sections 1 and 2, 0.28 against 0.25, p = 0.78).

Section boundaries are each animal's own (sectExt).

In [31]:
rng_s11b = np.random.default_rng(111)

def pieces(boundary, L):
    """A, B, C bounds (m) per animal for the boundary after section `boundary` (1, 2 or 3)."""
    lo_sec = np.where(boundary == 1, 0.0, BOUND[:, boundary - 2]) if boundary > 1 else np.zeros(5)
    b = BOUND[:, boundary - 1]
    nxt = BOUND[:, boundary]
    earlier = b - lo_sec
    later = nxt - b
    if L == "L-a":
        w = earlier
        A = (lo_sec, b)
        B = (b, b + w)
        C = (b + w, np.minimum(b + 2 * w, nxt))
    else:
        w = np.minimum(earlier, later / 2)
        A = (b - w, b)
        B = (b, b + w)
        C = (b + w, b + 2 * w)
    return A, B, C

S11B = []
for k in MAIN + ["F-b"]:
    f = FIELDS[k]
    for boundary, label_, exp_ in [(3, "sections 3 and 4", (0.50, 0.38)), (2, "sections 2 and 3", (0.32, 0.34)), (1, "sections 1 and 2", (0.28, 0.25))]:
        for L in ("L-a", "L-b"):
            A, B, C = pieces(boundary, L)
            ca, cb, cc = counts_in(f, *A), counts_in(f, *B), counts_in(f, *C)
            across, within = stats.spearmanr(ca, cb)[0], stats.spearmanr(cb, cc)[0]
            diff = across - within
            for H in ("H-a", "H-b"):
                stack = np.stack([ca, cb, cc], axis=1)
                if H == "H-a":
                    swap = rng_s11b.random((8000, len(ca))) < 0.5
                    A2 = np.where(swap, cc, ca); C2 = np.where(swap, ca, cc); B2 = np.broadcast_to(cb, A2.shape)
                else:
                    perm = np.argsort(rng_s11b.random((8000, len(ca), 3)), axis=2)
                    sh = np.take_along_axis(np.broadcast_to(stack, perm.shape), perm, axis=2)
                    A2, B2, C2 = sh[..., 0], sh[..., 1], sh[..., 2]
                null = spearman_rows(A2, B2) - spearman_rows(B2, C2)
                pv = float(np.mean(np.abs(null) >= abs(diff)))
                S11B.append(dict(reading=k, boundary=label_, L=L, H=H, piece_m=round(float(np.mean(B[1] - B[0])), 2),
                                 rho_across=across, exp_across=exp_[0], rho_within=within, exp_within=exp_[1], p=pv))
s11b = pd.DataFrame(S11B)
print(s11b.round(3).to_string(index=False))
reading         boundary   L   H  piece_m  rho_across  exp_across  rho_within  exp_within     p
F-a/P-a sections 3 and 4 L-a H-a    11.52       0.521        0.50       0.395        0.38 0.029
F-a/P-a sections 3 and 4 L-a H-b    11.52       0.521        0.50       0.395        0.38 0.044
F-a/P-a sections 3 and 4 L-b H-a    11.52       0.521        0.50       0.395        0.38 0.026
F-a/P-a sections 3 and 4 L-b H-b    11.52       0.521        0.50       0.395        0.38 0.045
F-a/P-a sections 2 and 3 L-a H-a     6.15       0.322        0.32       0.372        0.34 0.547
F-a/P-a sections 2 and 3 L-a H-b     6.15       0.322        0.32       0.372        0.34 0.563
F-a/P-a sections 2 and 3 L-b H-a     5.76       0.305        0.32       0.346        0.34 0.630
F-a/P-a sections 2 and 3 L-b H-b     5.76       0.305        0.32       0.346        0.34 0.628
F-a/P-a sections 1 and 2 L-a H-a     3.49       0.300        0.28       0.307        0.25 0.940
F-a/P-a sections 1 and 2 L-a H-b     3.49       0.300        0.28       0.307        0.25 0.940
F-a/P-a sections 1 and 2 L-b H-a     3.07       0.211        0.28       0.300        0.25 0.298
F-a/P-a sections 1 and 2 L-b H-b     3.07       0.211        0.28       0.300        0.25 0.339
F-a/P-b sections 3 and 4 L-a H-a    11.52       0.463        0.50       0.418        0.38 0.435
F-a/P-b sections 3 and 4 L-a H-b    11.52       0.463        0.50       0.418        0.38 0.474
F-a/P-b sections 3 and 4 L-b H-a    11.52       0.463        0.50       0.418        0.38 0.427
F-a/P-b sections 3 and 4 L-b H-b    11.52       0.463        0.50       0.418        0.38 0.483
F-a/P-b sections 2 and 3 L-a H-a     6.15       0.348        0.32       0.333        0.34 0.879
F-a/P-b sections 2 and 3 L-a H-b     6.15       0.348        0.32       0.333        0.34 0.865
F-a/P-b sections 2 and 3 L-b H-a     5.76       0.340        0.32       0.318        0.34 0.809
F-a/P-b sections 2 and 3 L-b H-b     5.76       0.340        0.32       0.318        0.34 0.805
F-a/P-b sections 1 and 2 L-a H-a     3.49       0.316        0.28       0.331        0.25 0.866
F-a/P-b sections 1 and 2 L-a H-b     3.49       0.316        0.28       0.331        0.25 0.858
F-a/P-b sections 1 and 2 L-b H-a     3.07       0.261        0.28       0.327        0.25 0.455
F-a/P-b sections 1 and 2 L-b H-b     3.07       0.261        0.28       0.327        0.25 0.470
    F-b sections 3 and 4 L-a H-a    11.52       0.499        0.50       0.380        0.38 0.039
    F-b sections 3 and 4 L-a H-b    11.52       0.499        0.50       0.380        0.38 0.066
    F-b sections 3 and 4 L-b H-a    11.52       0.499        0.50       0.380        0.38 0.040
    F-b sections 3 and 4 L-b H-b    11.52       0.499        0.50       0.380        0.38 0.060
    F-b sections 2 and 3 L-a H-a     6.15       0.338        0.32       0.331        0.34 0.931
    F-b sections 2 and 3 L-a H-b     6.15       0.338        0.32       0.331        0.34 0.938
    F-b sections 2 and 3 L-b H-a     5.76       0.318        0.32       0.337        0.34 0.826
    F-b sections 2 and 3 L-b H-b     5.76       0.318        0.32       0.337        0.34 0.826
    F-b sections 1 and 2 L-a H-a     3.49       0.358        0.28       0.253        0.25 0.223
    F-b sections 1 and 2 L-a H-b     3.49       0.358        0.28       0.253        0.25 0.253
    F-b sections 1 and 2 L-b H-a     3.07       0.279        0.28       0.251        0.25 0.756
    F-b sections 1 and 2 L-b H-b     3.07       0.279        0.28       0.251        0.25 0.762

Result: not reproduced, resting on the assumption P-a. Under P-a the boundary between sections 3 and 4 gives rho across 0.521 against rho within 0.395, and p of 0.026 to 0.045 under every reading of L and H, below 0.05. The other boundaries give p 0.298 to 0.940. Under P-b no boundary has p < 0.05 (smallest 0.427), which the criterion counts as reproduced. At that boundary the two rho values match the paper's 0.50 and 0.38; the data set's fields give p 0.039 and 0.040 (H-a) and 0.066 and 0.060 (H-b) there. Under every end allowance of P-a from none to 30 cm the boundary between sections 3 and 4 keeps p below 0.05 (0.0125 to 0.0328 under L-a and H-a, sensitivity section), so the result does not rest on the allowance, but it rests on P-a, with p near 0.05, and the data set's fields split by the reading of H.

Sensitivity to the end allowance of P-a¶

The 20 cm end allowance of P-a (EDGE_CM, see the data check) was chosen after round 1. The verifier asked for it to be varied (round 2, point a), as fig3d-uniform-density, figs7a-mean-fields-per-animal, fig3c-lomax-recruitment and the case for P-a rest on it. Here P-a is recomputed with no allowance (the first version, False), and with 0, 10, 15, 20 and 30 cm, and the quantities those claims are judged on are recomputed. The Monte Carlo p-values use fewer draws than in the claims' own sections (1000 for the Lomax tests, 5000 for the Anderson-Darling tests, 4000 for the boundary test with L-a and H-a only).

In [32]:
# Sensitivity to the end allowance of P-a (verifier round 2, point a). EDGE_CM is 20 cm in the
# main analysis; here P-a is recomputed with no allowance (the first version), 0, 10, 15 and 30 cm.
# 0 cm still lets a pass that reaches the last position visited count; above 20 cm no field changes.
rng_edge = np.random.default_rng(2020)
EDGE_ROWS = []
for e_cm in (False, 0, 10, 15, 20, 30):
    f = FIELDS["F-a/P-a"] if e_cm == 20 else rich.track_fields(animals, "P-a", edge_cm=e_cm)
    c = rich.counts(f, cells)
    m = rich.match_dataset_fields(animals, f, "P-a")
    per = pd.Series(c).groupby(cells.animal.values).mean()
    s7a = int(sum(abs(per[an] - v) <= 0.1 * v + 1e-9 for an, v in expected.items()))
    ks3d = stats.kstest(np.clip(f.loc_m.values, 0, 48), "uniform", args=(0, 48))
    r, p, _ = rich.nbinfit(c)
    first = np.clip(rich.first_field(f, cells), 0, 48)
    d, p_ka = lomax_test(first, r, p, 48, rng_edge, n_mc=1000)
    _, p_kb = lomax_test(first, r, p, 48, rng_edge, n_mc=1000, refit=True)
    cf = cell_fields(f)
    ps = [rich.ad_uniform_p(np.concatenate([v for v in cf.values() if len(v) == n] or [np.array([])]), 0, 48, rng_edge, n_mc=5000)[1]
          for n in range(1, 6)]
    A, B, C = pieces(3, "L-a")
    ca, cb, cc = counts_in(f, *A), counts_in(f, *B), counts_in(f, *C)
    diff = stats.spearmanr(ca, cb)[0] - stats.spearmanr(cb, cc)[0]
    swap = rng_edge.random((4000, len(ca))) < 0.5
    null = spearman_rows(np.where(swap, cc, ca), np.broadcast_to(cb, swap.shape)) - spearman_rows(np.broadcast_to(cb, swap.shape), np.where(swap, ca, cc))
    EDGE_ROWS.append(dict(edge_cm=str(e_cm), fields=len(f), at_end=int(f.touches_end.sum()), dataset_overlapped=int(m.matched.sum()),
                          s7a_within=s7a, ks_3d=ks3d.statistic, p_3d=ks3d.pvalue, r=r, p=p, ks_3c=d, p_3c_Ka=p_ka, p_3c_Kb=p_kb,
                          s6_min_adj_p=float(np.min(rich.bh(ps))), s11_34_p_LaHa=float(np.mean(np.abs(null) >= abs(diff))),
                          d90_m=rich.lomax_inverse(0.9, r, p)))
print(pd.DataFrame(EDGE_ROWS).round(4).to_string(index=False))
print("tolerances: fig3d KS 0.027 to 0.033; fig3c KS 0.045 to 0.055; figs7a 5 of 5 within 10%; "
      "figs6 adjusted p >= 0.05; figs11 boundary p >= 0.05; 90% recruitment 450 to 550 m")
edge_cm  fields  at_end  dataset_overlapped  s7a_within  ks_3d   p_3d      r      p  ks_3c  p_3c_Ka  p_3c_Kb  s6_min_adj_p  s11_34_p_LaHa    d90_m
  False     791       0                 784           1 0.0442 0.0880 0.5592 0.1517 0.0396   0.7233   0.4895        0.4067         0.0290 518.7574
      0     815      27                 807           5 0.0341 0.2944 0.5552 0.1470 0.0402   0.7123   0.4545        0.1515         0.0125 515.1554
     10     848      68                 837           5 0.0307 0.3930 0.5566 0.1424 0.0532   0.3646   0.1439        0.1860         0.0170 491.0452
     15     853      73                 843           5 0.0325 0.3215 0.5625 0.1430 0.0598   0.2627   0.0669        0.2005         0.0275 472.1760
     20     852      72                 842           5 0.0315 0.3596 0.5626 0.1432 0.0600   0.2767   0.0629        0.3752         0.0300 472.2903
     30     852      72                 842           5 0.0315 0.3596 0.5626 0.1432 0.0600   0.2627   0.0679        0.3806         0.0328 472.2903
tolerances: fig3d KS 0.027 to 0.033; fig3c KS 0.045 to 0.055; figs7a 5 of 5 within 10%; figs6 adjusted p >= 0.05; figs11 boundary p >= 0.05; 90% recruitment 450 to 550 m

Sensitivity (not an outcome). For figs7a-mean-fields-per-animal all five animal means are within 10% under every allowance from 0 to 30 cm, and one of five without an allowance. For fig3d-uniform-density the KS statistic is within 0.03 +/- 0.003 from 10 to 30 cm (0.0307 to 0.0325) and outside at 0 cm (0.0341) and without an allowance (0.0442); p is 0.088 to 0.393 throughout. For fig3c-lomax-recruitment the statistic is within 0.05 +/- 0.005 only at 10 cm (0.0532, p 0.365 under K-a and 0.144 under K-b), below the tolerance at 0 cm and without an allowance (0.0402 and 0.0396), and above it from 15 cm (0.0598 to 0.0600), so its partial outcome rests on the allowance as well as on P-a. For figs6-few-field-cells-uniform no group has an adjusted p below 0.05 under any allowance (smallest 0.152). For figs11-no-boundary-remapping the boundary between sections 3 and 4 has p below 0.05 under every allowance (0.0125 to 0.0328). The 90% recruitment distance stays within 450 to 550 m (472 to 519 m). The data set's fields overlapped rise from 784 without an allowance to 842 at 20 cm, and nothing changes from 20 to 30 cm. The 20 cm of the main analysis is kept: it is two smoothing SDs, and the fields no longer change beyond it.

figs12-pairs-uncorrelated¶

Field locations are uncorrelated between pairs of cells; the correlations between the numbers of fields two cells have across spatial bins match the null of independence at every scale tested.

In [33]:
rng_s12 = np.random.default_rng(12)
rng_s12v = np.random.default_rng(1212)
S12, S12V = [], []

def pair_corr_null(M, sims):
    """Correlations over cells' bins for every pair, observed matrix M and null matrices sims."""
    Z = sims - sims.mean(axis=2, keepdims=True)
    sd = np.sqrt((Z ** 2).sum(axis=2))
    sd[sd == 0] = np.nan
    Z = Z / sd[..., None]
    return np.einsum("sik,sjk->sij", Z, Z)

for k in MAIN + ["F-b"]:
    f = FIELDS[k]
    for nbins in (48, 24, 12, 6, 3):
        acc = {sel: dict(obs=[], null_all=[], null_sum=np.zeros(2000), n=0) for sel in ("all pairs", "different tetrodes")}
        accv = dict(obs=[], null_sum=np.zeros(2000), n=0)
        for ai in range(5):
            nc = int(np.sum(cells.ai == ai))
            M = np.zeros((nc, nbins))
            g = f[f.ai == ai]
            b = np.clip((np.clip(g.loc_m.values, 0, 48) / 48 * nbins).astype(int), 0, nbins - 1)
            np.add.at(M, (g.cell.values, b), 1)
            iu = np.triu_indices(nc, 1)
            var_ok = M.std(axis=1) > 0
            pair_ok = var_ok[iu[0]] & var_ok[iu[1]]
            tt = animals[ai]["tetrode"]
            diff_tt = tt[iu[0]] != tt[iu[1]]
            r_obs = np.corrcoef(M)[iu] if pair_ok.any() else np.full(len(iu[0]), np.nan)
            sims = np.argsort(rng_s12.random((2000, nc, nbins)), axis=2)
            Ms = np.take_along_axis(np.broadcast_to(M, sims.shape), sims, axis=2)
            R = pair_corr_null(M, Ms)[:, iu[0], iu[1]]
            for sel, mask in (("all pairs", pair_ok), ("different tetrodes", pair_ok & diff_tt)):
                acc[sel]["obs"].append(r_obs[mask])
                acc[sel]["null_all"].append(R[:200][:, mask].ravel())
                acc[sel]["null_sum"] += R[:, mask].sum(axis=1)
                acc[sel]["n"] += int(mask.sum())
            if k in MAIN:
                # Variant null keeping the animal's own field locations: its fields reassigned to
                # cells at random, each cell keeping its number of fields (2000 times).
                cid = g.cell.values
                perm = np.argsort(rng_s12v.random((2000, len(cid))), axis=1)
                flat = (np.arange(2000)[:, None] * nc * nbins + cid[None, :] * nbins + b[perm]).ravel()
                Mv = np.bincount(flat, minlength=2000 * nc * nbins).reshape(2000, nc, nbins).astype(float)
                Rv = pair_corr_null(M, Mv)[:, iu[0], iu[1]][:, pair_ok]
                accv["obs"].append(r_obs[pair_ok])
                accv["null_sum"] += np.nansum(Rv, axis=1)
                accv["n"] += int(pair_ok.sum())
        for sel, d in acc.items():
            obs = np.concatenate(d["obs"])
            null_mean = d["null_sum"] / d["n"]
            ks = stats.ks_2samp(obs, np.concatenate(d["null_all"]))
            lo, hi = np.percentile(null_mean, [2.5, 97.5])
            (S12 if sel == "all pairs" else S12V).append(dict(reading=k, pairs_used=sel, null="bins shuffled", bins=nbins, pairs=d["n"],
                         obs_mean=obs.mean(), null_mean=null_mean.mean(), null_lo=lo, null_hi=hi,
                         Ub_inside=bool(lo <= obs.mean() <= hi), Ua_KS=ks.statistic, Ua_p=ks.pvalue))
        if k in MAIN:
            obs = np.concatenate(accv["obs"])
            null_mean = accv["null_sum"] / accv["n"]
            lo, hi = np.percentile(null_mean, [2.5, 97.5])
            S12V.append(dict(reading=k, pairs_used="all pairs", null="fields reassigned within animal", bins=nbins, pairs=accv["n"],
                             obs_mean=obs.mean(), null_mean=null_mean.mean(), null_lo=lo, null_hi=hi,
                             Ub_inside=bool(lo <= obs.mean() <= hi), Ua_KS=np.nan, Ua_p=np.nan))
s12 = pd.DataFrame(S12)
print(s12.round(4).to_string(index=False))
print("U-a uses the first 200 of the 2000 shuffles of each animal for the pooled null sample (a standard subsample); U-b uses all 2000.")
print("\nVariants, not the criterion's test: pairs on different tetrodes only (same shuffle), and a null that keeps each")
print("animal's field locations (U-b only; the KS test is not run on it).")
print(pd.DataFrame(S12V).round(4).to_string(index=False))
/home/runner/work/encore/encore/executed/rich-2014/.venv/lib/python3.13/site-packages/numpy/lib/_function_base_impl.py:3037: RuntimeWarning: invalid value encountered in divide
  c /= stddev[:, None]
/home/runner/work/encore/encore/executed/rich-2014/.venv/lib/python3.13/site-packages/numpy/lib/_function_base_impl.py:3038: RuntimeWarning: invalid value encountered in divide
  c /= stddev[None, :]
reading pairs_used          null  bins  pairs  obs_mean  null_mean  null_lo  null_hi  Ub_inside  Ua_KS   Ua_p
F-a/P-a  all pairs bins shuffled    48   2870    0.0065     0.0000  -0.0051   0.0056      False 0.0393 0.0003
F-a/P-a  all pairs bins shuffled    24   2870    0.0088     0.0001  -0.0072   0.0078      False 0.0314 0.0069
F-a/P-a  all pairs bins shuffled    12   2870    0.0116     0.0001  -0.0098   0.0119       True 0.0227 0.1046
F-a/P-a  all pairs bins shuffled     6   2827    0.0281    -0.0004  -0.0140   0.0182      False 0.0361 0.0013
F-a/P-a  all pairs bins shuffled     3   2556    0.0189    -0.0001  -0.0207   0.0312       True 0.0566 0.0000
F-a/P-b  all pairs bins shuffled    48   2802    0.0088     0.0000  -0.0049   0.0058      False 0.0410 0.0002
F-a/P-b  all pairs bins shuffled    24   2802    0.0096     0.0002  -0.0070   0.0085      False 0.0407 0.0002
F-a/P-b  all pairs bins shuffled    12   2802    0.0147    -0.0001  -0.0099   0.0122      False 0.0334 0.0039
F-a/P-b  all pairs bins shuffled     6   2802    0.0307    -0.0000  -0.0139   0.0183      False 0.0413 0.0001
F-a/P-b  all pairs bins shuffled     3   2575    0.0224    -0.0000  -0.0202   0.0326       True 0.0759 0.0000
    F-b  all pairs bins shuffled    48   2964    0.0065    -0.0000  -0.0049   0.0056      False 0.0308 0.0072
    F-b  all pairs bins shuffled    24   2964    0.0051    -0.0002  -0.0072   0.0074       True 0.0218 0.1189
    F-b  all pairs bins shuffled    12   2964    0.0060     0.0001  -0.0095   0.0118       True 0.0236 0.0739
    F-b  all pairs bins shuffled     6   2964    0.0194     0.0002  -0.0130   0.0179      False 0.0301 0.0093
    F-b  all pairs bins shuffled     3   2873    0.0066     0.0001  -0.0193   0.0316       True 0.0563 0.0000
U-a uses the first 200 of the 2000 shuffles of each animal for the pooled null sample (a standard subsample); U-b uses all 2000.

Variants, not the criterion's test: pairs on different tetrodes only (same shuffle), and a null that keeps each
animal's field locations (U-b only; the KS test is not run on it).
reading         pairs_used                            null  bins  pairs  obs_mean  null_mean  null_lo  null_hi  Ub_inside  Ua_KS   Ua_p
F-a/P-a different tetrodes                   bins shuffled    48   2513    0.0070     0.0000  -0.0056   0.0059      False 0.0423 0.0003
F-a/P-a          all pairs fields reassigned within animal    48   2870    0.0065     0.0047   0.0016   0.0079       True    NaN    NaN
F-a/P-a different tetrodes                   bins shuffled    24   2513    0.0101    -0.0000  -0.0074   0.0085      False 0.0336 0.0068
F-a/P-a          all pairs fields reassigned within animal    24   2870    0.0088     0.0080   0.0031   0.0132       True    NaN    NaN
F-a/P-a different tetrodes                   bins shuffled    12   2513    0.0122     0.0001  -0.0104   0.0128       True 0.0226 0.1545
F-a/P-a          all pairs fields reassigned within animal    12   2870    0.0116     0.0148   0.0064   0.0244       True    NaN    NaN
F-a/P-a different tetrodes                   bins shuffled     6   2478    0.0262    -0.0003  -0.0155   0.0187      False 0.0352 0.0044
F-a/P-a          all pairs fields reassigned within animal     6   2827    0.0281     0.0291   0.0146   0.0458       True    NaN    NaN
F-a/P-a different tetrodes                   bins shuffled     3   2233    0.0182     0.0000  -0.0235   0.0325       True 0.0581 0.0000
F-a/P-a          all pairs fields reassigned within animal     3   2556    0.0189     0.0217  -0.0012   0.0496       True    NaN    NaN
F-a/P-b different tetrodes                   bins shuffled    48   2455    0.0096     0.0000  -0.0053   0.0061      False 0.0437 0.0002
F-a/P-b          all pairs fields reassigned within animal    48   2802    0.0088     0.0059   0.0025   0.0095       True    NaN    NaN
F-a/P-b different tetrodes                   bins shuffled    24   2455    0.0111     0.0002  -0.0077   0.0092      False 0.0430 0.0002
F-a/P-b          all pairs fields reassigned within animal    24   2802    0.0096     0.0086   0.0035   0.0143       True    NaN    NaN
F-a/P-b different tetrodes                   bins shuffled    12   2455    0.0152    -0.0001  -0.0106   0.0129      False 0.0324 0.0115
F-a/P-b          all pairs fields reassigned within animal    12   2802    0.0147     0.0176   0.0085   0.0272       True    NaN    NaN
F-a/P-b different tetrodes                   bins shuffled     6   2455    0.0284     0.0000  -0.0157   0.0195      False 0.0393 0.0010
F-a/P-b          all pairs fields reassigned within animal     6   2802    0.0307     0.0320   0.0174   0.0476       True    NaN    NaN
F-a/P-b different tetrodes                   bins shuffled     3   2253    0.0210    -0.0001  -0.0234   0.0351       True 0.0779 0.0000
F-a/P-b          all pairs fields reassigned within animal     3   2575    0.0224     0.0234  -0.0013   0.0537       True    NaN    NaN
    F-b different tetrodes                   bins shuffled    48   2594    0.0059    -0.0000  -0.0055   0.0059       True 0.0311 0.0132
    F-b different tetrodes                   bins shuffled    24   2594    0.0056    -0.0002  -0.0073   0.0077       True 0.0236 0.1123
    F-b different tetrodes                   bins shuffled    12   2594    0.0063     0.0002  -0.0104   0.0123       True 0.0236 0.1104
    F-b different tetrodes                   bins shuffled     6   2594    0.0171    -0.0000  -0.0145   0.0192       True 0.0316 0.0114
    F-b different tetrodes                   bins shuffled     3   2514    0.0048     0.0001  -0.0221   0.0313       True 0.0553 0.0000

Result: not reproduced. Pairs of cells are slightly positively correlated against the criterion's null (each cell's bins shuffled). Under P-a the mean correlation is above the null's 95% interval at 48, 24 and 6 bins (0.0065, 0.0088 and 0.0281 against upper ends 0.0056, 0.0078 and 0.0182) and the two-sample KS test gives p 0.0003, 0.0100 and 0.0008 there; at 12 bins neither test differs (mean 0.0116 inside, KS p 0.114), and at 3 bins the mean is inside but the KS test differs. P-b differs under both tests at 48, 24, 12 and 6 bins. The effect is small (mean r at most 0.031). Variants: on pairs from different tetrodes the pattern is the same (P-a outside at 48, 24 and 6 bins). Against a null that keeps each animal's field locations and reassigns its fields to cells, the observed mean lies inside the 95% interval at every scale under both readings, so the positive correlation is consistent with what the uneven field density within each animal would give; this null does not show that the density causes it. Only one animal, ANM228900, has field locations that differ from uniform on their own (fig3d-uniform-density). The criterion's test is the paper's, and it finds the effect.

fig3e-memoryless-recruitment¶

Recruitment is memoryless; recruitment curves started at evenly spaced points along the track, ignoring earlier activity, have the same shape whatever the starting point, and the same holds working back from the far end.

In [34]:
rng_3e = np.random.default_rng(33)
S3E = []
for k in MAIN + ["F-b"]:
    r, p = NB[k]
    for s in range(0, 45, 5):
        for direction in ("forward", "reverse"):
            start = s if direction == "forward" else 48 - s
            d = rich.first_field(FIELDS[k].assign(loc_m=np.clip(FIELDS[k].loc_m, 0, 48)), cells, start=start,
                                 reverse=(direction == "reverse"))
            length = 48 - s
            D, pv = lomax_test(d, r, p, length, rng_3e, n_mc=2000)
            S3E.append(dict(reading=k, start=s, direction=direction, length=length, recruited=np.mean(np.isfinite(d)),
                            lomax_at_end=rich.lomax_cdf(length, r, p), KS=D, p=pv))
s3e = pd.DataFrame(S3E)
for k in MAIN + ["F-b"]:
    for V, step in (("V-a", 5), ("V-b", 10)):
        sel = (s3e.reading == k) & (s3e.start % step == 0)
        s3e.loc[sel, f"p_BH_{V}"] = rich.bh(s3e.loc[sel, "p"].values)
print(s3e.round(3).to_string(index=False))
for k in MAIN + ["F-b"]:
    for V in ("V-a", "V-b"):
        g = s3e[(s3e.reading == k) & s3e[f"p_BH_{V}"].notna()]
        bad = g[g[f"p_BH_{V}"] < 0.05]
        print(f"{k} {V}: curves {len(g)}, adjusted p < 0.05: {len(bad)}"
              + (f" (lengths {bad.length.tolist()})" if len(bad) else ""))
reading  start direction  length  recruited  lomax_at_end    KS     p  p_BH_V-a  p_BH_V-b
F-a/P-a      0   forward      48      0.640         0.665 0.064 0.231     0.849     0.857
F-a/P-a      0   reverse      48      0.640         0.665 0.047 0.554     0.849     0.864
F-a/P-a      5   forward      43      0.625         0.647 0.049 0.503     0.849       NaN
F-a/P-a      5   reverse      43      0.625         0.647 0.039 0.759     0.853       NaN
F-a/P-a     10   forward      38      0.601         0.626 0.059 0.274     0.849     0.857
F-a/P-a     10   reverse      38      0.605         0.626 0.029 0.943     0.943     0.943
F-a/P-a     15   forward      33      0.597         0.601 0.039 0.708     0.849       NaN
F-a/P-a     15   reverse      33      0.577         0.601 0.043 0.612     0.849       NaN
F-a/P-a     20   forward      28      0.573         0.571 0.039 0.691     0.849     0.864
F-a/P-a     20   reverse      28      0.561         0.571 0.042 0.616     0.849     0.864
F-a/P-a     25   forward      23      0.549         0.533 0.065 0.163     0.849       NaN
F-a/P-a     25   reverse      23      0.510         0.533 0.042 0.591     0.849       NaN
F-a/P-a     30   forward      18      0.474         0.484 0.025 0.943     0.943     0.943
F-a/P-a     30   reverse      18      0.470         0.484 0.052 0.325     0.849     0.857
F-a/P-a     35   forward      13      0.391         0.418 0.043 0.459     0.849       NaN
F-a/P-a     35   reverse      13      0.427         0.418 0.054 0.249     0.849       NaN
F-a/P-a     40   forward       8      0.312         0.322 0.033 0.623     0.849     0.864
F-a/P-a     40   reverse       8      0.352         0.322 0.045 0.343     0.849     0.857
F-a/P-b      0   forward      48      0.628         0.650 0.054 0.379     0.856     0.846
F-a/P-b      0   reverse      48      0.628         0.650 0.042 0.664     0.856     0.846
F-a/P-b      5   forward      43      0.613         0.632 0.064 0.194     0.856       NaN
F-a/P-b      5   reverse      43      0.613         0.632 0.035 0.832     0.881       NaN
F-a/P-b     10   forward      38      0.593         0.611 0.059 0.265     0.856     0.846
F-a/P-b     10   reverse      38      0.593         0.611 0.038 0.739     0.856     0.846
F-a/P-b     15   forward      33      0.585         0.585 0.045 0.571     0.856       NaN
F-a/P-b     15   reverse      33      0.561         0.585 0.047 0.504     0.856       NaN
F-a/P-b     20   forward      28      0.561         0.555 0.037 0.748     0.856     0.846
F-a/P-b     20   reverse      28      0.530         0.555 0.048 0.436     0.856     0.846
F-a/P-b     25   forward      23      0.538         0.517 0.056 0.266     0.856       NaN
F-a/P-b     25   reverse      23      0.478         0.517 0.052 0.356     0.856       NaN
F-a/P-b     30   forward      18      0.466         0.468 0.033 0.761     0.856     0.846
F-a/P-b     30   reverse      18      0.423         0.468 0.058 0.203     0.856     0.846
F-a/P-b     35   forward      13      0.379         0.403 0.035 0.663     0.856       NaN
F-a/P-b     35   reverse      13      0.383         0.403 0.054 0.239     0.856       NaN
F-a/P-b     40   forward       8      0.292         0.308 0.032 0.644     0.856     0.846
F-a/P-b     40   reverse       8      0.312         0.308 0.020 0.946     0.946     0.946
    F-b      0   forward      48      0.652         0.672 0.064 0.227     0.750     0.567
    F-b      0   reverse      48      0.652         0.672 0.066 0.192     0.750     0.567
    F-b      5   forward      43      0.636         0.655 0.050 0.460     0.750       NaN
    F-b      5   reverse      43      0.636         0.655 0.033 0.875     0.931       NaN
    F-b     10   forward      38      0.613         0.634 0.066 0.187     0.750     0.567
    F-b     10   reverse      38      0.617         0.634 0.028 0.951     0.951     0.951
    F-b     15   forward      33      0.609         0.609 0.044 0.583     0.750       NaN
    F-b     15   reverse      33      0.585         0.609 0.039 0.720     0.864       NaN
    F-b     20   forward      28      0.581         0.579 0.045 0.534     0.750     0.725
    F-b     20   reverse      28      0.557         0.579 0.054 0.371     0.750     0.725
    F-b     25   forward      23      0.557         0.541 0.056 0.289     0.750       NaN
    F-b     25   reverse      23      0.518         0.541 0.043 0.568     0.750       NaN
    F-b     30   forward      18      0.486         0.493 0.030 0.880     0.931     0.951
    F-b     30   reverse      18      0.470         0.493 0.060 0.209     0.750     0.567
    F-b     35   forward      13      0.391         0.427 0.049 0.350     0.750       NaN
    F-b     35   reverse      13      0.419         0.427 0.055 0.240     0.750       NaN
    F-b     40   forward       8      0.308         0.331 0.035 0.580     0.750     0.725
    F-b     40   reverse       8      0.344         0.331 0.037 0.514     0.750     0.725
F-a/P-a V-a: curves 18, adjusted p < 0.05: 0
F-a/P-a V-b: curves 10, adjusted p < 0.05: 0
F-a/P-b V-a: curves 18, adjusted p < 0.05: 0
F-a/P-b V-b: curves 10, adjusted p < 0.05: 0
F-b V-a: curves 18, adjusted p < 0.05: 0
F-b V-b: curves 10, adjusted p < 0.05: 0

Result: reproduced. No forward or reverse curve differs from the Lomax after adjustment, under either spacing (V-a, 18 curves; V-b, 10) and either pass reading; the smallest adjusted p is 0.849 (P-a) and 0.846 (P-b). Recruitment at the end of each curve stays within 0.05 of the Lomax.

figs14-field-properties¶

Field size (65 plus or minus 43 cm) and in-field rate (5 plus or minus 2 Hz) are not correlated with location along the track (rho 0.05 and 0.01) or with the number of other fields of the same cell (rho 0.05 and 0.05).

In [35]:
for k in MAIN + ["F-b"]:
    f = FIELDS[k].copy()
    n = f.groupby(["ai", "cell"]).size().rename("n").reset_index()
    f = f.merge(n, on=["ai", "cell"])
    f["others"] = f.n - 1
    variants = [("M-a", "size_cm", "rate"), ("M-b", "size_b", "rate_b")] if "F-a" in k else [("dataset", "size_cm", "rate")]
    for M, sc, rc in variants:
        s_ = f[sc].values; r_ = f[rc].values
        r1 = stats.spearmanr(s_, f.loc_m); r2 = stats.spearmanr(r_, f.loc_m)
        r3 = stats.spearmanr(s_, f.others); r4 = stats.spearmanr(r_, f.others)
        print(f"{k} {M}: n {len(f)} fields; size {s_.mean():.1f} +/- {s_.std(ddof=1):.1f} cm (expected 65 +/- 43); "
              f"rate {r_.mean():.2f} +/- {r_.std(ddof=1):.2f} Hz (expected 5 +/- 2)")
        print(f"     Spearman size~location {r1[0]:.3f} p {r1[1]:.3f}; rate~location {r2[0]:.3f} p {r2[1]:.3f}; "
              f"size~others {r3[0]:.3f} p {r3[1]:.3f}; rate~others {r4[0]:.3f} p {r4[1]:.3f}")

# Why the in-field rates of F-a are lower than the data set's (verifier round 2, point e). On the
# data set's own field extents (F-b), the rate is computed three ways from the recomputed maps: the
# criterion's mean of the smoothed map, its peak, and spikes over occupancy in the field's bins
# (unsmoothed), for the field's direction or both. Then the last is applied to the F-a fields.
def field_rates(f, dir_signs):
    cache, out = {}, []
    for _, r_ in f.iterrows():
        key = (r_.ai, r_.cell, r_.epoch)
        if key not in cache:
            cache[key] = rich.directional_maps(animals[r_.ai], r_.cell, r_.epoch)
        c, maps, _ = cache[key]
        sel = (c >= r_.start_cm) & (c <= r_.end_cm)
        signs = dir_signs[r_.direction]
        sm = np.nanmean(np.vstack([maps[s]["rate"] for s in signs]), axis=0)[sel]
        edges_ = np.r_[c - rich.BIN_CM / 2, c[-1] + rich.BIN_CM / 2]
        n_sp = sum(np.histogram(maps[s]["spike_x"], edges_)[0][sel].sum() for s in signs)
        occ = sum(maps[s]["occ"][sel].sum() for s in signs)
        out.append((np.nanmean(sm), np.nanmax(sm), n_sp / occ if occ else np.nan))
    return np.array(out)

FB = FIELDS["F-b"]
fr = field_rates(FB, {1: [-1], 2: [1], 3: [1, -1]})  # data set: 1 inbound, 2 outbound
print(f"F-b extents, {len(FB)} fields: data set's inFieldRate {FB.rate.mean():.2f} +/- {FB.rate.std():.2f} Hz; "
      f"recomputed map mean {np.nanmean(fr[:, 0]):.2f}, map peak {np.nanmean(fr[:, 1]):.2f}, "
      f"spikes over occupancy {np.nanmean(fr[:, 2]):.2f} Hz")
for d_, name in ((1, "inbound"), (2, "outbound"), (3, "both directions")):
    s_ = (FB.direction == d_).values
    print(f"     {name} ({int(s_.sum())} fields): data set {FB.rate[s_].mean():.2f}, map mean {np.nanmean(fr[s_, 0]):.2f}, "
          f"spikes over occupancy {np.nanmean(fr[s_, 2]):.2f} Hz")
print(f"     Pearson r of the data set's rate with the map mean {np.corrcoef(FB.rate, fr[:, 0])[0, 1]:.3f}, "
      f"with spikes over occupancy {np.corrcoef(FB.rate, fr[:, 2])[0, 1]:.3f}")
RAW_RATE = {}
for k in MAIN:
    RAW_RATE[k] = field_rates(FIELDS[k], {1: [1], 2: [-1], 3: [1, -1]})[:, 2]  # F-a: 1 outbound, 2 inbound
    print(f"{k}: in-field rate as spikes over occupancy {np.nanmean(RAW_RATE[k]):.2f} +/- {np.nanstd(RAW_RATE[k], ddof=1):.2f} Hz "
          f"(criterion's map mean {FIELDS[k].rate.mean():.2f}); above 4.8 Hz {100 * np.mean(RAW_RATE[k] > 4.8):.1f}% (variant, not the criterion's measure)")
F-a/P-a M-a: n 852 fields; size 70.7 +/- 47.7 cm (expected 65 +/- 43); rate 4.76 +/- 2.27 Hz (expected 5 +/- 2)
     Spearman size~location 0.069 p 0.044; rate~location 0.045 p 0.192; size~others 0.078 p 0.023; rate~others -0.049 p 0.157
F-a/P-a M-b: n 852 fields; size 65.0 +/- 38.3 cm (expected 65 +/- 43); rate 4.94 +/- 2.40 Hz (expected 5 +/- 2)
     Spearman size~location 0.094 p 0.006; rate~location 0.029 p 0.403; size~others 0.067 p 0.051; rate~others -0.042 p 0.223
F-a/P-b M-a: n 793 fields; size 72.0 +/- 48.2 cm (expected 65 +/- 43); rate 4.86 +/- 2.30 Hz (expected 5 +/- 2)
     Spearman size~location 0.059 p 0.098; rate~location 0.019 p 0.588; size~others 0.077 p 0.031; rate~others -0.065 p 0.069
F-a/P-b M-b: n 793 fields; size 66.4 +/- 38.9 cm (expected 65 +/- 43); rate 5.02 +/- 2.43 Hz (expected 5 +/- 2)
     Spearman size~location 0.080 p 0.025; rate~location 0.012 p 0.741; size~others 0.061 p 0.084; rate~others -0.056 p 0.115
F-b dataset: n 887 fields; size 65.2 +/- 42.9 cm (expected 65 +/- 43); rate 5.45 +/- 2.42 Hz (expected 5 +/- 2)
     Spearman size~location 0.053 p 0.111; rate~location 0.011 p 0.754; size~others 0.049 p 0.143; rate~others -0.046 p 0.170
F-b extents, 887 fields: data set's inFieldRate 5.45 +/- 2.42 Hz; recomputed map mean 4.94, map peak 7.29, spikes over occupancy 5.39 Hz
     inbound (364 fields): data set 5.25, map mean 4.95, spikes over occupancy 5.47 Hz
     outbound (356 fields): data set 5.18, map mean 4.81, spikes over occupancy 5.38 Hz
     both directions (167 fields): data set 6.45, map mean 5.18, spikes over occupancy 5.25 Hz
     Pearson r of the data set's rate with the map mean 0.924, with spikes over occupancy 0.926
F-a/P-a: in-field rate as spikes over occupancy 5.08 +/- 2.08 Hz (criterion's map mean 4.76); above 4.8 Hz 44.4% (variant, not the criterion's measure)
F-a/P-b: in-field rate as spikes over occupancy 5.19 +/- 2.11 Hz (criterion's map mean 4.86); above 4.8 Hz 47.3% (variant, not the criterion's measure)

Result: not reproduced. Under every reading of F-a at least one of the four correlations has p < 0.05: field size against location (rho 0.069, p 0.044 under P-a M-a; 0.094, p 0.006 under P-a M-b; 0.080, p 0.025 under P-b M-b) or size against the number of other fields (0.078, p 0.023 under P-a M-a; 0.077, p 0.031 under P-b M-a). The correlations are small. Field size (65.0 to 72.0 cm, SD 38.3 to 48.2) and mean rate (4.76 to 5.02 Hz) are near the paper's values, the rate SD (2.27 to 2.43 Hz) above 2 +/- 0.2. The data set's fields give no correlation with p < 0.05 (smallest 0.111), size 65.2 +/- 42.9 cm and rate 5.45 +/- 2.42 Hz. Diagnosis of the rates (verifier round 2, point e): on the data set's own field extents, the criterion's measure (the mean of the recomputed smoothed map) gives 4.94 Hz against the data set's 5.45 Hz, while spikes over occupancy in the field's bins give 5.39 Hz; the gap is largest for fields of both directions (data set 6.45, map mean 5.18, spikes over occupancy 5.25 Hz). So about 0.5 Hz of the difference comes from how the rate is measured, which the data set does not document, and the rest (4.94 against 4.76 Hz under P-a M-a) from the field extents. On the F-a fields spikes over occupancy give 5.08 (P-a) and 5.19 Hz (P-b). The criterion fixes the map mean, so this is a variant.

figs15-higher-threshold¶

Different criteria for place field detection do not change the results; with a higher threshold (an in-field rate above 4.8 Hz, which about 50% of fields reach), the gamma-Poisson model still describes the number of fields per cell and the recruitment of cells.

In [36]:
rng_s15 = np.random.default_rng(15)
for k in MAIN + ["F-b"]:
    f = FIELDS[k]
    variants = [("M-a", "rate"), ("M-b", "rate_b")] if "F-a" in k else [("dataset", "rate")]
    for M, rc in variants:
        keep = f[f[rc] > 4.8]
        x = rich.counts(keep, cells)
        r, p, _ = rich.nbinfit(x)
        first = np.clip(rich.first_field(keep, cells), 0, 48)
        d, p_ka = lomax_test(first, r, p, 48, rng_s15)
        _, p_kb = lomax_test(first, r, p, 48, rng_s15, refit=True)
        dt = dispersion_tests(x)
        print(f"{k} {M}: fields kept {len(keep)} of {len(f)} ({100 * len(keep) / len(f):.1f}%, expected 50 +/- 5); "
              f"refit r {r:.3f}, p {p:.3f}; recruitment KS {d:.3f}, p K-a {p_ka:.3f}, K-b {p_kb:.3f}; "
              f"dispersion p D-a {dt['p_Da']:.2e}, D-b {dt['p_Db']:.2e}")
# Variant (verifier round 2, point e): the in-field rate as spikes over occupancy in the field's
# bins (RAW_RATE, figs14 cell), not the criterion's map mean. Fraction kept only.
for k in MAIN:
    print(f"{k} spikes over occupancy (variant): fields above 4.8 Hz {int(np.sum(RAW_RATE[k] > 4.8))} of {len(RAW_RATE[k])} "
          f"({100 * np.mean(RAW_RATE[k] > 4.8):.1f}%)")
F-a/P-a M-a: fields kept 326 of 852 (38.3%, expected 50 +/- 5); refit r 0.512, p 0.284; recruitment KS 0.038, p K-a 0.676, K-b 0.371; dispersion p D-a 5.73e-55, D-b 2.12e-45
F-a/P-a M-b: fields kept 360 of 852 (42.3%, expected 50 +/- 5); refit r 0.541, p 0.275; recruitment KS 0.036, p K-a 0.720, K-b 0.464; dispersion p D-a 6.72e-63, D-b 3.53e-50
F-a/P-b M-a: fields kept 318 of 793 (40.1%, expected 50 +/- 5); refit r 0.525, p 0.294; recruitment KS 0.031, p K-a 0.824, K-b 0.601; dispersion p D-a 5.65e-53, D-b 3.64e-43
F-a/P-b M-b: fields kept 349 of 793 (44.0%, expected 50 +/- 5); refit r 0.550, p 0.285; recruitment KS 0.028, p K-a 0.929, K-b 0.782; dispersion p D-a 2.66e-58, D-b 5.51e-47
F-b dataset: fields kept 450 of 887 (50.7%, expected 50 +/- 5); refit r 0.604, p 0.254; recruitment KS 0.027, p K-a 0.945, K-b 0.870; dispersion p D-a 3.37e-70, D-b 3.42e-58
F-a/P-a spikes over occupancy (variant): fields above 4.8 Hz 378 of 852 (44.4%)
F-a/P-b spikes over occupancy (variant): fields above 4.8 Hz 375 of 793 (47.3%)

Result: partially reproduced. With fields above 4.8 Hz the refitted gamma-Poisson model still describes recruitment (KS 0.028 to 0.038, p 0.371 to 0.929 under K-a and K-b, every reading), but only 38.3 to 44.0% of the recomputed fields pass the threshold, outside 50 +/- 5%. The data set's fields give 50.7%. The criterion names no outcome for this case; the recruitment part holds and the fraction does not. With the in-field rate taken as spikes over occupancy (a variant, figs14 section, not the criterion's measure), 44.4% (P-a) and 47.3% (P-b) of fields pass 4.8 Hz, so part of the low fraction comes from the rate measure.

figs16-anatomy¶

The number of fields per cell is weakly related to the anatomical position of the cell in the pooled data (septotemporal r = -0.20, p = 0.001; proximodistal r = -0.19, p = 0.002), but the relation is not consistent within individual animals.

In [37]:
for k in MAIN + ["F-b"]:
    x = COUNTS[k]
    for R, fn in (("R-a Pearson", stats.pearsonr), ("R-b Spearman", stats.spearmanr)):
        st_ = fn(cells.st, x); pd_ = fn(cells.pd, x)
        per = []
        for ai, an in enumerate(ANIMALS):
            sel = cells.ai.values == ai
            a1 = fn(cells.st[sel], x[sel]); a2 = fn(cells.pd[sel], x[sel])
            per.append((an, round(float(a1[0]), 2), round(float(a1[1]), 3), round(float(a2[0]), 2), round(float(a2[1]), 3)))
        per = pd.DataFrame(per, columns=["animal", "st r", "st p", "pd r", "pd p"])
        st_sig_same = int(np.sum((per["st p"] < 0.05) & (np.sign(per["st r"]) == np.sign(st_[0]))))
        pd_sig_same = int(np.sum((per["pd p"] < 0.05) & (np.sign(per["pd r"]) == np.sign(pd_[0]))))
        st_opp = int(np.sum(np.sign(per["st r"]) == -np.sign(st_[0])))
        pd_opp = int(np.sum(np.sign(per["pd r"]) == -np.sign(pd_[0])))
        print(f"{k} {R}: pooled ST r {st_[0]:.3f} p {st_[1]:.2g} (expected -0.20 +/- 0.02); PD r {pd_[0]:.3f} p {pd_[1]:.2g} "
              f"(expected -0.19 +/- 0.019)")
        print(f"     animals significant with the pooled sign: ST {st_sig_same}, PD {pd_sig_same} (N-a holds when < 3); "
              f"animals with the opposite sign: ST {st_opp}, PD {pd_opp} (N-b holds when >= 1)")
        print("     " + per.to_string(index=False).replace("\n", "\n     "))
F-a/P-a R-a Pearson: pooled ST r -0.215 p 0.00059 (expected -0.20 +/- 0.02); PD r -0.198 p 0.0016 (expected -0.19 +/- 0.019)
     animals significant with the pooled sign: ST 1, PD 1 (N-a holds when < 3); animals with the opposite sign: ST 1, PD 2 (N-b holds when >= 1)
          animal  st r  st p  pd r  pd p
     ANM00190422 -0.26 0.039 -0.32 0.010
       ANM204878 -0.24 0.066 -0.18 0.168
       ANM212379 -0.37 0.077  0.09 0.682
       ANM228899  0.05 0.724  0.06 0.671
       ANM228900 -0.22 0.128 -0.06 0.693
F-a/P-a R-b Spearman: pooled ST r -0.300 p 1.2e-06 (expected -0.20 +/- 0.02); PD r -0.243 p 9.4e-05 (expected -0.19 +/- 0.019)
     animals significant with the pooled sign: ST 2, PD 1 (N-a holds when < 3); animals with the opposite sign: ST 1, PD 2 (N-b holds when >= 1)
          animal  st r  st p  pd r  pd p
     ANM00190422 -0.29 0.021 -0.33 0.007
       ANM204878 -0.24 0.067 -0.19 0.158
       ANM212379 -0.50 0.013  0.07 0.759
       ANM228899  0.08 0.568  0.09 0.508
       ANM228900 -0.23 0.098 -0.05 0.737
F-a/P-b R-a Pearson: pooled ST r -0.215 p 0.00058 (expected -0.20 +/- 0.02); PD r -0.192 p 0.0022 (expected -0.19 +/- 0.019)
     animals significant with the pooled sign: ST 1, PD 1 (N-a holds when < 3); animals with the opposite sign: ST 1, PD 2 (N-b holds when >= 1)
          animal  st r  st p  pd r  pd p
     ANM00190422 -0.27 0.035 -0.31 0.013
       ANM204878 -0.25 0.057 -0.19 0.149
       ANM212379 -0.33 0.112  0.11 0.618
       ANM228899  0.01 0.947  0.07 0.595
       ANM228900 -0.22 0.115 -0.04 0.802
F-a/P-b R-b Spearman: pooled ST r -0.292 p 2.3e-06 (expected -0.20 +/- 0.02); PD r -0.247 p 7.4e-05 (expected -0.19 +/- 0.019)
     animals significant with the pooled sign: ST 2, PD 1 (N-a holds when < 3); animals with the opposite sign: ST 1, PD 2 (N-b holds when >= 1)
          animal  st r  st p  pd r  pd p
     ANM00190422 -0.29 0.022 -0.33 0.008
       ANM204878 -0.24 0.069 -0.19 0.148
       ANM212379 -0.42 0.043  0.06 0.784
       ANM228899  0.07 0.604  0.09 0.499
       ANM228900 -0.24 0.096 -0.04 0.775
F-b R-a Pearson: pooled ST r -0.199 p 0.0014 (expected -0.20 +/- 0.02); PD r -0.193 p 0.0021 (expected -0.19 +/- 0.019)
     animals significant with the pooled sign: ST 0, PD 1 (N-a holds when < 3); animals with the opposite sign: ST 1, PD 2 (N-b holds when >= 1)
          animal  st r  st p  pd r  pd p
     ANM00190422 -0.23 0.067 -0.29 0.021
       ANM204878 -0.23 0.083 -0.17 0.206
       ANM212379 -0.36 0.087  0.05 0.833
       ANM228899  0.06 0.660  0.06 0.635
       ANM228900 -0.21 0.135 -0.04 0.791
F-b R-b Spearman: pooled ST r -0.300 p 1.1e-06 (expected -0.20 +/- 0.02); PD r -0.245 p 8.3e-05 (expected -0.19 +/- 0.019)
     animals significant with the pooled sign: ST 3, PD 1 (N-a holds when < 3); animals with the opposite sign: ST 1, PD 2 (N-b holds when >= 1)
          animal  st r  st p  pd r  pd p
     ANM00190422 -0.29 0.022 -0.33 0.007
       ANM204878 -0.30 0.024 -0.23 0.083
       ANM212379 -0.46 0.024  0.03 0.901
       ANM228899  0.08 0.546  0.08 0.555
       ANM228900 -0.24 0.097 -0.03 0.824

Result: reproduced. Under R-a (Pearson) and P-a the pooled correlations are -0.215 (septotemporal, p 0.00059) and -0.198 (proximodistal, p 0.0016), within tolerance; only one animal shows a significant correlation of the pooled sign on each axis (N-a), and some animals have the opposite sign (N-b). P-b gives -0.215 and -0.192. Under R-b (Spearman) the pooled values, -0.29 to -0.30 and -0.24 to -0.25, are outside tolerance.

fig4a-pre-sleep-rate¶

Firing rates in slow-wave sleep before the animal experienced the maze are moderately correlated with the later number of fields per cell (r = 0.45, P < 10^-13), evidence that preexisting differences between cells contribute to field propensity.

The SWS periods are the data set's intSWS (the claims file's criterion uses them when present).

In [38]:
sws = np.concatenate([rich.sws_rates(a)[0] for a in animals])
print("SWS rate per cell, Hz: median", np.median(sws).round(3), "range", sws.min().round(4), "to", sws.max().round(2),
      "; cells with zero SWS spikes", int((sws == 0).sum()))
pos_min = sws[sws > 0].min()
for k in MAIN + ["F-b"]:
    x = COUNTS[k]
    wa = stats.pearsonr(sws, x); wb = stats.pearsonr(np.log10(np.where(sws > 0, sws, pos_min)), x)
    wc = stats.spearmanr(sws, x)
    per = [round(float(stats.pearsonr(sws[cells.ai.values == ai], x[cells.ai.values == ai])[0]), 2) for ai in range(5)]
    print(f"{k}: W-a Pearson r {wa[0]:.3f} p {wa[1]:.2g}; W-b log10 r {wb[0]:.3f} p {wb[1]:.2g}; "
          f"W-c Spearman {wc[0]:.3f} p {wc[1]:.2g}; W-a p below 1e-13: {wa[1] < 1e-13}  (expected 0.45 +/- 0.045, p < 1e-13); per-animal Pearson {per}")
SWS rate per cell, Hz: median 0.163 range 0.0206 to 1.6 ; cells with zero SWS spikes 0
F-a/P-a: W-a Pearson r 0.450 p 5e-14; W-b log10 r 0.422 p 2.3e-12; W-c Spearman 0.383 p 2.9e-10; W-a p below 1e-13: True  (expected 0.45 +/- 0.045, p < 1e-13); per-animal Pearson [0.43, 0.53, 0.46, 0.36, 0.5]
F-a/P-b: W-a Pearson r 0.455 p 2.6e-14; W-b log10 r 0.432 p 6.2e-13; W-c Spearman 0.392 p 9.7e-11; W-a p below 1e-13: True  (expected 0.45 +/- 0.045, p < 1e-13); per-animal Pearson [0.41, 0.55, 0.48, 0.36, 0.47]
F-b: W-a Pearson r 0.446 p 8.8e-14; W-b log10 r 0.421 p 2.7e-12; W-c Spearman 0.390 p 1.3e-10; W-a p below 1e-13: True  (expected 0.45 +/- 0.045, p < 1e-13); per-animal Pearson [0.42, 0.5, 0.47, 0.4, 0.49]

Result: reproduced. Under W-a (Pearson on rates) r = 0.450 with p 5e-14 for P-a and 0.455 with p 2.6e-14 for P-b, within 0.45 +/- 0.045 and below 1e-13. Log rates (0.422 and 0.432) and Spearman (0.383 and 0.392) give lower values. Each animal's Pearson r lies between 0.36 and 0.55.

fig4b-single-field-proportion¶

Under the gamma-distributed propensities the proportion of cells with a single field would stay at about 5 to 10% over a wide range of environment sizes, which could allow a simple readout of location.

In [39]:
L = np.logspace(-1, 4, 2001)

def single_field(r, p, L, reading):
    pL = 1 / (1 + (L / 48) * (1 - p) / p)
    one = r * pL ** r * (1 - pL)
    return one if reading == "X-a" else one / (1 - pL ** r)

def widest(L, y, lo=4.5, hi=11.0):
    ok = (y >= lo) & (y <= hi)
    best = (np.nan, np.nan, 1.0)
    for s0, e0 in zip(*rich._runs(ok)):
        fac = L[e0 - 1] / L[s0]
        if fac > best[2] or np.isnan(best[0]):
            best = (L[s0], L[e0 - 1], fac)
    return best

# The criterion's threshold: the factor spanned by the printed parameters (r 0.57, p 0.14) under the
# same reading, less 10%; the claims file states 5.0 (X-a) and 3.9 (X-b).
NEED = {"X-a": 5.0, "X-b": 3.9}
for X in ("X-a", "X-b"):
    lo_, hi_, fac = widest(L, 100 * single_field(0.57, 0.14, L, X))
    print(f"printed parameters {X}: {lo_:.1f} to {hi_:.1f} m, factor {fac:.2f}, less 10% {0.9 * fac:.2f} "
          f"(claims file {NEED[X]})")
for k in MAIN + ["F-b"]:
    r, p = NB[k]
    for X in ("X-a", "X-b"):
        y = 100 * single_field(r, p, L, X)
        lo_, hi_, fac = widest(L, y)
        inside = y[(L >= lo_) & (L <= hi_)]
        print(f"{k} {X}: at 48 m {100 * single_field(r, p, np.array([48.0]), X)[0]:.1f}%; widest interval inside 4.5-11%: "
              f"{lo_:.1f} to {hi_:.1f} m, factor {fac:.2f} (needed {NEED[X]}, met {fac >= NEED[X]}), "
              f"proportion there {inside.min():.2f} to {inside.max():.2f}%; over 0.1 m to 10 km from {y.min():.2f} to {y.max():.2f}%")
printed parameters X-a: 117.5 to 649.4 m, factor 5.53, less 10% 4.97 (claims file 5.0)
printed parameters X-b: 171.8 to 745.6 m, factor 4.34, less 10% 3.91 (claims file 3.9)
F-a/P-a X-a: at 48 m 16.1%; widest interval inside 4.5-11%: 122.3 to 691.8 m, factor 5.66 (needed 5.0, met True), proportion there 4.50 to 11.00%; over 0.1 m to 10 km from 0.69 to 20.27%
F-a/P-a X-b: at 48 m 24.3%; widest interval inside 4.5-11%: 179.9 to 794.3 m, factor 4.42 (needed 3.9, met True), proportion there 4.51 to 11.00%; over 0.1 m to 10 km from 1.04 to 99.04%
F-a/P-b X-a: at 48 m 16.5%; widest interval inside 4.5-11%: 131.8 to 758.6 m, factor 5.75 (needed 5.0, met True), proportion there 4.51 to 11.00%; over 0.1 m to 10 km from 0.64 to 20.15%
F-a/P-b X-b: at 48 m 25.3%; widest interval inside 4.5-11%: 196.1 to 881.0 m, factor 4.49 (needed 3.9, met True), proportion there 4.50 to 10.98%; over 0.1 m to 10 km from 1.12 to 99.09%
F-b X-a: at 48 m 15.9%; widest interval inside 4.5-11%: 117.5 to 656.9 m, factor 5.59 (needed 5.0, met True), proportion there 4.51 to 10.99%; over 0.1 m to 10 km from 0.72 to 20.31%
F-b X-b: at 48 m 23.7%; widest interval inside 4.5-11%: 172.8 to 758.6 m, factor 4.39 (needed 3.9, met True), proportion there 4.50 to 10.97%; over 0.1 m to 10 km from 1.00 to 99.00%

Result: reproduced. With the P-a fit the proportion stays inside 4.5 to 11% from 122 to 692 m under X-a, a factor of 5.66 in size, above the 5.0 that the printed parameters less 10% set (they give 5.53); X-b gives 180 to 794 m, a factor of 4.42, above 3.9. P-b gives 5.75 and 4.49. At 48 m the proportion is 16.1% (X-a), above the 5 to 10% band, so the band holds for environments of roughly 120 to 690 m, not for the track itself. The data set's fields give factors of 5.59 and 4.39. The criterion was amended after a reader's answer (questions/rich-2014.yaml); under the earlier factor of 10 the outcome was not reproduced.

fig4c-active-subsets¶

Unlike equal propensities, which recruit all cells in large enough environments, the observed distribution of propensities lets environments over a wider range of sizes be distinguished by their active subsets, even with each cell's propensity fixed across environments.

In [40]:
def xor_matrix(rates_per_m, sizes, rng):
    active = rng.poisson(np.outer(rates_per_m, sizes)) > 0  # cells x environments
    A = active.astype(float)
    return (A.T @ (1 - A) + (1 - A).T @ A) / len(rates_per_m)

SPACING = {"G-a": lambda: np.logspace(-1, np.log10(50), 300), "G-b": lambda: np.linspace(0.1, 50, 300)}
LEVELS = {"K-a": 0.1, "K-b": 0.2}
off = ~np.eye(300, dtype=bool)
rows = []
for k in MAIN + ["F-b"]:
    r, p = NB[k]
    mean_per_m = COUNTS[k].mean() / 48
    for G in ("G-a", "G-b"):
        rng_4c = np.random.default_rng(4)
        sizes = SPACING[G]()
        big = np.outer(sizes > 10, sizes > 10)
        np.fill_diagonal(big, False)
        gp = xor_matrix(rng_4c.gamma(r, (1 - p) / p / 48, 1000), sizes, rng_4c)
        eq = xor_matrix(np.full(1000, mean_per_m), sizes, rng_4c)
        lo = xor_matrix(np.full(1000, mean_per_m / 2), sizes, rng_4c)
        hi = xor_matrix(np.full(1000, mean_per_m * 2), sizes, rng_4c)
        for K, lev in LEVELS.items():
            rows.append(dict(reading=k, G=G, K=K, gamma_poisson=np.mean(gp[off] > lev), equal_rate=np.mean(eq[off] > lev),
                             half_rate=np.mean(lo[off] > lev), twice_rate=np.mean(hi[off] > lev)))
        print(f"{k} {G}: reported, not judged: mean XOR over pairs both > 10 m: gamma-Poisson {gp[big].mean():.3f}, "
              f"equal-rate {eq[big].mean():.3f}, half rate {lo[big].mean():.3f}, twice rate {hi[big].mean():.3f}; "
              f"pairs both > 20 m, twice rate {hi[np.outer(sizes > 20, sizes > 20)].mean():.3f}")
print("sizes below 1 m:", {G: int(np.sum(SPACING[G]() < 1)) for G in SPACING}, "of 300")
s4c = pd.DataFrame(rows)
s4c["difference"] = s4c.gamma_poisson - s4c.equal_rate
s4c["gamma_higher"] = s4c.difference > 0
print("Share of all pairs of different environments with an exclusive-OR proportion above the level:")
print(s4c.round(3).to_string(index=False))

# Seed check for the judged comparison (P-a fit): 10 further seeds per spacing.
r, p = NB["F-a/P-a"]
mean_per_m = COUNTS["F-a/P-a"].mean() / 48
for G in ("G-a", "G-b"):
    d = {K: [] for K in LEVELS}
    for seed in range(10):
        rng_seed = np.random.default_rng(400 + seed)
        sizes = SPACING[G]()
        gp = xor_matrix(rng_seed.gamma(r, (1 - p) / p / 48, 1000), sizes, rng_seed)
        eq = xor_matrix(np.full(1000, mean_per_m), sizes, rng_seed)
        for K, lev in LEVELS.items():
            d[K].append(np.mean(gp[off] > lev) - np.mean(eq[off] > lev))
    for K in LEVELS:
        print(f"F-a/P-a {G} {K}: gamma-Poisson minus equal-rate share over 10 seeds, {np.min(d[K]):.3f} to {np.max(d[K]):.3f}")

# The matrices under both spacings (verifier round 3 asked for the G-b ones, on which the outcome rests).
r, p = NB["F-a/P-a"]
fig, ax = plt.subplots(2, 2, figsize=(8, 7))
for j, G in enumerate(("G-a", "G-b")):
    rng_4c = np.random.default_rng(4)
    sizes = SPACING[G]()
    gp_rates = rng_4c.gamma(r, (1 - p) / p / 48, 1000)
    if G == "G-a":
        print("expected share of cells active at 50 m: gamma-Poisson", round(float(np.mean(1 - np.exp(-gp_rates * 50))), 3),
              "equal-rate", round(float(1 - np.exp(-COUNTS["F-a/P-a"].mean() / 48 * 50)), 3))
    ext = [np.log10(0.1), np.log10(50)] * 2 if G == "G-a" else [0.1, 50] * 2
    for i, (name, rates) in enumerate([("gamma-Poisson", gp_rates),
                                        ("equal-rate", np.full(1000, COUNTS["F-a/P-a"].mean() / 48))]):
        M = xor_matrix(rates, sizes, rng_4c)
        im = ax[j, i].imshow(M, origin="lower", extent=ext, vmin=0, vmax=0.6)
        ax[j, i].set_title(f"{name} (F-a/P-a, {G})")
        ax[j, i].set_xlabel("log10 size (m)" if G == "G-a" else "size (m)")
        print(name, G, "XOR range", M.min().round(3), "to", M.max().round(3), "(colour scale 0 to 0.6)")
fig.colorbar(im, ax=ax)
plt.show()

# Which spacing Fig. S18 shows (verifier round 2, point d). Fig. S18 (supplement page 32) draws both
# rows against "environment size (m)" on axes marked 0 and 50 at their ends; a logarithmic axis
# cannot start at 0. As a second check, the share of the image width (of the 300 sizes, in order)
# over which a condition's exclusive-OR proportion with the largest environment exceeds 0.5: in
# Fig. S18 the high-rate panel is bright only in a narrow strip at the left edge.
r, p = NB["F-a/P-a"]
mean_per_m = COUNTS["F-a/P-a"].mean() / 48
for G in ("G-a", "G-b"):
    rng_s18 = np.random.default_rng(418)
    sizes = SPACING[G]()
    conds = {"gamma-Poisson": rng_s18.gamma(r, (1 - p) / p / 48, 1000), "equal-rate": np.full(1000, mean_per_m),
             "half rate": np.full(1000, mean_per_m / 2), "twice rate": np.full(1000, mean_per_m * 2)}
    share = {}
    for name, rates in conds.items():
        M = xor_matrix(rates, sizes, rng_s18)
        share[name] = round(float(np.mean(M[:, -1] > 0.5)), 3)
    print(f"{G}: share of the width with exclusive-OR against the 50 m environment above 0.5: {share}; "
          f"size at 10% of the width {sizes[29]:.2f} m")
# The fitted equal rate would need this many fields per 48 m for the bright strip of a high-rate
# condition to cover only the first 5% of the width (exclusive-OR 0.5 with the 50 m environment
# at the 15th size, assuming all cells active at 50 m):
for G in ("G-a", "G-b"):
    L5 = SPACING[G]()[14]
    print(f"{G}: 5% of the width is {L5:.2f} m; the rate giving half the cells active there is "
          f"{np.log(2) / L5 * 48:.0f} fields per 48 m (fitted equal rate {COUNTS['F-a/P-a'].mean():.2f})")
F-a/P-a G-a: reported, not judged: mean XOR over pairs both > 10 m: gamma-Poisson 0.264, equal-rate 0.348, half rate 0.495, twice rate 0.133; pairs both > 20 m, twice rate 0.035
F-a/P-a G-b: reported, not judged: mean XOR over pairs both > 10 m: gamma-Poisson 0.247, equal-rate 0.274, half rate 0.471, twice rate 0.084; pairs both > 20 m, twice rate 0.028
F-a/P-b G-a: reported, not judged: mean XOR over pairs both > 10 m: gamma-Poisson 0.266, equal-rate 0.371, half rate 0.498, twice rate 0.150; pairs both > 20 m, twice rate 0.043
F-a/P-b G-b: reported, not judged: mean XOR over pairs both > 10 m: gamma-Poisson 0.251, equal-rate 0.299, half rate 0.482, twice rate 0.097; pairs both > 20 m, twice rate 0.036
F-b G-a: reported, not judged: mean XOR over pairs both > 10 m: gamma-Poisson 0.262, equal-rate 0.336, half rate 0.492, twice rate 0.125; pairs both > 20 m, twice rate 0.031
F-b G-b: reported, not judged: mean XOR over pairs both > 10 m: gamma-Poisson 0.245, equal-rate 0.262, half rate 0.463, twice rate 0.077; pairs both > 20 m, twice rate 0.025
sizes below 1 m: {'G-a': 111, 'G-b': 6} of 300
Share of all pairs of different environments with an exclusive-OR proportion above the level:
reading   G   K  gamma_poisson  equal_rate  half_rate  twice_rate  difference  gamma_higher
F-a/P-a G-a K-a          0.835       0.848      0.734       0.898      -0.013         False
F-a/P-a G-a K-b          0.679       0.714      0.592       0.786      -0.036         False
F-a/P-a G-b K-a          1.000       0.952      0.998       0.577       0.048          True
F-a/P-a G-b K-b          0.923       0.780      0.992       0.430       0.143          True
F-a/P-b G-a K-a          0.822       0.833      0.723       0.893      -0.011         False
F-a/P-b G-a K-b          0.656       0.706      0.575       0.780      -0.049         False
F-a/P-b G-b K-a          0.999       0.978      0.998       0.610       0.021          True
F-a/P-b G-b K-b          0.948       0.826      0.990       0.456       0.123          True
    F-b G-a K-a          0.841       0.849      0.741       0.902      -0.007         False
    F-b G-a K-b          0.679       0.721      0.596       0.789      -0.042         False
    F-b G-b K-a          1.000       0.935      0.998       0.565       0.065          True
    F-b G-b K-b          0.909       0.762      0.992       0.410       0.146          True
F-a/P-a G-a K-a: gamma-Poisson minus equal-rate share over 10 seeds, -0.024 to 0.000
F-a/P-a G-a K-b: gamma-Poisson minus equal-rate share over 10 seeds, -0.057 to -0.031
F-a/P-a G-b K-a: gamma-Poisson minus equal-rate share over 10 seeds, 0.045 to 0.050
F-a/P-a G-b K-b: gamma-Poisson minus equal-rate share over 10 seeds, 0.108 to 0.190
expected share of cells active at 50 m: gamma-Poisson 0.681 equal-rate 0.97
gamma-Poisson G-a XOR range 0.0 to 0.679 (colour scale 0 to 0.6)
equal-rate G-a XOR range 0.0 to 0.973 (colour scale 0 to 0.6)
gamma-Poisson G-b XOR range 0.0 to 0.692 (colour scale 0 to 0.6)
equal-rate G-b XOR range 0.0 to 0.968 (colour scale 0 to 0.6)
No description has been provided for this image
G-a: share of the width with exclusive-OR against the 50 m environment above 0.5: {'gamma-Poisson': 0.6, 'equal-rate': 0.74, 'half rate': 0.85, 'twice rate': 0.627}; size at 10% of the width 0.18 m
G-b: share of the width with exclusive-OR against the 50 m environment above 0.5: {'gamma-Poisson': 0.087, 'equal-rate': 0.197, 'half rate': 0.387, 'twice rate': 0.1}; size at 10% of the width 4.94 m
G-a: 5% of the width is 0.13 m; the rate giving half the cells active there is 249 fields per 48 m (fitted equal rate 3.37)
G-b: 5% of the width is 2.44 m; the rate giving half the cells active there is 14 fields per 48 m (fitted equal rate 3.37)

Result: reproduced, resting on the assumption of linear spacing (G-b). The verifier agreed with this change in round 3; the outcome verified in round 2 was not reproduced under logarithmic spacing (G-a). The readings disagree. With logarithmic sizes the share of pairs of different environments with an exclusive-OR proportion above the level is lower for the gamma-Poisson model than for the fitted equal-rate model, 0.835 against 0.848 (K-a, 0.1) and 0.679 against 0.714 (K-b, 0.2), under the P-a fit; with linear sizes it is higher, 1.000 against 0.952 and 0.923 against 0.780. P-b and the data set's fields give the same signs. Over 10 further seeds the difference under G-a is -0.024 to 0.000 for K-a, so that sign is within seed noise, and -0.057 to -0.031 for K-b; under G-b it is 0.045 to 0.050 and 0.108 to 0.190.

The spacing. Two of the reasons given before for G-a do not hold (verifier round 2): the phrase "over spatial scales spanning several orders of magnitude" describes the recruitment curve of Fig. 3C, not this simulation, and the "small environments" of the Fig. S18 legend are those where the low-rate condition performs poorly. Fig. S18 itself (supplement page 32, rendered in this revision) draws both of its rows against "environment size (m)" on axes marked 0 and 50 at their ends, which a logarithmic axis cannot be, and its arrows mark environments at about 10 and 30 m. Its high-rate panel is bright only in a narrow strip at the left edge. Here the exclusive-OR proportion with the 50 m environment is above 0.5 over 0.627 of the sizes for twice the fitted rate under G-a, and a strip of 5% of the width would need about 249 fields per 48 m; under G-b it is 0.100 of the sizes, and 5% needs about 14 fields per 48 m. Linear spacing is thus the reading the figure supports, and under it the gamma-Poisson share is higher at both levels, which the criterion counts as reproduced. The text does not state the spacing, so the outcome rests on G-b as an assumption. The matrices under both spacings are drawn above.

Reported, not judged: the expected share of cells active at 50 m is 0.681 for the gamma-Poisson and 0.97 for the fitted equal rate; the mean exclusive-OR proportion over pairs both larger than 10 m is 0.264 against 0.348 (G-a) and 0.247 against 0.274 (G-b), lower for the gamma-Poisson under both; with twice the fitted rate it is 0.133 and 0.084, and 0.035 and 0.028 between environments over 20 m, near zero as the Fig. S18 legend says of its high rate. The criterion itself says that the fitted equal rate does not recruit all cells by 50 m, so that comparison does not test the paper's statement (verifier round 2); this is asked of a reader.

figs5-silent-cells-low-rate¶

Cells without fields had very low firing rates in the environment (0.006 plus or minus 0.01 Hz), lower than cells with fields, and the number of fields and the run firing rate of a cell are tightly correlated.

In [41]:
RATES = {Z: np.array([rich.run_rate(a, k, novel_only=(Z == "Z-a")) for a in animals for k in range(len(a["cells"]))]) for Z in ("Z-a", "Z-b")}
# Variant, not a reading of the criterion: all RUN1 track time with no speed threshold (verifier round 1).
RATES["all RUN1, no speed threshold"] = np.array([rich.run_rate(a, k, novel_only=False, speed=False) for a in animals for k in range(len(a["cells"]))])
for k in MAIN + ["F-b"]:
    x = COUNTS[k]
    for Z in RATES:
        rt = RATES[Z]
        sil, fld = rt[x == 0], rt[x > 0]
        mw = stats.mannwhitneyu(sil, fld, alternative="less")
        sp = stats.spearmanr(rt, x)
        print(f"{k} {Z}: cells without fields {len(sil)}, rate {sil.mean():.4f} +/- {sil.std(ddof=1):.4f} Hz "
              f"(expected 0.006 +/- 0.01); with fields median {np.median(fld):.3f} Hz; Mann-Whitney one-sided p {mw.pvalue:.2g}; "
              f"Spearman rate~fields {sp[0]:.3f} p {sp[1]:.2g}")
        if k == "F-a/P-a" and Z == "Z-a":
            print("     silent-cell rates, sorted (Hz):", np.round(np.sort(sil), 4).tolist())
F-a/P-a Z-a: cells without fields 91, rate 0.0141 +/- 0.0277 Hz (expected 0.006 +/- 0.01); with fields median 0.278 Hz; Mann-Whitney one-sided p 8.7e-38; Spearman rate~fields 0.927 p 1.1e-108
     silent-cell rates, sorted (Hz): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0006, 0.0008, 0.0009, 0.001, 0.001, 0.001, 0.001, 0.0015, 0.0015, 0.0018, 0.0018, 0.0019, 0.0019, 0.0019, 0.0019, 0.0019, 0.0019, 0.0021, 0.0021, 0.0023, 0.0028, 0.0028, 0.0029, 0.0029, 0.0031, 0.0031, 0.0037, 0.0038, 0.0038, 0.0038, 0.0039, 0.0039, 0.0039, 0.0041, 0.0042, 0.0042, 0.0046, 0.0047, 0.0052, 0.0052, 0.0062, 0.0067, 0.0069, 0.0069, 0.0074, 0.0087, 0.0087, 0.0088, 0.0104, 0.0125, 0.0144, 0.0145, 0.0146, 0.0163, 0.0187, 0.0187, 0.0203, 0.0246, 0.0252, 0.028, 0.0301, 0.0337, 0.0346, 0.0353, 0.0401, 0.0404, 0.0413, 0.0525, 0.0586, 0.0592, 0.0606, 0.1096, 0.1115, 0.1859]
F-a/P-a Z-b: cells without fields 91, rate 0.0190 +/- 0.0384 Hz (expected 0.006 +/- 0.01); with fields median 0.291 Hz; Mann-Whitney one-sided p 2.7e-36; Spearman rate~fields 0.907 p 4.8e-96
F-a/P-a all RUN1, no speed threshold: cells without fields 91, rate 0.0210 +/- 0.0439 Hz (expected 0.006 +/- 0.01); with fields median 0.255 Hz; Mann-Whitney one-sided p 1.6e-35; Spearman rate~fields 0.888 p 1.1e-86
F-a/P-b Z-a: cells without fields 94, rate 0.0151 +/- 0.0279 Hz (expected 0.006 +/- 0.01); with fields median 0.285 Hz; Mann-Whitney one-sided p 2.3e-38; Spearman rate~fields 0.919 p 2.9e-103
F-a/P-b Z-b: cells without fields 94, rate 0.0259 +/- 0.0664 Hz (expected 0.006 +/- 0.01); with fields median 0.292 Hz; Mann-Whitney one-sided p 1.9e-35; Spearman rate~fields 0.889 p 2.4e-87
F-a/P-b all RUN1, no speed threshold: cells without fields 94, rate 0.0267 +/- 0.0604 Hz (expected 0.006 +/- 0.01); with fields median 0.258 Hz; Mann-Whitney one-sided p 1e-34; Spearman rate~fields 0.873 p 2.5e-80
F-b Z-a: cells without fields 88, rate 0.0105 +/- 0.0176 Hz (expected 0.006 +/- 0.01); with fields median 0.275 Hz; Mann-Whitney one-sided p 3.6e-38; Spearman rate~fields 0.937 p 1e-116
F-b Z-b: cells without fields 88, rate 0.0159 +/- 0.0342 Hz (expected 0.006 +/- 0.01); with fields median 0.287 Hz; Mann-Whitney one-sided p 1.9e-36; Spearman rate~fields 0.916 p 9e-102
F-b all RUN1, no speed threshold: cells without fields 88, rate 0.0172 +/- 0.0366 Hz (expected 0.006 +/- 0.01); with fields median 0.251 Hz; Mann-Whitney one-sided p 6.2e-36; Spearman rate~fields 0.899 p 8e-92

Result: partially reproduced. Cells without fields fire less than cells with fields (one-sided Mann-Whitney p below 1e-34 under every reading) and rate and field number are tightly correlated (Spearman 0.889 to 0.927), but the silent cells' rate, 0.0141 to 0.0259 Hz with SD 0.028 to 0.066 Hz, is outside 0.006 +/- 0.0006 and 0.01 +/- 0.001 under every reading. Counting all RUN1 track time with no speed threshold (a variant) gives 0.0210 (P-a) and 0.0267 Hz (P-b), so that denominator does not give the paper's value either. The data set's fields give 0.0105 +/- 0.0176 Hz (Z-a). The criterion names no outcome for this case; the comparison and the correlation hold and the values do not.

figs8-silent-cells-form-fields¶

Some cells that remained silent on the 48 m track formed clear place fields in a second novel environment, the open field.

Open-field fields are counted under O-a (speed above 5 cm/s) and O-b (no speed threshold); dataset is the data set's RUN3 count (numField, last column).

In [42]:
OF = {O: np.array([rich.open_field_fields(a, k, O)[0] for a in animals for k in range(len(a["cells"]))]) for O in ("O-a", "O-b")}
OF["dataset"] = np.concatenate([a["numField"][:, 5] for a in animals]).astype(int)
for O in OF:
    print(f"open field {O}: fields {OF[O].sum()}, cells with a field {(OF[O] > 0).sum()}")
for k in MAIN + ["F-b"]:
    silent = COUNTS[k] == 0
    for O in ("O-a", "O-b", "dataset"):
        n = int(np.sum(silent & (OF[O] > 0)))
        print(f"{k} with {O}: RUN1-silent cells {silent.sum()}, of which with an open-field field {n} "
              f"({100 * n / silent.sum():.1f}%); per animal {[int(np.sum(silent & (OF[O] > 0) & (cells.ai.values == ai))) for ai in range(5)]}")
open field O-a: fields 74, cells with a field 61
open field O-b: fields 77, cells with a field 62
open field dataset: fields 59, cells with a field 53
F-a/P-a with O-a: RUN1-silent cells 91, of which with an open-field field 12 (13.2%); per animal [5, 3, 1, 2, 1]
F-a/P-a with O-b: RUN1-silent cells 91, of which with an open-field field 11 (12.1%); per animal [4, 3, 1, 2, 1]
F-a/P-a with dataset: RUN1-silent cells 91, of which with an open-field field 10 (11.0%); per animal [4, 3, 1, 1, 1]
F-a/P-b with O-a: RUN1-silent cells 94, of which with an open-field field 13 (13.8%); per animal [5, 3, 2, 2, 1]
F-a/P-b with O-b: RUN1-silent cells 94, of which with an open-field field 13 (13.8%); per animal [4, 3, 2, 3, 1]
F-a/P-b with dataset: RUN1-silent cells 94, of which with an open-field field 11 (11.7%); per animal [4, 3, 2, 1, 1]
F-b with O-a: RUN1-silent cells 88, of which with an open-field field 12 (13.6%); per animal [5, 3, 1, 2, 1]
F-b with O-b: RUN1-silent cells 88, of which with an open-field field 11 (12.5%); per animal [4, 3, 1, 2, 1]
F-b with dataset: RUN1-silent cells 88, of which with an open-field field 10 (11.4%); per animal [4, 3, 1, 1, 1]

Result: reproduced. Of the 91 (P-a) and 94 (P-b) cells without a RUN1 field, 10 to 13 have an open-field field under every combination of readings (12 under P-a and O-a), at least one in each animal. The data set's own RUN3 counts give 10 and 11, so the result does not rest on the open-field scale (see the data check).

figs17-propensity-across-environments¶

Field propensities are correlated across environments but not as strongly as within one environment; the number of fields per cell in a window of the track correlates with the rest of the track at Spearman rho about 0.41, the open field with the long track at about 0.22, against about 0 for the shuffle.

In [43]:
rng_s17 = np.random.default_rng(17)

def s17(f, of_counts, J, n=2000):
    loc = np.clip(f.loc_m.values, 0, 48)
    order = np.argsort(loc)
    loc = loc[order]
    key = {kk: i for i, kk in enumerate(zip(cells.ai, cells.cell))}
    cid = np.array([key[(a_, c_)] for a_, c_ in zip(f.ai.values[order], f.cell.values[order])])
    total = np.bincount(cid, minlength=len(cells))
    nwin = int(of_counts.sum())
    within, between, shuffle = [], [], []
    for _ in range(n):
        if J == "J-a":
            u = rng_s17.uniform(0, 48)
            i0 = int(np.searchsorted(loc, u))
            idx = (i0 + np.arange(nwin)) % len(loc)
        else:
            u = rng_s17.uniform(0, loc[len(loc) - nwin])
            i0 = int(np.searchsorted(loc, u))
            idx = i0 + np.arange(nwin)
        inside = np.bincount(cid[idx], minlength=len(cells))
        outside = total - inside
        within.append(stats.spearmanr(inside, outside)[0])
        between.append(stats.spearmanr(of_counts, outside)[0])
        shuffle.append(stats.spearmanr(rng_s17.permutation(of_counts), outside)[0])
    q = lambda v: (np.median(v), *np.percentile(v, [2.5, 97.5]))
    return q(within), q(between), q(shuffle)

S17 = []
for k in MAIN + ["F-b"]:
    for O in (("O-a", "O-b") if "F-a" in k else ("dataset",)):
        for J in ("J-a", "J-b"):
            w, b, s = s17(FIELDS[k], OF[O], J)
            S17.append(dict(reading=k, open_field=O, J=J, window_fields=int(OF[O].sum()),
                            within=w[0], within_lo=w[1], within_hi=w[2], between=b[0], between_lo=b[1], between_hi=b[2],
                            shuffle=s[0], shuffle_hi=s[2]))
s17t = pd.DataFrame(S17)
s17t["within_ok"] = (s17t.within - 0.41).abs() <= 0.075
s17t["between_ok"] = (s17t.between - 0.22).abs() <= 0.015
s17t["order_ok"] = (s17t.between < s17t.within) & (s17t.between > s17t.shuffle_hi)
print(s17t.round(3).to_string(index=False))
reading open_field   J  window_fields  within  within_lo  within_hi  between  between_lo  between_hi  shuffle  shuffle_hi  within_ok  between_ok  order_ok
F-a/P-a        O-a J-a             74   0.466      0.389      0.531    0.234       0.204       0.250    0.003       0.126       True        True      True
F-a/P-a        O-a J-b             74   0.469      0.390      0.531    0.234       0.204       0.250    0.004       0.124       True        True      True
F-a/P-a        O-b J-a             77   0.467      0.395      0.539    0.247       0.209       0.264    0.002       0.123       True       False      True
F-a/P-a        O-b J-b             77   0.472      0.398      0.539    0.247       0.209       0.264   -0.001       0.118       True       False      True
F-a/P-b        O-a J-a             74   0.460      0.372      0.535    0.231       0.213       0.250   -0.000       0.129       True        True      True
F-a/P-b        O-a J-b             74   0.463      0.371      0.536    0.232       0.211       0.251   -0.002       0.118       True        True      True
F-a/P-b        O-b J-a             77   0.466      0.375      0.543    0.232       0.208       0.250    0.002       0.121       True        True      True
F-a/P-b        O-b J-b             77   0.467      0.375      0.539    0.232       0.207       0.250   -0.002       0.127       True        True      True
    F-b    dataset J-a             59   0.414      0.339      0.490    0.225       0.198       0.239    0.000       0.120       True        True      True
    F-b    dataset J-b             59   0.416      0.339      0.490    0.225       0.199       0.239   -0.001       0.122       True        True      True

Result: reproduced. Under P-a and O-a the within-track median is 0.466 (J-a) and 0.468 (J-b), within 0.41 +/- 0.075, and the between-environment median 0.235 and 0.234, at the upper edge of 0.22 +/- 0.015, below the within value and above the shuffle's 95% bound (0.126 and 0.124). Under P-b every reading holds (between 0.231 to 0.232). Under P-a with O-b the between median, 0.247, is outside tolerance.

Summary¶

Claim Outcome
cell-counts reproduced
figs3-cluster-quality blocked, data missing
fig1-recruitment-by-section reproduced
fig2-individual-poisson reproduced
fig2bc-population-bias reproduced
figs6-few-field-cells-uniform reproduced (assumption P-a)
fig3b-overdispersion reproduced
figs7a-mean-fields-per-animal reproduced
fig3b-negbin-fit reproduced
fig3c-recruitment-fraction reproduced
fig3c-lomax-recruitment partially reproduced (assumption P-a)
fig3c-extrapolation-500m reproduced
fig3d-uniform-density reproduced
figs10-no-track-or-speed-influence not reproduced
figs11-propensity-stationary reproduced
figs11-no-boundary-remapping not reproduced (assumption P-a)
figs12-pairs-uncorrelated not reproduced
fig3e-memoryless-recruitment reproduced
figs14-field-properties not reproduced
figs15-higher-threshold partially reproduced
figs16-anatomy reproduced
fig4a-pre-sleep-rate reproduced
fig4b-single-field-proportion reproduced
fig4c-active-subsets reproduced (assumption G-b)
figs5-silent-cells-low-rate partially reproduced
figs8-silent-cells-form-fields reproduced
figs17-propensity-across-environments reproduced

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. Fields are recomputed from the spikes and positions by the Methods; the paper's own detection code is not public. The recomputed fields number 852 (P-a) and 793 (P-b), against the data set's 887, and overlap 842 and 787 of them; the data set's fields that P-a misses fail its pass rule (29) or its width rule (16). The definition of a pass is open; P-a, which recovers more of the data set's fields and all five of its per-animal means, is the reading adopted where the readings disagree (three claims, marked). Under P-b figs6 would be partially reproduced and fig3c-lomax-recruitment and figs11-no-boundary-remapping reproduced. Under P-a a field reaching the end of the positions visited in its section counts its passes up to 20 cm from that end, a standard choice; the first version of this notebook dropped such fields. The end allowance was varied from none to 30 cm: it decides whether fig3d-uniform-density is within tolerance (from 10 cm) and whether fig3c-lomax-recruitment is (only at 10 cm), and leaves figs6-few-field-cells-uniform, figs7a-mean-fields-per-animal (from 0 cm) and figs11-no-boundary-remapping as they are. For fig4c-active-subsets the spacing of the 300 simulated environment sizes is open in the text; Fig. S18 draws the sizes on linear axes from 0 to 50 m, so linear spacing is assumed, under which the claim is reproduced (agreed in the third verification round); under logarithmic spacing it would not be. The track's corners and heading for Fig. S10 are reconstructed from the animal's room position, as the scale model is not in the data set; the reconstruction has a corner of 45 degrees or more about every 1.2 to 1.55 m, so the distance panel has little power with 1 m bins under Y-a; with the 15 cm bins that Fig. S10 shows it passes. The failure of the angle panel holds with the figure's 30 degree bins but not with several other widths and offsets. The in-field rate is the criterion's mean of the smoothed map; on the data set's own field extents it is about 0.5 Hz below the data set's rate, which matches spikes over occupancy in the field more closely. The PRE slow-wave sleep periods are the data set's.

What was found about the data set. It holds the paper's 253 cells with exactly the per-animal counts, and the paper's own fields, whose counts give the per-animal means of Fig. S7A and the negative binomial fit (r 0.565, p 0.139). The L-ratio and isolation distance fields are empty in the units' cluster info and in each epoch's own, and no unclustered spikes or waveforms are included, so Fig. S3 cannot be tested. The readme gives no units: positions are in inches, the open field in pixels with a per-animal scale, speed in inches per microsecond, and the data set's maps and fields use 1 inch bins where the Methods say 1 cm. The direction code of the fields (1 inbound, 2 outbound) is not described. The region of every unit of one animal is N/A. The section lengths (3.7, 6.1, 11.5 and 26.9 m) differ from the Methods' 3, 7, 12 and 26 m, and the open field spans about 100 to 119 by 72 to 97 cm against the stated ~40 x 100 cm.

In [44]:
print(f"notebook ran in {(time.time() - started) / 60:.1f} min; peak memory "
      f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
notebook ran in 8.4 min; peak memory 1.06 GB