The findings of tingley-2018-01, checked on version 0.261109.2219¶

This notebook belongs to the reconciliation of attempt tingley-2018-02 with the attempt before it, tingley-2018-01 (docs/protocol.md, "Repeat attempts"). tingley-2018-01 was made on DANDI:000213 version 0.250624.0438 and recorded 16 findings. Each section below opens with one of them, as the earlier record states it, and checks it on version 0.261109.2219, the version tingley-2018-02 used. Every file is streamed from the archive; only metadata, positions, trial tables and spike times are read, never the LFP or raw data. Sections 12 and 15 read the paper's code from GitHub at the commits the earlier attempt read.

In [1]:
import json
import re
import time
from concurrent.futures import ThreadPoolExecutor

import h5py
import numpy as np
import pandas as pd
import requests

import tingley as tg

pd.set_option("display.width", 220)
pd.set_option("display.max_rows", 200)
pd.set_option("display.max_colwidth", 70)
print("DANDI:%s version %s" % (tg.DANDISET, tg.VERSION))
assert tg.DANDISET == "000213" and tg.VERSION == "0.261109.2219"
DANDI:000213 version 0.261109.2219

Survey of the 67 files¶

One pass over every file collects what the sections below use. Two alignment checks are made per file. (1) As in tingley-2018-01: the mean running speed inside the trial windows, with the windows shifted by -3 to 3 s; trials are runs, so speed should peak near a shift of 0. (2) New here, because version 0.261109.2219 holds the lab's linearization: the median distance between the head position at each linearized sample's time (shifted by -2 to 2 s) and the template point the sample is assigned to; it should be smallest near a shift of 0. Speeds are in position units per second, and distances in position units.

In [2]:
SPEED_SHIFTS = (-3.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0)
LIN_SHIFTS = tuple(np.round(np.arange(-2.0, 2.01, 0.25), 2))


def _s(x):
    return x.decode() if isinstance(x, bytes) else str(x)


def survey(asset):
    f = tg.open_asset(asset)
    p = asset["path"]
    r = {"subject": p.split("/")[0][4:], "session": p.split("_ses-")[1].split("_behavior")[0]}
    r["session_description"] = _s(f["session_description"][()])
    e = f["general/extracellular_ephys/electrodes"]
    ecols = [_s(c) for c in e.attrs["colnames"]]
    reg = tg._str(e["region"][:])
    r["electrode_columns"] = ecols
    r["electrode_region"] = dict(zip(*np.unique(reg, return_counts=True)))
    r["electrode_location"] = dict(zip(*np.unique(tg._str(e["location"][:]), return_counts=True)))
    r["region_description"] = _s(e["region"].attrs.get("description", ""))
    for k in ("ca1", "ca3"):
        flag = e[k + "_channel"][:].astype(bool)
        r["n_%s_channel" % k] = int(flag.sum())
        r["%s_channel_region" % k] = sorted(set(reg[flag]))
    # units
    r["has_units"] = "units" in f
    r["unit_region"], r["units_columns"], r["n_units"], r["units_unsorted"] = {}, [], 0, 0
    if r["has_units"]:
        u = f["units"]
        r["unit_region"] = dict(zip(*np.unique(tg._str(u["region"][:]), return_counts=True)))
        r["unit_region_description"] = _s(u["region"].attrs.get("description", ""))
        r["units_columns"] = [_s(c) for c in u.attrs["colnames"]]
        st, idx = u["spike_times"][:], u["spike_times_index"][:]
        b = np.r_[0, idx]
        r["n_units"] = len(idx)
        r["units_unsorted"] = int(sum(np.any(np.diff(st[b[i]:b[i + 1]]) < 0) for i in range(len(idx))))
    # trials and trial conditions
    t = f["intervals/trials"]
    cols = [_s(c) for c in t.attrs["colnames"]]
    r["trial_columns"] = cols
    r["n_trials"] = len(t["start_time"])
    for k in ("trial_type", "direction", "condition_type"):
        r[k] = sorted(set(tg._str(t[k][:]))) if k in cols else None
    starts, stops = t["start_time"][:], t["stop_time"][:]
    beh = f["processing/behavior"]
    r["behavior_objects"] = sorted(beh.keys())
    # position
    hp = beh["position/head_position"]
    r["position_description"] = _s(hp.attrs.get("description", ""))
    d = hp["data"]
    r["position_unit"] = _s(d.attrs["unit"])
    xyz = d[:]
    r["position_columns"] = xyz.shape[1]
    r["z_equals_y"] = bool(np.allclose(xyz[:, 1], xyz[:, 2], equal_nan=True)) if xyz.shape[1] > 2 else None
    good = xyz[~np.isnan(xyz[:, :2]).any(axis=1), :2]
    r["xy_extent"] = float(np.max(np.percentile(good, 99, axis=0) - np.percentile(good, 1, axis=0)))
    if "timestamps" in hp:
        ts = hp["timestamps"][:]
        r["position_time"] = "timestamps"
    else:
        rate = float(hp["starting_time"].attrs["rate"])
        ts = float(hp["starting_time"][()]) + np.arange(len(xyz)) / rate
        r["position_time"] = "rate %g Hz" % rate
    r["position_nonincreasing_steps"] = int((np.diff(ts) <= 0).sum())
    # (1) speed in the trial windows, shifted (as tingley-2018-01)
    ok = ~np.isnan(xyz[:, :2]).any(axis=1) & np.r_[True, np.diff(ts) > 0]
    tk, pk = ts[ok], xyz[ok, :2]
    sp = np.r_[np.nan, np.hypot(*np.diff(pk, axis=0).T) / np.diff(tk)]
    sp[sp > np.nanpercentile(sp, 99.5)] = np.nan   # tracking jumps, as tingley-2018-01
    r["speed_shift"] = {}
    for sh in SPEED_SHIFTS:
        m = np.zeros(len(tk), bool)
        for a, b_ in zip(starts + sh, stops + sh):
            m[np.searchsorted(tk, a):np.searchsorted(tk, b_)] = True
        r["speed_shift"][sh] = float(np.nanmean(sp[m])) if m.any() else np.nan
    # (2) head position against the template point of each linearized sample, shifted
    tc = beh["trial_conditions"]
    tmpl = np.stack([tc["template_x"][:], tc["template_y"][:]], -1)
    conds = list(tc["condition"][:])
    r["template_length_median"] = float(np.nanmedian(
        [np.nansum(np.linalg.norm(np.diff(x, axis=0), axis=1)) for x in tmpl]))
    lp, lt = tg._ragged(t, "linearized_position"), tg._ragged(t, "linearized_position_timestamps")
    cond = t["condition"][:]
    r["lin_distance"] = {}
    for sh in LIN_SHIFTS:
        dist = []
        for k in range(len(lp)):
            if len(lt[k]):
                i = np.clip(np.searchsorted(ts, lt[k] + sh), 0, len(ts) - 1)
                dist.append(np.nanmedian(np.linalg.norm(xyz[i, :2] - tmpl[conds.index(cond[k])][lp[k] - 1], axis=1)))
        r["lin_distance"][sh] = float(np.nanmedian(dist))
    # units of every behaviour series
    r["behavior_units"] = {}
    def visit(name, obj):
        if isinstance(obj, h5py.Dataset) and name.endswith("data") and "unit" in obj.attrs:
            r["behavior_units"][name] = _s(obj.attrs["unit"])
    beh.visititems(visit)
    lfp = f["processing/ecephys/LFP/lfp/data"]
    r["lfp_shape"], r["lfp_chunks"] = lfp.shape, lfp.chunks
    f.close()
    return r


