File size: 15,281 Bytes
055f287 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | """Convert SPE-1 paired patch / Neuropixels recordings to Arrow
For each cell, this writes:
<output_root>/<cell_id>/
train/, test/ (HuggingFace ``DatasetDict`` Arrow shards)
dataset_dict.json
conversion_metadata.json (GT electrode + bad channels + spike counts)
templates.npz (peak-aligned mean template, Zhao et al. 2026)
Usage:
python scripts/convert_to_arrow.py \\
--data-dir <SPE1_RAW>/Recordings \\
--chan-map <SPE1_RAW>/chanMap.mat \\
--summary "<SPE1_RAW>/Data Summary.xlsx" \\
--output . \\
[--cells c14 c26 ...] [--duration 300]
"""
from __future__ import annotations
import argparse
import gc
import json
import os
import sys
import numpy as np
import pandas as pd
import scipy.io
import scipy.signal
import spikeinterface.core as sc
import spikeinterface.extractors as se
import spikeinterface.preprocessing as spre
from datasets import Dataset
ZHAO_CELLS: list[str] = [
"c14",
"c15",
"c16",
"c19",
"c24",
"c26",
"c28",
"c29",
"c37",
"c45",
"c46",
]
NPX_SAMPLE_RATE: float = 30_000.0 # Neuropixels sampling rate
PATCH_SAMPLE_RATE: float = 50_023.0 # Patch amplifier sampling rate (approx.)
SKIP_SECONDS: float = 10.0 # Burn-in to discard
def detect_spikes_from_patch(
patch_sig: np.ndarray,
patch_sample_rate: float = PATCH_SAMPLE_RATE,
) -> np.ndarray:
"""Detect APs via 200 Hz HP + 12·MAD threshold (Garcia, SI blog 2020)."""
sos = scipy.signal.iirfilter(
5,
200.0 / patch_sample_rate * 2,
analog=False,
btype="highpass",
ftype="butter",
output="sos",
)
patch_sig_f = scipy.signal.sosfiltfilt(sos, patch_sig, axis=0)
med = np.median(patch_sig_f)
mad = np.median(np.abs(patch_sig_f - med)) * 1.4826
thresh = med - 12 * mad
refractory = int(patch_sample_rate * 0.001) # 1 ms
idx, _ = scipy.signal.find_peaks(-patch_sig_f, height=-thresh, distance=refractory)
return idx.astype(np.int64)
def extract_peak_aligned_templates(
recording: sc.BaseRecording,
spike_samples: np.ndarray,
ms_before: float = 1.0,
ms_after: float = 2.0,
min_spikes: int = 2,
) -> tuple[np.ndarray, dict]:
"""Mean spike template, no per-spike realignment (Zhao et al. 2026)."""
fs = recording.get_sampling_frequency()
n_channels = recording.get_num_channels()
total_samples = recording.get_num_samples()
n_before = int(ms_before * fs / 1000.0)
n_after = int(ms_after * fs / 1000.0)
win_len = n_before + n_after
running_sum: np.ndarray | None = None
n_used = 0
n_oob = 0
for sample_idx in spike_samples:
start = int(sample_idx) - n_before
end = int(sample_idx) + n_after
if start < 0 or end > total_samples:
n_oob += 1
continue
snippet = recording.get_traces(start_frame=start, end_frame=end).astype(
np.float32
)
running_sum = snippet if running_sum is None else running_sum + snippet
n_used += 1
if running_sum is not None and n_used >= min_spikes:
mean_template = running_sum / n_used
else:
mean_template = np.zeros((win_len, n_channels), dtype=np.float32)
return (
mean_template[np.newaxis, ...], # [1, win_len, n_ch]
{
"extraction_method": "zhao2026_raw_mean_template",
"ms_before": float(ms_before),
"ms_after": float(ms_after),
"nbefore": int(n_before),
"nafter": int(n_after),
"n_spikes_total": int(len(spike_samples)),
"n_spikes_used": int(n_used),
"n_out_of_bounds_discarded": int(n_oob),
},
)
def convert_cell(
cell_id: str,
cell_dir: str,
channel_locations: np.ndarray,
output_root: str,
summary_row: dict | None = None,
duration_s: float = 300.0,
segment_duration_s: float = 3.0,
train_fraction: float = 0.8,
ms_before: float = 1.0,
ms_after: float = 2.0,
skip_existing: bool = True,
) -> str:
output_dir = os.path.join(output_root, cell_id)
if skip_existing and os.path.isfile(
os.path.join(output_dir, "conversion_metadata.json")
):
print(f" [{cell_id}] Already converted, skipping.")
return output_dir
# Locate per-cell binaries
files: dict[str, str] = {}
for fname in os.listdir(cell_dir):
for suffix, key in [
("npx_raw.bin", "npx_raw"),
("patch_ch1.bin", "patch_v"),
("wc_spike_samples.npy", "wc_spike"),
]:
if fname.endswith(suffix):
files[key] = os.path.join(cell_dir, fname)
for k in ("npx_raw", "patch_v"):
if k not in files:
raise FileNotFoundError(f"[{cell_id}] missing {k} in {cell_dir}")
print(f" [{cell_id}] Loading recordings …")
npx_raw = np.memmap(files["npx_raw"], dtype="int16", mode="r").reshape(-1, 384)
n_npx_samples = npx_raw.shape[0]
patch_v = np.fromfile(files["patch_v"], dtype="float64")
if "wc_spike" in files:
spike_idx_patch = np.load(files["wc_spike"]).astype(np.int64)
spike_source = "wc_spike_samples.npy (authoritative GT)"
else:
spike_idx_patch = detect_spikes_from_patch(patch_v, PATCH_SAMPLE_RATE)
spike_source = "detect_spikes_from_patch (fallback)"
print(f" [{cell_id}] Spike source: {spike_source}")
# Re-express patch spike indices in NPX clock & restrict to analysis window
time_factor = n_npx_samples / len(patch_v)
spike_idx_npx = (spike_idx_patch * time_factor).astype(np.int64)
start_frame = int(SKIP_SECONDS * NPX_SAMPLE_RATE)
end_frame = min(start_frame + int(duration_s * NPX_SAMPLE_RATE), n_npx_samples)
spike_idx_npx = spike_idx_npx[
(spike_idx_npx >= start_frame) & (spike_idx_npx < end_frame)
]
spike_idx_relative = spike_idx_npx - start_frame
n_analysis_samples = end_frame - start_frame
print(
f" [{cell_id}] {len(spike_idx_npx)} spikes in "
f"[{SKIP_SECONDS:.0f}s, {SKIP_SECONDS + duration_s:.0f}s]"
)
rec = se.BinaryRecordingExtractor(
file_paths=files["npx_raw"],
sampling_frequency=NPX_SAMPLE_RATE,
num_channels=384,
dtype="int16",
time_axis=0,
)
rec.set_channel_locations(channel_locations)
rec = rec.frame_slice(start_frame, end_frame)
rec.set_property("gain_to_uV", np.full(384, 2.34375, dtype=np.float32))
rec.set_property("offset_to_uV", np.zeros(384, dtype=np.float32))
# Preprocessing: bandpass 300–3000 Hz + global CMR
rec_bp = spre.bandpass_filter(rec, freq_min=300.0, freq_max=3000.0)
rec_prep = spre.common_reference(rec_bp, operator="median", reference="global")
# Bad channel detection on bandpass (NOT on CMR'd traces as CMR collapses
# the inter-channel coherence the default detector relies on).
bad_ids, _ = spre.detect_bad_channels(recording=rec_bp)
rec_ids = list(rec_bp.channel_ids)
bad_idx = sorted(int(rec_ids.index(c)) for c in bad_ids)
print(f" [{cell_id}] {len(bad_idx)} bad channels: {bad_idx}")
# Templates
print(f" [{cell_id}] Extracting peak-aligned templates …")
templates_array, tpl_meta = extract_peak_aligned_templates(
rec_prep,
spike_idx_relative,
ms_before=ms_before,
ms_after=ms_after,
)
n_before = tpl_meta["nbefore"]
n_after = tpl_meta["nafter"]
template = templates_array[0] # [win_len, n_channels]
peak_ch = int(np.argmax(np.max(np.abs(template), axis=0)))
# Arrow segments
print(f" [{cell_id}] Writing Arrow segments …")
seg_len = int(segment_duration_s * NPX_SAMPLE_RATE)
segments = [
(i, min(i + seg_len, n_analysis_samples))
for i in range(0, n_analysis_samples, seg_len)
]
n_train = int(len(segments) * train_fraction)
for split, seg_range in [
("train", segments[:n_train]),
("test", segments[n_train:]),
]:
def _gen(sr=seg_range):
for s0, s1 in sr:
traces = rec_prep.get_traces(start_frame=s0, end_frame=s1)
cp = traces.T.astype(np.float32) # [n_channels, T]
cit: list[list[int]] = [[] for _ in range(384)]
ctt: list[list[float]] = [[] for _ in range(384)]
in_seg = spike_idx_relative[
(spike_idx_relative >= s0) & (spike_idx_relative < s1)
]
t_ms = (in_seg - s0).astype(np.float64) / NPX_SAMPLE_RATE * 1000.0
cit[peak_ch].extend([0] * len(t_ms))
ctt[peak_ch].extend(t_ms.tolist())
yield {
"sample_id": f"{s0:010d}",
"cit": [np.array(c, dtype=np.int32) for c in cit],
"ctt": [np.array(c, dtype=np.float64) for c in ctt],
"cp": [cp[ch] for ch in range(384)],
}
del cp, traces
gc.collect()
split_dir = os.path.join(output_dir, split)
os.makedirs(split_dir, exist_ok=True)
ds = Dataset.from_generator(_gen, writer_batch_size=1)
ds.save_to_disk(split_dir)
del ds
gc.collect()
print(f" [{cell_id}] Saved {split}: {len(seg_range)} segments")
with open(os.path.join(output_dir, "dataset_dict.json"), "w") as f:
json.dump({"splits": {"train": {"name": "train"}, "test": {"name": "test"}}}, f)
# Ground-truth electrode location from Data Summary.xlsx
gt_chan_idx: int | None = None
unit_xy: list[float] | None = None
if summary_row is not None:
gt_chan_idx = int(summary_row.get("chan_predicted", -1))
if 0 <= gt_chan_idx < len(channel_locations):
xy = channel_locations[gt_chan_idx].tolist()
unit_xy = [float(xy[0]), float(xy[1]), 0.0]
metadata = {
"source_metadata": {
"mode": "spe1_paired_recording",
"dataset": "Marques-Smith et al. (2018) — CRCNS spe-1",
"cell_id": cell_id,
"skip_seconds": float(SKIP_SECONDS),
"duration_s": float(duration_s),
"patch_sample_rate_hz": float(PATCH_SAMPLE_RATE),
"preprocessing": "bandpass_300_3000Hz + global_CMR",
"spike_source": spike_source,
},
"template_metadata": tpl_meta,
"sampling_frequency": float(NPX_SAMPLE_RATE),
"num_units": 1,
"num_channels": 384,
"unit_peak_channel": {"0": peak_ch},
"unit_locations_um": ({"0": unit_xy} if unit_xy is not None else None),
"gt_electrode_chan_idx": gt_chan_idx,
"bad_channel_ids": bad_idx,
"n_spikes_total": int(len(spike_idx_npx)),
"n_spikes_used_for_templates": int(tpl_meta["n_spikes_used"]),
"segment_duration_s": float(segment_duration_s),
"train_fraction": float(train_fraction),
}
with open(os.path.join(output_dir, "conversion_metadata.json"), "w") as f:
json.dump(metadata, f, indent=2)
np.savez(
os.path.join(output_dir, "templates.npz"),
templates=templates_array,
sampling_frequency=float(NPX_SAMPLE_RATE),
probe_positions=channel_locations,
nbefore=n_before,
nafter=n_after,
)
print(
f" [{cell_id}] Done — peak_ch={peak_ch}, "
f"spikes_used={tpl_meta['n_spikes_used']}"
)
del rec_prep, rec_bp, rec, npx_raw, patch_v
del spike_idx_patch, spike_idx_npx, spike_idx_relative, templates_array
gc.collect()
return output_dir
def main():
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument(
"--data-dir",
required=True,
help="Path to the SPE-1 Recordings/ folder (per-cell subdirs).",
)
p.add_argument(
"--chan-map",
default=None,
help="chanMap.mat (default: <data-dir>/../chanMap.mat).",
)
p.add_argument(
"--summary",
default=None,
help="Data Summary.xlsx (default: <data-dir>/../Data Summary.xlsx).",
)
p.add_argument("--output", required=True, help="Root output directory.")
p.add_argument(
"--cells",
nargs="+",
default=None,
help="Cell IDs (default: all 11 Hao et al. cells).",
)
p.add_argument(
"--duration",
type=float,
default=300.0,
help="Seconds of recording to use after burn-in (default: 300).",
)
p.add_argument(
"--segment-duration",
type=float,
default=3.0,
help="Arrow segment duration in seconds (default: 3.0).",
)
p.add_argument("--train-fraction", type=float, default=0.8)
p.add_argument("--ms-before", type=float, default=1.0)
p.add_argument("--ms-after", type=float, default=2.0)
p.add_argument("--no-skip-existing", action="store_true")
args = p.parse_args()
spe1_root = os.path.dirname(args.data_dir.rstrip("/"))
chan_map = args.chan_map or os.path.join(spe1_root, "chanMap.mat")
if not os.path.isfile(chan_map):
sys.exit(f"chanMap.mat not found at {chan_map}")
summary_path = args.summary
if summary_path is None:
for candidate in ("Data Summary.xlsx", "Data_Summary.xlsx"):
cand = os.path.join(spe1_root, candidate)
if os.path.isfile(cand):
summary_path = cand
break
d = scipy.io.loadmat(chan_map)
channel_locations = np.zeros((384, 2), dtype=np.float32)
channel_locations[:, 0] = d["xcoords"][:, 0]
channel_locations[:, 1] = d["ycoords"][:, 0]
print(f"Loaded probe geometry: 384 channels from {chan_map}")
summary: dict[str, dict] = {}
if summary_path and os.path.isfile(summary_path):
df = pd.read_excel(summary_path)
for _, row in df.iterrows():
if "Cell" in row and pd.notna(row["Cell"]):
summary[str(row["Cell"])] = row.to_dict()
print(f"Loaded Data Summary: {len(summary)} entries from {summary_path}")
else:
print("WARNING: Data Summary.xlsx not found — unit locations will be unset.")
cells = args.cells if args.cells is not None else ZHAO_CELLS
os.makedirs(args.output, exist_ok=True)
for cell_id in cells:
cell_dir = os.path.join(args.data_dir, cell_id)
if not os.path.isdir(cell_dir):
print(f" [{cell_id}] not found at {cell_dir} — skipping")
continue
try:
convert_cell(
cell_id=cell_id,
cell_dir=cell_dir,
channel_locations=channel_locations,
output_root=args.output,
summary_row=summary.get(cell_id),
duration_s=args.duration,
segment_duration_s=args.segment_duration,
train_fraction=args.train_fraction,
ms_before=args.ms_before,
ms_after=args.ms_after,
skip_existing=not args.no_skip_existing,
)
except Exception as e:
print(f" [{cell_id}] ERROR: {e}")
raise
if __name__ == "__main__":
main()
|