"""Convert SPE-1 paired patch / Neuropixels recordings to Arrow For each cell, this writes: // 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 /Recordings \\ --chan-map /chanMap.mat \\ --summary "/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: /../chanMap.mat).", ) p.add_argument( "--summary", default=None, help="Data Summary.xlsx (default: /../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()