started = time.time()
assets = tg.list_assets()
with ThreadPoolExecutor(4) as ex:
    S = pd.DataFrame(list(ex.map(survey, assets)))
S["name"] = S.subject + " " + S.session.str.extract(r"(\d{8})", expand=False)
print("files: %d, read in %.0f s" % (len(S), time.time() - started))
print("assets that are not NWB files:", [a["path"] for a in assets if not a["path"].endswith(".nwb")])
print("files per subject:", S.subject.value_counts().sort_index().to_dict())
print("units per region label:", pd.DataFrame(list(S.unit_region)).sum().astype(int).to_dict())
print("files without units:", S[~S.has_units].name.tolist())
files: 67, read in 192 s
assets that are not NWB files: []
files per subject: {'DT2': 11, 'DT5': 16, 'DT7': 9, 'DT8': 17, 'DT9': 14}
units per region label: {np.str_('ls'): 1696, np.str_('ppc'): 60, np.str_('hpc'): 2636, np.str_('ca3'): 624, np.str_('acg'): 31, np.str_('cc'): 6, np.str_('ms'): 25, np.str_('sFi'): 54}
files without units: ['DT7 20170324']

1. Processed behaviour¶

The paper's processed behaviour is not in the dandiset; the linearized position, the trial conditions used for every rate and phase map, and the CA1 pyramidal layer channel used as the theta reference in each session must be rebuilt, and several outcomes depend on how.

In [3]:
lin = S.trial_columns.apply(lambda c: "linearized_position" in c and "condition" in c)
tcond = S.behavior_objects.apply(lambda b: "trial_conditions" in b)
print("files whose trials hold condition and linearized_position:", int(lin.sum()), "of", len(S))
print("files with processing/behavior/trial_conditions (templates):", int(tcond.sum()), "of", len(S))
print("files with a flagged CA1 channel (electrodes.ca1_channel):", int((S.n_ca1_channel > 0).sum()), "of", len(S))
print("files without one:", S[S.n_ca1_channel == 0].name.tolist())
files whose trials hold condition and linearized_position: 67 of 67
files with processing/behavior/trial_conditions (templates): 67 of 67
files with a flagged CA1 channel (electrodes.ca1_channel): 61 of 67
files without one: ['DT7 20170317', 'DT9 20170518', 'DT9 20170519', 'DT9 20170521', 'DT9 20170522', 'DT9 20170525']

Result: partly fixed. Every file now holds the lab's linearization (trials.linearized_position and condition) and the condition templates (trial_conditions), 67 of 67, and 61 files flag a CA1 channel. Six files flag none: DT7 20170317 and the five DT9 sessions from 20170518 to 20170525.

2. Unit sites¶

Units have no waveform, recording site or channel of largest amplitude, so the within-session depth analyses of Figure 4 (unit site on the shank) cannot be repeated.

In [4]:
for col in ("max_waveform_channel", "raw_waveform", "shank"):
    has = S.units_columns.apply(lambda c: col in c)
    print("units.%s in %d of %d files with units; missing in %s" % (col, int((has & S.has_units).sum()), int(S.has_units.sum()),
          S[~has & S.has_units].name.tolist()))
print("electrodes.shank_electrode_number in", int(S.electrode_columns.apply(lambda c: "shank_electrode_number" in c).sum()), "files")
units.max_waveform_channel in 65 of 66 files with units; missing in ['DT7 20170317']
units.raw_waveform in 65 of 66 files with units; missing in ['DT7 20170317']
units.shank in 66 of 66 files with units; missing in []
electrodes.shank_electrode_number in 67 files

Result: partly fixed. Units now carry their shank, the channel of largest waveform and the mean waveform in 65 of the 66 files with units; DT7 20170317 lacks max_waveform_channel and raw_waveform. Electrodes give each site's position in its group's channel list (shank_electrode_number).

3. Depths in the session names and the hpc label¶

The two depths in each session name (for example 1944um and 2232um) are not described; which is the LS probe and what the zero is cannot be told from the metadata. The hpc unit label is not defined as CA1.

In [5]:
print("electrodes.region description:", sorted(set(S.region_description)))
print("units.region description:", sorted(set(S.unit_region_description.dropna()))[0][:250])
unstated = S.session_description.str.contains("which probe each depth belongs to and what it is measured from are not stored")
print("session descriptions that say which probe each depth belongs to is not stored:", int(unstated.sum()), "of", len(S))
print("example session description:", S.session_description.iloc[20])
electrodes.region description: ["the lab's region label of the channel (sessionInfo.region); 'hpc' is the probe aimed at dorsal CA1, not resolved to a subfield"]
units.region description: the lab's region label of the unit (spikes.cellinfo region, or the spike group's sessionInfo.region label for sessions without a cellinfo file): ls (lateral septum), hpc (the probe aimed at dorsal CA1, not resolved to a subfield), ca1, ca3, and the s
session descriptions that say which probe each depth belongs to is not stored: 67 of 67
example session description: Rat DT5, recorded with two silicon probes in the right hemisphere, one in the lateral septal nucleus ('ls') and one in the hippocampal formation ('hpc'), in the home cage before and after running on a maze. Task: central alternation (117 trials). The session name carries the depths 1944 um and 2232 um (sessionInfo.depth is 1944, the first); which probe each depth belongs to and what it is measured from are not stored in the source. The time of day the session started is not recorded; the start time is midnight of its date.

Result: partly fixed. The region descriptions now define hpc as the probe aimed at dorsal CA1, not resolved to a subfield. The two depths in the session names are still undescribed: all 67 session descriptions say that which probe each depth belongs to, and what it is measured from, are not stored.

4. Position unit of eight DT8 files¶

Eight DT8 files state position in mm but hold values spanning about 1.1 to 1.3, which are metres.

In [6]:
S["stated_in_description"] = S.position_description.str.extract(r"stored in the lab's unit, (\w+)", expand=False)
cols = ["name", "position_unit", "stated_in_description", "xy_extent"]
print(S[S.subject == "DT8"][cols].round(3).to_string(index=False))
metres = S[(S.position_unit != "pixels") & (S.xy_extent < 10)]
millim = S[(S.position_unit != "pixels") & (S.xy_extent > 100)]
print("\nfiles whose positions span under 10 units (metres):", len(metres), "| stated units:", metres.position_unit.value_counts().to_dict())
print("DT8 files among them:", metres[metres.subject == "DT8"].name.tolist())
print("files whose positions span over 100 units (millimetres):", len(millim), "| stated units:",
      millim.position_unit.value_counts().to_dict(), "| per subject:", millim.subject.value_counts().sort_index().to_dict())
        name position_unit stated_in_description  xy_extent
DT8 20170125        meters                     m      1.141
DT8 20170128        meters                     m      1.262
DT8 20170201        meters                     m      1.298
DT8 20170202        meters                     m      1.275
DT8 20170206        meters                    mm   1181.799
DT8 20170207        meters                    mm   1196.792
DT8 20170211        meters                     m      1.310
DT8 20170214        meters                    mm   1036.900
DT8 20170215        meters                    mm   1178.784
DT8 20170216        meters                    mm   1179.190
DT8 20170217        meters                     m      1.220
DT8 20170218        meters                     m      1.149
DT8 20170221        meters                    mm   1142.276
DT8 20170224        meters                    mm   1231.675
DT8 20170305        meters                    mm   1182.315
DT8 20170306        meters                     m      1.176
DT8 20170308        meters                    mm   1240.093

files whose positions span under 10 units (metres): 25 | stated units: {'meters': 25}
DT8 files among them: ['DT8 20170125', 'DT8 20170128', 'DT8 20170201', 'DT8 20170202', 'DT8 20170211', 'DT8 20170217', 'DT8 20170218', 'DT8 20170306']
files whose positions span over 100 units (millimetres): 31 | stated units: {'meters': 31} | per subject: {'DT7': 8, 'DT8': 9, 'DT9': 14}

Result: these eight files are fixed, but the unit is wrong elsewhere. The eight DT8 files whose positions span 1.141 to 1.310 now state meters, and their descriptions say m. All 31 files whose positions span over 100 units (DT7 8, DT8 9, DT9 14) also state meters, while the DT8 descriptions printed above say mm, so these hold millimetres labelled as metres.

5. Third position column¶

In all 67 files the third column (z) of position is a copy of the second (y).

In [7]:
print("position columns per file:", S.position_columns.value_counts().to_dict())
three = S[S.position_columns == 3]
print("files with three columns whose z equals y:", int(three.z_equals_y.sum()), "of", len(three))
print("DT2 files and their columns:", S[S.subject == "DT2"].position_columns.value_counts().to_dict())
position columns per file: {3: 56, 2: 11}
files with three columns whose z equals y: 0 of 56
DT2 files and their columns: {2: 11}

Result: fixed. None of the 56 files with three position columns has z equal to y; the 11 DT2 files now store only x and y.

6. DT2 position timestamps¶

In eight of the eleven DT2 files the position timestamps repeat or go back; the time per sample (33.3 ms) can only be taken from the session span.

In [8]:
dt2 = S[S.subject == "DT2"]
print(dt2[["name", "position_time", "position_nonincreasing_steps"]].to_string(index=False))
m = re.search(r"The lab's timestamps.*?frame rate\)\.", dt2.position_description.iloc[0])
print("\nDT2 head_position description:", m.group(0) if m else dt2.position_description.iloc[0][:400])
        name position_time  position_nonincreasing_steps
DT2 20160217    rate 30 Hz                             0
DT2 20160219    rate 30 Hz                             0
DT2 20160220    rate 30 Hz                             0
DT2 20160221    rate 30 Hz                             0
DT2 20160222    rate 30 Hz                             0
DT2 20160223    rate 30 Hz                             0
DT2 20160225    rate 30 Hz                             0
DT2 20160226    rate 30 Hz                             0
DT2 20160227    rate 30 Hz                             0
DT2 20160228    rate 30 Hz                             0
DT2 20160304    rate 30 Hz                             0

DT2 head_position description: (x, y) position of the head tracked by a Basler camera above the maze (30 Hz) tracking two head-mounted LEDs (one blue, one red) (behavior.position of the lab's behavior.mat), in pixels: the source has no scale to metres. Values are the lab's, including NaN for untracked frames and large outliers in some sessions. The lab's timestamps (behavior.timestamps) are regular at 30 Hz from 0 s (within 1 u

Result: fixed. The DT2 positions are now stored at a regular 30 Hz from 0 s, with no repeated or decreasing times, and the description explains how the lab's rounded timestamps were rebuilt.

7. Unsorted spike times¶

11 units in six files hold spike times that are not in increasing order.

In [9]:
print("units with spike times not in increasing order:", int(S.units_unsorted.sum()), "in", int(S.has_units.sum()), "files with units")
units with spike times not in increasing order: 0 in 66 files with units

Result: fixed. No unit in the 66 files with units has spike times out of order.

8. DT2 labels and scale, DT7 units¶

Every DT2 electrode, and those of two DT9 files, is labelled unknown; DT2 positions are in pixels with no scale; DT7 20170317 has 43 units with no region or group; DT7 20170324 has no units.

In [10]:
print("electrodes labelled unknown (location or region), files:",
      int(sum(("unknown" in a) or ("unknown" in b) for a, b in zip(S.electrode_location, S.electrode_region))))
print("DT2 electrode regions:", S[S.subject == "DT2"].electrode_region.apply(lambda d: tuple(sorted(d))).value_counts().to_dict())
print("DT9 electrode regions:", S[S.subject == "DT9"].electrode_region.apply(lambda d: tuple(sorted(d))).value_counts().to_dict())
dt2 = S[S.subject == "DT2"]
print("DT2 position units:", dt2.position_unit.value_counts().to_dict(),
      "| description says there is no scale:", int(dt2.position_description.str.contains("no scale").sum()), "of", len(dt2))
for d in ("DT7 20170317", "DT7 20170324"):
    row = S[S.name == d].iloc[0]
    print(d, "| has units:", row.has_units, "| unit regions:", row.unit_region)
electrodes labelled unknown (location or region), files: 0
DT2 electrode regions: {(np.str_('hpc'), np.str_('ls')): 11}
DT9 electrode regions: {(np.str_('hpc'), np.str_('ls')): 9, (np.str_('ca3'), np.str_('ls')): 5}
DT2 position units: {'pixels': 11} | description says there is no scale: 11 of 11
DT7 20170317 | has units: True | unit regions: {np.str_('hpc'): np.int64(43)}
DT7 20170324 | has units: False | unit regions: {}

Result: partly fixed. No electrode is labelled unknown: the DT2 and DT9 electrodes carry region labels. The 43 units of DT7 20170317 are now labelled hpc. DT2 positions are still in pixels, and all 11 descriptions say the source has no scale to metres. DT7 20170324 still has no units.

9. Trial type and direction¶

Trials on the linear track, and in two DT8 alternation files (20170207 and 20170224), carry no type or direction.

In [11]:
cols = ["name", "trial_type", "direction", "condition_type", "n_trials"]
lin_track = S[S.condition_type.apply(lambda c: c is not None and "linear" in c)]
print("files with linear-track conditions:")
print(lin_track[cols].to_string(index=False))
print("\nDT8 20170207 and 20170224:")
print(S[S.name.isin(["DT8 20170207", "DT8 20170224"])][cols].to_string(index=False))
print("\nfiles without trials.trial_type:", S[S.trial_type.isna()].name.tolist())
files with linear-track conditions:
        name                               trial_type                      direction  condition_type  n_trials
DT5 20161021                                     None                           None        [linear]        54
DT5 20161026                                     None                           None        [linear]        57
DT7 20170401                                     None                           None        [linear]        81
DT7 20170412 [central alternation, wheel alternation] [clockwise, counter-clockwise] [linear, wheel]        76
DT9 20170502                                     None                           None        [linear]        60
DT9 20170504                                     None                           None        [linear]        56
DT9 20170507                                     None                           None        [linear]        62
DT9 20170521                                     None                           None        [linear]        93
DT9 20170522                                     None                           None        [linear]       105
DT9 20170525                                     None                           None        [linear]        57

DT8 20170207 and 20170224:
        name                               trial_type                      direction condition_type  n_trials
DT8 20170207                    [central alternation] [clockwise, counter-clockwise]      [central]       174
DT8 20170224 [central alternation, wheel alternation] [clockwise, counter-clockwise]      [central]       210

files without trials.trial_type: ['DT5 20161021', 'DT5 20161026', 'DT7 20170317', 'DT7 20170401', 'DT9 20170502', 'DT9 20170504', 'DT9 20170507', 'DT9 20170521', 'DT9 20170522', 'DT9 20170525']

Result: partly fixed. DT8 20170207 and 20170224 now give trial type and direction. The linear-track sessions (DT5 20161021 and 20161026, DT7 20170401, and six DT9 sessions), and DT7 20170317, still have no trial_type or direction column; the linear-track trials carry a condition whose condition_type is linear.

10. Trials against positions¶

In DT9 20170501 the trials do not match the positions (speed inside the trial windows does not change when they are shifted by up to 3 s), and in DT2 20160221 speed peaks with the trials shifted by 1 s, which suggests an offset of up to a second.

In [12]:
sp = pd.DataFrame(list(S.speed_shift), index=S.name)
sp["peak"] = sp.idxmax(axis=1)
print("(1) speed inside the trial windows shifted by each lag (s), position units per s:")
print(sp.loc[["DT9 20170501", "DT2 20160221"]].round(1).to_string())
print("files per peak lag:", sp.peak.value_counts().sort_index().to_dict())
ld = pd.DataFrame(list(S.lin_distance), index=S.name)
best = ld.idxmin(axis=1)
rel = pd.DataFrame({"best_shift": best, "d_at_0": ld[0.0], "d_at_best": ld.min(axis=1),
                    "d_at_0_over_path": ld[0.0] / S.template_length_median.values})
print("\n(2) median distance of the head from the template point of each linearized sample, by shift (s):")
print(ld.loc[["DT9 20170501", "DT2 20160221"], [-2.0, -1.0, -0.5, 0.0, 0.25, 0.5, 0.75, 1.0, 2.0]].round(1).to_string())
print(rel.loc[["DT9 20170501", "DT2 20160221"]].round(3).to_string())
others = rel.drop(["DT9 20170501", "DT2 20160221"])
print("other files: best shift", others.best_shift.value_counts().sort_index().to_dict(),
      "| distance at 0 over the template path length, %.3f to %.3f" % (others.d_at_0_over_path.min(), others.d_at_0_over_path.max()))
(1) speed inside the trial windows shifted by each lag (s), position units per s:
               -3.0   -2.0   -1.0   -0.5    0.0    0.5    1.0    2.0    3.0   peak
name                                                                              
DT9 20170501  321.1  328.5  326.7  321.0  315.0  306.0  296.6  290.6  290.8   -2.0
DT2 20160221  114.3  143.3  178.2  195.1  208.7  208.8  203.1  172.4  140.5    0.5
files per peak lag: {-2.0: 1, 0.0: 62, 0.5: 4}

(2) median distance of the head from the template point of each linearized sample, by shift (s):
              -2.00  -1.00  -0.50   0.00   0.25   0.50   0.75   1.00   2.00
name                                                                       
DT9 20170501  611.9  593.8  593.7  601.5  599.7  608.3  615.0  604.0  614.4
DT2 20160221  283.5  276.3  229.0  151.6  104.4   62.8   45.1   53.9  204.3
              best_shift   d_at_0  d_at_best  d_at_0_over_path
name                                                          
DT9 20170501       -0.75  601.528    585.293             0.224
DT2 20160221        0.75  151.589     45.079             0.149
other files: best shift {0.0: 49, 0.25: 16} | distance at 0 over the template path length, 0.021 to 0.107

Result: still present. In DT9 20170501 speed inside the trial windows does not rise at a shift of 0 (315.0, against 290.6 to 328.5 at the other shifts), and the head is a median 601.5 units from the template point of each linearized sample at a shift of 0, 0.224 of the path length, against 0.021 to 0.107 in the other files, at no shift less than 585.3. In DT2 20160221 the speed check now peaks at 0.5 s (208.8, against 208.7 at 0), but the head matches the linearized position best 0.75 s after the trial times (45.1 pixels, against 151.6 at 0); the other files match best at 0 or 0.25 s.

11. Unit counts¶

The dandiset holds 1,696 LS units and 3,217 hippocampal units (2,593 hpc, 624 ca3) against the paper's 1,647 LS and 2,951 hippocampal units, and 20,979 pairs of active hippocampal and LS units against 11,264 examined; which units the paper left out is not documented.

In [13]:
units = pd.DataFrame(list(S.unit_region)).fillna(0).astype(int)
tot = units.sum()
print("units per label:", tot.to_dict())
print("LS units: %d | hippocampal units (hpc + ca3): %d (hpc %d, ca3 %d) | paper: 1,647 LS, 2,951 hippocampal"
      % (tot["ls"], tot["hpc"] + tot["ca3"], tot["hpc"], tot["ca3"]))
print("hpc units in DT7 20170317:", int(units.loc[S.name == "DT7 20170317", "hpc"].sum()))
units per label: {np.str_('ls'): 1696, np.str_('ppc'): 60, np.str_('hpc'): 2636, np.str_('ca3'): 624, np.str_('acg'): 31, np.str_('cc'): 6, np.str_('ms'): 25, np.str_('sFi'): 54}
LS units: 1696 | hippocampal units (hpc + ca3): 3260 (hpc 2636, ca3 624) | paper: 1,647 LS, 2,951 hippocampal
hpc units in DT7 20170317: 43

Result: still present, with 43 more hpc units. The files hold 1696 LS units and 3260 hippocampal units (2636 hpc, 624 ca3), against the paper's 1,647 and 2,951; the 43 units of DT7 20170317 now count as hpc. Which units the paper left out is still not documented.

12. The paper's code and session files¶

The functions the paper's figure scripts call to bin spike phases (bz_phaseMap2Bins), compute information (olypherInfo) and detect assemblies, and the parameters of its place-field call, are not in the public repositories; the session files they read (behavior.mat, sessionInfo) are not in the dandiset.

In [14]:
REPOS = {"buzsakilab/buzcode": "e615663b2b100782d1f378580f6d7aaa35c12937",
         "DavidTingley/papers": "9f4cd48a44f211956954558b66d776ccbb74d693",
         "DavidTingley/scratch": "2f804532290774f52a442bf0f3ec23dd5398d58d",
         "buzsakilab/buzcode@master": "master"}
WANTED = ("bz_phaseMap2Bins.m", "bz_olypherInfo.m", "olypherInfo.m", "bz_peerPrediction.m", "bz_getPlaceFields1D.m")
for name, ref in REPOS.items():
    repo = name.split("@")[0]
    r = requests.get(f"https://api.github.com/repos/{repo}/git/trees/{ref}?recursive=1", timeout=120)
    if r.status_code != 200:
        print(name, "could not be listed:", r.status_code, r.text[:200])
        continue
    files = [x["path"] for x in r.json()["tree"]]
    found = {w: [p for p in files if p.split("/")[-1] == w] for w in WANTED}
    print(f"{name} at {ref[:7]} ({len(files)} paths):", {w: (v if v else "absent") for w, v in found.items()})
fig4 = requests.get("https://raw.githubusercontent.com/DavidTingley/papers/" + REPOS["DavidTingley/papers"]
                    + "/LS_phasecoding/makeFig4.m", timeout=120).text
print("\nmakeFig4.m:", [l.strip() for l in fig4.splitlines() if "phaseMap2Bins" in l])
fig1 = requests.get("https://raw.githubusercontent.com/DavidTingley/papers/" + REPOS["DavidTingley/papers"]
                    + "/LS_phasecoding/makeFig1.m", timeout=120).text
print("makeFig1.m:", [l.strip() for l in fig1.splitlines() if "olypherInfo" in l and "load" in l])
print("\nobjects in the files named for the lab's session files:",
      "trial_conditions in %d files, linearized_position in %d, ca1_channel (sessionInfo.ca1) in %d"
      % (int(S.behavior_objects.apply(lambda b: "trial_conditions" in b).sum()),
         int(S.trial_columns.apply(lambda c: "linearized_position" in c).sum()),
         int(S.electrode_columns.apply(lambda c: "ca1_channel" in c).sum())))
buzsakilab/buzcode could not be listed: 403 {"message":"API rate limit exceeded for 20.120.183.184. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)","documentation_url":"
DavidTingley/papers could not be listed: 403 {"message":"API rate limit exceeded for 20.120.183.184. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)","documentation_url":"
DavidTingley/scratch could not be listed: 403 {"message":"API rate limit exceeded for 20.120.183.184. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)","documentation_url":"
buzsakilab/buzcode@master could not be listed: 403 {"message":"API rate limit exceeded for 20.120.183.184. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)","documentation_url":"
makeFig4.m: ['[binnedfiringMaps.phaseMaps] = bz_phaseMap2Bins(phaseMaps.phaseMaps,firingMaps.rateMaps,behavior);']
makeFig1.m: ["load([examples{ex,1} '.olypherInfo_w_disc.cellinfo.mat'],'olypherInfo')", "load([sessionInfo.FileName '.olypherInfo_w_disc.cellinfo.mat'],'olypherInfo')"]

objects in the files named for the lab's session files: trial_conditions in 67 files, linearized_position in 67, ca1_channel (sessionInfo.ca1) in 67

Result: still present for bz_phaseMap2Bins. makeFig4.m calls it, and it is in none of the repositories listed above, including buzcode's master. buzcode at e615663 does hold bz_olypherInfo.m and bz_peerPrediction.m, and makeFig1.m loads saved per-session information files (.olypherInfo_w_disc.cellinfo.mat). The contents of the lab's session files that the earlier statement names are now in the NWB files: trial conditions and linearized positions (behavior.mat) and the CA1 channel (sessionInfo.ca1), in all 67 files.

13. Unit of the head-orientation quaternion¶

The head-orientation quaternion in processing/behavior/allocentric_frame_tracking states its unit as meters.

In [15]:
print("behaviour series and their units, files:")
print(S.behavior_units.apply(lambda d: json.dumps(d, sort_keys=True)).value_counts().to_string())
print("files with processing/behavior/allocentric_frame_tracking:", int(S.behavior_objects.apply(lambda b: "allocentric_frame_tracking" in b).sum()))
behaviour series and their units, files:
behavior_units
{"error_per_marker/data": "meters", "head_orientation/data": "dimensionless", "position/head_position/data": "meters"}    56
{"head_direction/head_yaw/data": "radians", "position/head_position/data": "pixels"}                                      11
files with processing/behavior/allocentric_frame_tracking: 0

Result: fixed. The quaternion is now processing/behavior/head_orientation, with unit dimensionless, in the 56 OptiTrack files; no file has allocentric_frame_tracking.

14. CA1 and CA3 labels per session¶

In every session the hippocampal channels and units carry one label, hpc or ca3, so no session has both a CA1 and a CA3 site labelled, where the paper's Figure 6A counts 63 CA1 and 19 CA3 sessions, more than the 67 files, so some of its sessions had both; the paper's per-session CA1 and CA3 channels cannot be recovered.

In [16]:
both_flags = S[(S.n_ca1_channel > 0) & (S.n_ca3_channel > 0)]
print("sessions with a flagged CA1 channel:", int((S.n_ca1_channel > 0).sum()), "| with a flagged CA3 channel:", int((S.n_ca3_channel > 0).sum()),
      "| with both:", len(both_flags), both_flags.subject.value_counts().sort_index().to_dict())
print("region labels of the flagged channels in sessions with both:",
      sorted({(tuple(a), tuple(b)) for a, b in zip(both_flags.ca1_channel_region, both_flags.ca3_channel_region)}))
hl = S.unit_region.apply(lambda d: tuple(sorted(k for k in d if k in ("hpc", "ca1", "ca3"))))
print("hippocampal unit labels per session:", hl.value_counts().to_dict())
print("sessions whose units carry both hpc (or ca1) and ca3:", int(hl.apply(lambda t: "ca3" in t and len(t) > 1).sum()))
sessions with a flagged CA1 channel: 61 | with a flagged CA3 channel: 19 | with both: 14 {'DT5': 12, 'DT7': 2}
region labels of the flagged channels in sessions with both: [((np.str_('ca3'),), (np.str_('ca3'),)), ((np.str_('hpc'),), (np.str_('hpc'),))]
hippocampal unit labels per session: {(np.str_('hpc'),): 37, (): 19, (np.str_('ca3'),): 11}
sessions whose units carry both hpc (or ca1) and ca3: 0

Result: partly fixed. The channels are now flagged per session: 61 sessions have a CA1 channel and 19 a CA3 channel, 14 of them both (DT5 12, DT7 2). The flagged channels still carry one region label per session, and no session has units labelled both hpc and ca3 (37 hpc, 11 ca3, 19 neither), so a unit's subfield still cannot be told.

15. Place-field threshold in the paper's code¶

In scratch_07_25_17_calc_firingMaps.m (DavidTingley/scratch at 2f80453), the place-field file that the figure scripts load is named for a 20% threshold, but the call that fills it passes no threshold, so bz_getPlaceFields1D's default of 1% applies; the Methods state 20%.

In [17]:
SCRATCH = "https://raw.githubusercontent.com/DavidTingley/scratch/2f804532290774f52a442bf0f3ec23dd5398d58d/"
BUZ = "https://raw.githubusercontent.com/buzsakilab/buzcode/e615663b2b100782d1f378580f6d7aaa35c12937/"
calc = requests.get(SCRATCH + "scratch_07_25_17_calc_firingMaps.m", timeout=120).text.splitlines()
for i, l in enumerate(calc, 1):
    if re.search(r"thresh|bz_getPlaceFields1D|pctThresh", l):
        print("scratch_07_25_17_calc_firingMaps.m:%d: %s" % (i, l.strip()))
gpf = requests.get(BUZ + "analysis/placeFields/bz_getPlaceFields1D.m", timeout=120).text.splitlines()
for i, l in enumerate(gpf, 1):
    if "percentThreshold" in l and ("addParameter" in l or "p.Results" in l):
        print("bz_getPlaceFields1D.m:%d: %s" % (i, l.strip()))
scratch_07_25_17_calc_firingMaps.m:24: for thresh = [.01 .05 .1 .2 .4]
scratch_07_25_17_calc_firingMaps.m:26: fields{cond} = bz_getPlaceFields1D(firingMaps.rateMaps{cond},'minPeakRate',2);
scratch_07_25_17_calc_firingMaps.m:28: save([d(ii).name '.placeFields.' num2str(thresh*100,'%0.2i') '_pctThresh.mat'],'fields')
scratch_07_25_17_calc_firingMaps.m:36: for thresh = .15%[.01 .05 .1 .2 .4]
scratch_07_25_17_calc_firingMaps.m:38: fields{cond} = bz_getPlaceFields1D(firingMaps.rateMaps{cond},'minPeakRate',2,'percentThreshold',thresh);
scratch_07_25_17_calc_firingMaps.m:40: save([d(ii).name '.placeFields.' num2str(thresh*100,'%0.2i') '_pctThresh.mat'],'fields')
bz_getPlaceFields1D.m:31: addParameter(p,'percentThreshold',.01,@isnumeric)
bz_getPlaceFields1D.m:40: threshold = p.Results.percentThreshold; % change between peak rate and start/stop of field

Result: still present. The code is read at the commits the paper's analysis used, which have not changed: the loop over thresholds of 1% to 40% calls bz_getPlaceFields1D with no percentThreshold (line 26), so every file it saves, placeFields.20_pctThresh.mat among them, uses the default of 0.01 (bz_getPlaceFields1D.m, line 31). Only the later loop at 15% passes the threshold.

16. LFP chunking¶

42 files chunk the LFP as 500 samples by all channels, so reading one channel of a session means reading the whole LFP; chunks along time per channel would make single-channel access practical.

In [18]:
print("LFP chunk shapes, files:", S.lfp_chunks.astype(str).value_counts().to_dict())
print("LFP channels per file:", S.lfp_shape.apply(lambda s: s[1]).value_counts().sort_index().to_dict())
LFP chunk shapes, files: {'(1048576, 16)': 67}
LFP channels per file: {96: 47, 128: 20}

Result: fixed. All 67 files now chunk the LFP as 1048576 samples by 16 channels, so one channel is read with 16 of the 96 or 128 channels.

Summary¶

Finding of tingley-2018-01 On version 0.261109.2219
1. Processed behaviour missing partly fixed: linearization and conditions in all files; no CA1 channel in 6
2. No unit sites partly fixed: largest-waveform channel in 65 of 66 files with units
3. Depths undescribed, hpc undefined partly fixed: hpc defined; depths still undescribed
4. Eight DT8 files in metres labelled mm fixed for these eight; 31 files in millimetres now labelled meters
5. z copies y fixed
6. DT2 timestamps fixed
7. Unsorted spike times fixed
8. DT2 labels and scale, DT7 units partly fixed: labels given; DT2 still in pixels; DT7 20170324 still without units
9. Trials without type or direction partly fixed: two DT8 files fixed; linear track unchanged
10. Trials against positions still present in DT9 20170501 and DT2 20160221
11. Unit counts against the paper still present
12. Code not public still present for bz_phaseMap2Bins
13. Quaternion in meters fixed
14. One hippocampal label per session partly fixed: CA1 and CA3 channels flagged; units still one label
15. Place-field threshold in the code still present
16. LFP chunking fixed