[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73JKF71H0ZDCDWF93TZ6S5S":3,"skill-same:01M73JKF71H0ZDCDWF93TZ6S5S":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73JKF71H0ZDCDWF93TZ6S5S","spikeinterface-electrophysiology",null,"Unified Python framework for extracellular electrophysiology. Load 20+ formats (SpikeGLX, OpenEphys, NWB, Intan, Maxwell, Blackrock), preprocess, run 10+ sorters (Kilosort4, SpykingCircus2, Tridesclous, MountainSort5) via one API, compute quality metrics (SNR, ISI, firing rate), compare sorters, export NWB\u002FPhy. For format-agnostic multi-sorter workflows. For Neuropixels-specific PSTH\u002Fdecoding use neuropixels.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fspikeinterface-electrophysiology\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"spikeinterface-electrophysiology\"\ndescription: \"Unified Python framework for extracellular electrophysiology. Load 20+ formats (SpikeGLX, OpenEphys, NWB, Intan, Maxwell, Blackrock), preprocess, run 10+ sorters (Kilosort4, SpykingCircus2, Tridesclous, MountainSort5) via one API, compute quality metrics (SNR, ISI, firing rate), compare sorters, export NWB\u002FPhy. For format-agnostic multi-sorter workflows. For Neuropixels-specific PSTH\u002Fdecoding use neuropixels.\"\nlicense: \"MIT\"\n---\n\n# SpikeInterface — Unified Extracellular Electrophysiology Framework\n\n## Overview\n\nSpikeInterface provides a common Python API to read extracellular recordings from 20+ file formats, preprocess raw voltage traces, run 10+ spike sorters, postprocess and quality-control sorted units, and export results — all without format-specific code. Its modular design lets users swap sorters, formats, and preprocessing steps without rewriting pipelines. SpikeInterface is built around lazy, chainable objects: a `Recording` holds raw data, a `Sorting` holds spike times, and a `SortingAnalyzer` ties them together for waveform and metric computation.\n\n## When to Use\n\n- Loading recordings from multiple acquisition systems (SpikeGLX, OpenEphys, Intan, NWB, Maxwell MEA, Blackrock) with a unified API rather than format-specific parsers\n- Running the same preprocessing and sorting pipeline across experiments recorded on different hardware\n- Comparing two or more spike sorters on the same recording to assess agreement and choose the best output\n- Running containerized sorters (Kilosort, IronClust, MountainSort5) via Docker or Singularity without local installation\n- Computing standard quality metrics (SNR, ISI violations, firing rate, presence ratio, amplitude cutoff) and applying threshold-based curation\n- Validating spike-sorting accuracy against synthetic or hybrid ground-truth recordings\n- Exporting sorted results to NWB for data sharing or to Phy for manual curation\n- Use `neuropixels-analysis` instead for a complete Neuropixels-specific Kilosort4 workflow including PSTH computation, tuning curves, and population decoding\n- For EEG, ECG, or other biosignal processing (not spike sorting), use `neurokit2` instead\n\n## Prerequisites\n\n- **Python packages**: `spikeinterface[full]>=0.101`, `probeinterface`, `numpy`, `matplotlib`\n- **Optional sorter deps**: `kilosort` (pip), or Docker\u002FSingularity for containerized sorters\n- **Data requirements**: raw binary recording files plus probe geometry (`.prb`, `.json`, or auto-detected from format)\n- **Hardware**: GPU required for Kilosort4; all other sorters run on CPU\n\n```bash\npip install \"spikeinterface[full]>=0.101\" probeinterface\n# Optional: Kilosort4 Python package\npip install kilosort\n# Optional: Phy for manual curation\npip install phy\n```\n\n## Quick Start\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.preprocessing as spre\nimport spikeinterface.sorters as ss\nimport spikeinterface.qualitymetrics as sqm\n\n# Load, preprocess, sort, and inspect quality metrics in 10 lines\nrecording = si.read_openephys(\"\u002Fdata\u002Fsession_001\", stream_name=\"Signals CH\")\nrecording_pp = spre.bandpass_filter(\n    spre.common_reference(recording, reference=\"global\", operator=\"median\"),\n    freq_min=300, freq_max=6000,\n)\nsorting = ss.run_sorter(\"spykingcircus2\", recording_pp, output_folder=\".\u002Fsc2_out\")\nanalyzer = si.create_sorting_analyzer(sorting, recording_pp, folder=\".\u002Fanalyzer\")\nanalyzer.compute([\"random_spikes\", \"waveforms\", \"templates\", \"noise_levels\"])\nmetrics = sqm.compute_quality_metrics(analyzer, metric_names=[\"snr\", \"firing_rate\", \"isi_violation\"])\nprint(metrics.describe())\n```\n\n## Core API\n\n### Module 1: Recording I\u002FO\n\nSpikeInterface wraps every acquisition format behind a common `BaseRecording` interface. Once loaded, all objects expose the same methods regardless of origin format.\n\n```python\nimport spikeinterface.full as si\n\n# SpikeGLX (.bin + .meta)\nrecording_sglx = si.read_spikeglx(\"\u002Fdata\u002Fsession_001\", stream_name=\"imec0.ap\")\n\n# OpenEphys (binary or classic)\nrecording_oe = si.read_openephys(\"\u002Fdata\u002Foe_session\", stream_name=\"Signals CH\")\n\n# NWB file\nrecording_nwb = si.read_nwb_recording(\"\u002Fdata\u002Frecording.nwb\",\n                                       electrical_series_name=\"ElectricalSeries\")\n\n# Intan RHD\u002FRHS\nrecording_intan = si.read_intan(\"\u002Fdata\u002Fsession.rhd\", stream_name=\"RHn\")\n\n# Inspect any recording with the same API\nprint(f\"Format:       {type(recording_sglx).__name__}\")\nprint(f\"Channels:     {recording_sglx.get_num_channels()}\")\nprint(f\"Sampling rate:{recording_sglx.get_sampling_frequency()} Hz\")\nprint(f\"Duration:     {recording_sglx.get_total_duration():.1f} s\")\nprint(f\"Probe:        {recording_sglx.get_probe().name}\")\n```\n\n```python\n# List available streams before loading (useful when a file has multiple streams)\nstreams = si.get_neo_streams(\"spikeglx\", \"\u002Fdata\u002Fsession_001\")\nprint(\"Available streams:\", streams)\n# e.g. ['imec0.ap', 'imec0.lf', 'nidq']\n\n# Select a time slice (lazy, no data loaded until get_traces() is called)\nrecording_slice = recording_sglx.frame_slice(\n    start_frame=0,\n    end_frame=int(60 * recording_sglx.get_sampling_frequency()),  # first 60 s\n)\nprint(f\"Sliced duration: {recording_slice.get_total_duration():.1f} s\")\n```\n\n### Module 2: Preprocessing\n\nPreprocessing functions return new `Recording` objects wrapping the original; the chain is applied lazily when data is read. This keeps memory usage low even for multi-hour recordings.\n\n```python\nimport spikeinterface.preprocessing as spre\n\n# 1. Common median reference — removes shared noise across all channels\nrecording_cmr = spre.common_reference(recording_sglx,\n                                       reference=\"global\",\n                                       operator=\"median\")\n\n# 2. Bandpass filter for action potentials (300–6000 Hz typical)\nrecording_filt = spre.bandpass_filter(recording_cmr,\n                                       freq_min=300,\n                                       freq_max=6000)\n\n# 3. Remove bad channels automatically (coherence-based detection)\nrecording_clean, removed_ids = spre.remove_bad_channels(recording_filt,\n                                                          method=\"coherence+psd\")\nprint(f\"Removed {len(removed_ids)} bad channels: {removed_ids}\")\nprint(f\"Clean channels: {recording_clean.get_num_channels()}\")\n```\n\n```python\n# Whitening — decorrelates channels; recommended before template-matching sorters\nrecording_white = spre.whiten(recording_clean, mode=\"local\")\n\n# Phase shift correction for Neuropixels (samples acquired with small time offsets)\nrecording_shifted = spre.phase_shift(recording_clean)\n\n# Inspect a short snippet of preprocessed data\ntraces = recording_white.get_traces(start_frame=0, end_frame=3000, segment_index=0)\nprint(f\"Trace snippet shape: {traces.shape}\")   # (3000, n_channels)\nprint(f\"Trace range: [{traces.min():.2f}, {traces.max():.2f}] µV\")\n```\n\n### Module 3: Spike Sorting\n\n`ss.run_sorter()` wraps every supported sorter behind a uniform call signature. Sorter-specific parameters are passed as keyword arguments; all other pipeline steps are identical.\n\n```python\nimport spikeinterface.sorters as ss\nfrom pathlib import Path\n\n# List all sorters available in the current environment\navailable = ss.available_sorters()\nprint(\"Available sorters:\", available)\n\n# List sorters that can run without local installation (via container)\ninstalled = ss.installed_sorters()\nprint(\"Installed locally:\", installed)\n\n# Run SpykingCircus2 (CPU, no external deps)\nsorting_sc2 = ss.run_sorter(\n    \"spykingcircus2\",\n    recording_clean,\n    output_folder=Path(\".\u002Fsorter_output\u002Fsc2\"),\n    remove_existing_folder=True,\n    verbose=True,\n)\nprint(f\"SpykingCircus2 units: {len(sorting_sc2.get_unit_ids())}\")\n```\n\n```python\n# Run Kilosort4 via Docker container (no local GPU\u002FMATLAB required)\nsorting_ks4 = ss.run_sorter(\n    \"kilosort4\",\n    recording_clean,\n    output_folder=Path(\".\u002Fsorter_output\u002Fks4\"),\n    singularity_image=False,   # use Docker; set True for Singularity\n    docker_image=True,\n    remove_existing_folder=True,\n    # Kilosort4-specific parameters\n    nblocks=5,\n    Th_learned=8,\n    do_correction=True,\n)\nprint(f\"Kilosort4 units: {len(sorting_ks4.get_unit_ids())}\")\n\n# Run MountainSort5 (CPU, fast, good for tetrode\u002Flow-channel-count probes)\nsorting_ms5 = ss.run_sorter(\n    \"mountainsort5\",\n    recording_clean,\n    output_folder=Path(\".\u002Fsorter_output\u002Fms5\"),\n    scheme=\"2\",          # scheme 2 is recommended for high-density probes\n    detect_threshold=5.5,\n)\nprint(f\"MountainSort5 units: {len(sorting_ms5.get_unit_ids())}\")\n```\n\n### Module 4: Postprocessing (SortingAnalyzer)\n\n`SortingAnalyzer` is the central postprocessing object in SpikeInterface >= 0.101. It replaces the older `WaveformExtractor` and provides a unified interface for waveforms, templates, PCAs, and downstream metrics.\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.postprocessing as spost\n\n# Create analyzer (saves to disk; use format=\"memory\" for in-RAM only)\nanalyzer = si.create_sorting_analyzer(\n    sorting_sc2,\n    recording_clean,\n    folder=\".\u002Fanalyzer_sc2\",\n    format=\"binary_folder\",\n    overwrite=True,\n    sparse=True,           # sparse=True: only nearby channels per unit\n    ms_before=1.0,\n    ms_after=2.0,\n)\n\n# Compute extensions in dependency order\nanalyzer.compute([\n    \"random_spikes\",       # subsample spike indices for waveform extraction\n    \"waveforms\",           # raw waveform snippets per unit\n    \"templates\",           # mean\u002Fstd template per unit\n    \"noise_levels\",        # per-channel noise estimate\n])\n\n# Retrieve templates\ntemplates = analyzer.get_extension(\"templates\").get_data(outputs=\"Templates\")\nprint(f\"Templates object: {templates}\")\nprint(f\"Unit 0 template shape: {templates.get_one_template_dense(0).shape}\")\n# (n_samples, n_channels)\n```\n\n```python\n# Compute amplitude and PCA extensions (needed for quality metrics)\nanalyzer.compute([\n    \"spike_amplitudes\",          # amplitude at peak channel per spike\n    \"principal_components\",      # PCA scores (n_components x n_spikes)\n    \"template_similarity\",       # pairwise template correlation matrix\n    \"correlograms\",              # auto- and cross-correlograms\n    \"unit_locations\",            # estimated unit position on probe (center of mass)\n])\n\n# Access spike amplitudes for first unit\next_amp = analyzer.get_extension(\"spike_amplitudes\")\nunit_ids = analyzer.unit_ids\namps = ext_amp.get_data()[analyzer.sorting.ids_to_indices([unit_ids[0]])]\nprint(f\"Unit {unit_ids[0]} — median amplitude: {abs(amps).median():.1f} µV\")\n```\n\n### Module 5: Quality Metrics\n\nQuality metrics summarize unit isolation quality. Metrics requiring only spike times (ISI violations, firing rate) are fast; metrics requiring waveforms (SNR, amplitude cutoff) need the `SortingAnalyzer` to be populated first.\n\n```python\nimport spikeinterface.qualitymetrics as sqm\n\n# Compute a standard panel of quality metrics\nmetrics = sqm.compute_quality_metrics(\n    analyzer,\n    metric_names=[\n        \"snr\",                    # signal-to-noise ratio of template peak\n        \"isi_violation\",          # fraction of ISIs \u003C refractory period\n        \"firing_rate\",            # mean firing rate (Hz) over recording\n        \"presence_ratio\",         # fraction of time windows with ≥1 spike\n        \"amplitude_cutoff\",       # estimated fraction of spikes below threshold\n        \"nearest_neighbor\",       # isolation distance in PCA space\n        \"silhouette_score\",       # cluster separation in PCA space\n    ],\n)\nprint(metrics.head())\nprint(f\"\\nShape: {metrics.shape}\")  # (n_units, n_metrics)\n```\n\n```python\nimport pandas as pd\n\n# Apply threshold-based curation (Allen Brain Institute defaults)\nthresholds = {\n    \"snr\":                   (\">=\", 5.0),\n    \"isi_violations_ratio\":  (\"\u003C=\", 0.1),\n    \"firing_rate\":           (\">=\", 0.1),\n    \"presence_ratio\":        (\">=\", 0.9),\n    \"amplitude_cutoff\":      (\"\u003C=\", 0.1),\n}\n\nkeep = pd.Series(True, index=metrics.index)\nfor col, (op, val) in thresholds.items():\n    if col not in metrics.columns:\n        continue\n    if op == \">=\":\n        keep &= metrics[col] >= val\n    else:\n        keep &= metrics[col] \u003C= val\n\ngood_unit_ids = metrics[keep].index.tolist()\nprint(f\"Total units:   {len(metrics)}\")\nprint(f\"Curated units: {len(good_unit_ids)} ({100*len(good_unit_ids)\u002Flen(metrics):.0f}%)\")\n\n# Filter analyzer to good units\nsorting_curated = sorting_sc2.select_units(good_unit_ids)\n```\n\n### Module 6: Comparison and Export\n\nCompare sorters against each other or against ground truth, then export results in shareable formats.\n\n```python\nimport spikeinterface.comparison as sc\n\n# Compare two sorters — matches units by spike train overlap\ncomparison = sc.compare_two_sorters(\n    sorting_sc2,\n    sorting_ks4,\n    sorting1_name=\"SpykingCircus2\",\n    sorting2_name=\"Kilosort4\",\n    match_score=0.5,        # minimum overlap to count as a match\n    delta_time=0.4,         # coincidence window (ms)\n)\n\n# Performance summary per matched unit pair\nperf = comparison.get_performance(method=\"by_unit\")\nprint(perf.head(10))\n# Columns: accuracy, recall, precision, false_discovery_rate, miss_rate\n\n# Agreement score matrix (fraction overlap between all unit pairs)\nagreement_matrix = comparison.get_agreement_fraction_table()\nprint(f\"Agreement matrix shape: {agreement_matrix.shape}\")\n```\n\n```python\nimport spikeinterface.exporters as sexp\n\n# Export curated sorting to NWB (Neurodata Without Borders)\nsexp.export_to_nwb(\n    sorting_curated,\n    nwb_file_path=\".\u002Fsession_sorted.nwb\",\n    overwrite=True,\n)\nprint(\"Exported to NWB: session_sorted.nwb\")\n\n# Export to Phy for manual curation\nsexp.export_to_phy(\n    analyzer,\n    output_folder=\".\u002Fphy_export\",\n    compute_pc_features=True,\n    copy_binary=True,\n    remove_if_exists=True,\n)\nprint(\"Phy export ready at: .\u002Fphy_export\")\nprint(\"Launch Phy with: phy template-gui phy_export\u002Fparams.py\")\n```\n\n## Common Workflows\n\n### Workflow 1: Multi-Sorter Comparison on OpenEphys Data\n\n**Goal**: Load an OpenEphys recording, preprocess, run two sorters, compare their agreement, curate the higher-yield output, and export to NWB.\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.preprocessing as spre\nimport spikeinterface.sorters as ss\nimport spikeinterface.comparison as sc\nimport spikeinterface.qualitymetrics as sqm\nimport spikeinterface.exporters as sexp\nfrom pathlib import Path\n\n# --- Step 1: Load ---\ndata_dir = Path(\"\u002Fdata\u002Foe_recording\")\nstreams = si.get_neo_streams(\"openephys\", data_dir)\nprint(\"Streams:\", streams)\n\nrecording = si.read_openephys(data_dir, stream_name=\"Signals CH\")\nprint(f\"Loaded: {recording.get_num_channels()} ch, \"\n      f\"{recording.get_sampling_frequency()} Hz, \"\n      f\"{recording.get_total_duration():.1f} s\")\n\n# --- Step 2: Preprocess ---\nrec = spre.bandpass_filter(recording, freq_min=300, freq_max=6000)\nrec = spre.common_reference(rec, reference=\"global\", operator=\"median\")\nrec, bad_ids = spre.remove_bad_channels(rec, method=\"coherence+psd\")\nprint(f\"Preprocessing complete. Removed channels: {bad_ids}\")\n\n# --- Step 3: Run two sorters ---\nout = Path(\".\u002Fsorting_outputs\")\nsorting_sc2 = ss.run_sorter(\"spykingcircus2\", rec,\n                              output_folder=out \u002F \"sc2\",\n                              remove_existing_folder=True)\nsorting_tdc = ss.run_sorter(\"tridesclous2\", rec,\n                              output_folder=out \u002F \"tdc\",\n                              remove_existing_folder=True)\nprint(f\"SC2 units: {len(sorting_sc2.unit_ids)}, \"\n      f\"TDC units: {len(sorting_tdc.unit_ids)}\")\n\n# --- Step 4: Compare ---\ncmp = sc.compare_two_sorters(sorting_sc2, sorting_tdc,\n                               sorting1_name=\"SC2\",\n                               sorting2_name=\"Tridesclous2\",\n                               match_score=0.5)\nperf = cmp.get_performance(method=\"pooled_with_average\")\nprint(f\"\\nAgreement performance:\\n{perf}\")\n\n# --- Step 5: Quality metrics on SC2 (higher yield) ---\nanalyzer = si.create_sorting_analyzer(sorting_sc2, rec,\n                                        folder=\".\u002Fanalyzer_sc2\",\n                                        overwrite=True, sparse=True)\nanalyzer.compute([\"random_spikes\", \"waveforms\", \"templates\",\n                  \"noise_levels\", \"spike_amplitudes\"])\nmetrics = sqm.compute_quality_metrics(\n    analyzer,\n    metric_names=[\"snr\", \"firing_rate\", \"isi_violation\",\n                  \"presence_ratio\", \"amplitude_cutoff\"],\n)\n\nkeep = (metrics[\"snr\"] >= 5) & (metrics[\"isi_violations_ratio\"] \u003C= 0.1) \\\n     & (metrics[\"firing_rate\"] >= 0.1) & (metrics[\"presence_ratio\"] >= 0.9)\nsorting_curated = sorting_sc2.select_units(metrics[keep].index.tolist())\nprint(f\"\\nCurated: {len(sorting_curated.unit_ids)} \u002F {len(sorting_sc2.unit_ids)} units\")\n\n# --- Step 6: Export winner to NWB ---\nsexp.export_to_nwb(sorting_curated,\n                    nwb_file_path=\".\u002Fsession_sorted.nwb\",\n                    overwrite=True)\nprint(\"Saved: session_sorted.nwb\")\n```\n\n### Workflow 2: Ground Truth Validation with Synthetic Recordings\n\n**Goal**: Generate a synthetic recording with known spike trains, run a sorter, and measure true accuracy (recall, precision) against ground truth — for benchmarking sorters or testing preprocessing pipelines.\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.preprocessing as spre\nimport spikeinterface.sorters as ss\nimport spikeinterface.comparison as sc\nimport numpy as np\n\n# --- Step 1: Generate ground-truth synthetic recording ---\n# Uses a Marsaglia noise model with realistic waveform templates\nrecording_gt, sorting_gt = si.generate_ground_truth_recording(\n    durations=[120.0],             # 120 s recording\n    sampling_frequency=30000.0,\n    num_channels=32,\n    num_units=10,\n    noise_kwargs={\"noise_level\": 10.0, \"dtype\": \"float32\"},\n    seed=42,\n)\nprint(f\"GT recording: {recording_gt.get_num_channels()} ch, \"\n      f\"{recording_gt.get_total_duration():.0f} s\")\nprint(f\"GT units: {len(sorting_gt.unit_ids)}\")\nprint(f\"GT firing rates: \"\n      f\"{[round(len(sorting_gt.get_unit_spike_train(u, 0))\u002F120, 1) for u in sorting_gt.unit_ids]} Hz\")\n\n# --- Step 2: Preprocess ---\nrec_pp = spre.bandpass_filter(recording_gt, freq_min=300, freq_max=6000)\nrec_pp = spre.common_reference(rec_pp, reference=\"global\", operator=\"median\")\n\n# --- Step 3: Sort with two sorters ---\nsorting_sc2 = ss.run_sorter(\"spykingcircus2\", rec_pp,\n                              output_folder=\".\u002Fgt_sc2\",\n                              remove_existing_folder=True)\nsorting_ms5 = ss.run_sorter(\"mountainsort5\", rec_pp,\n                              output_folder=\".\u002Fgt_ms5\",\n                              remove_existing_folder=True,\n                              scheme=\"2\")\n\n# --- Step 4: Compare each sorter against ground truth ---\nfor name, sorting_test in [(\"SC2\", sorting_sc2), (\"MS5\", sorting_ms5)]:\n    cmp = sc.compare_sorter_to_ground_truth(sorting_gt, sorting_test,\n                                              exhaustive_gt=True)\n    perf = cmp.get_performance(method=\"pooled_with_average\")\n    print(f\"\\n{name} vs Ground Truth:\")\n    print(f\"  Accuracy:  {perf['accuracy']:.3f}\")\n    print(f\"  Recall:    {perf['recall']:.3f}\")\n    print(f\"  Precision: {perf['precision']:.3f}\")\n    print(f\"  Well-detected units: {cmp.get_well_detected_units(well_detected_score=0.8)}\")\n```\n\n### Workflow 3: Batch Processing Multiple Sessions\n\n**Goal**: Apply the same preprocessing + sorting pipeline to multiple recording sessions and collect quality metrics across all sessions.\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.preprocessing as spre\nimport spikeinterface.sorters as ss\nimport spikeinterface.qualitymetrics as sqm\nimport pandas as pd\nfrom pathlib import Path\n\nsessions = list(Path(\"\u002Fdata\u002Fexperiment\").glob(\"session_*\u002F\"))\nall_metrics = []\n\nfor session_dir in sessions:\n    print(f\"Processing {session_dir.name} ...\")\n    try:\n        streams = si.get_neo_streams(\"spikeglx\", session_dir)\n        ap_stream = [s for s in streams if \"ap\" in s][0]\n        rec = si.read_spikeglx(session_dir, stream_name=ap_stream)\n\n        # Preprocess\n        rec = spre.bandpass_filter(\n            spre.common_reference(rec, reference=\"global\", operator=\"median\"),\n            freq_min=300, freq_max=6000,\n        )\n        rec, _ = spre.remove_bad_channels(rec)\n\n        # Sort\n        out_dir = session_dir \u002F \"sorting\"\n        sorting = ss.run_sorter(\"spykingcircus2\", rec,\n                                 output_folder=out_dir,\n                                 remove_existing_folder=True)\n\n        # Compute metrics\n        analyzer = si.create_sorting_analyzer(\n            sorting, rec, folder=session_dir \u002F \"analyzer\", overwrite=True, sparse=True\n        )\n        analyzer.compute([\"random_spikes\", \"waveforms\", \"templates\",\n                          \"noise_levels\", \"spike_amplitudes\"])\n        m = sqm.compute_quality_metrics(\n            analyzer, metric_names=[\"snr\", \"firing_rate\", \"isi_violation\"]\n        )\n        m[\"session\"] = session_dir.name\n        all_metrics.append(m)\n\n    except Exception as e:\n        print(f\"  FAILED: {e}\")\n        continue\n\n# Combine across sessions\ncombined = pd.concat(all_metrics)\ncombined.to_csv(\"all_sessions_metrics.csv\")\nprint(f\"\\nSaved metrics: {combined.shape[0]} units across {len(all_metrics)} sessions\")\nprint(combined.groupby(\"session\")[[\"snr\", \"firing_rate\"]].median())\n```\n\n## Key Parameters\n\n| Parameter | Module \u002F Function | Default | Range \u002F Options | Effect |\n|-----------|-------------------|---------|-----------------|--------|\n| `freq_min` \u002F `freq_max` | `spre.bandpass_filter` | 300 \u002F 6000 Hz | 150–500 \u002F 3000–10000 Hz | Spike band; use 300–6000 Hz for AP activity |\n| `reference` | `spre.common_reference` | `\"global\"` | `\"global\"`, `\"local\"`, `\"single\"` | Channel subset used for median reference subtraction |\n| `method` | `spre.remove_bad_channels` | `\"coherence+psd\"` | `\"coherence+psd\"`, `\"std\"`, `\"mad\"` | Algorithm for bad channel detection |\n| `scheme` | `ss.run_sorter(\"mountainsort5\")` | `\"2\"` | `\"1\"`, `\"2\"`, `\"3\"` | Sorting scheme; scheme 2 recommended for high-density probes |\n| `nblocks` | `ss.run_sorter(\"kilosort4\")` | `5` | `0–10` | Number of drift correction blocks; 0 disables drift correction |\n| `Th_learned` | `ss.run_sorter(\"kilosort4\")` | `8` | `6–12` | Detection threshold (× noise); lower = more units, more noise |\n| `match_score` | `sc.compare_two_sorters` | `0.5` | `0.1–0.9` | Minimum spike-train overlap to declare a unit match |\n| `sparse` | `si.create_sorting_analyzer` | `True` | `True`, `False` | Limit waveform extraction to channels near each unit; reduces memory |\n| `ms_before` \u002F `ms_after` | `si.create_sorting_analyzer` | `1.0` \u002F `2.0` ms | 0.5–2.0 \u002F 1.0–3.0 ms | Waveform snippet window relative to detected spike peak |\n| `snr` threshold | `sqm.compute_quality_metrics` | — | 5–10 recommended | Amplitude \u002F noise ratio; > 5 indicates well-isolated unit |\n| `isi_violations_ratio` | `sqm.compute_quality_metrics` | — | ≤ 0.1 recommended | Fraction of ISIs \u003C refractory period (1.5 ms); \u003C 0.1 = single unit |\n| `presence_ratio` | `sqm.compute_quality_metrics` | — | ≥ 0.9 recommended | Fraction of recording epochs where unit fires; \u003C 0.9 = drifting unit |\n\n## Best Practices\n\n1. **Always inspect available streams before loading**: Different acquisition systems save AP data, LFP data, and auxiliary channels as separate streams. Loading the wrong stream silently yields valid-looking but incorrect data.\n   ```python\n   streams = si.get_neo_streams(\"spikeglx\", data_dir)\n   print(streams)  # e.g. ['imec0.ap', 'imec0.lf', 'nidq']\n   recording = si.read_spikeglx(data_dir, stream_name=\"imec0.ap\")\n   ```\n\n2. **Chain preprocessing lazily; do not load to memory early**: Preprocessing objects are lazy and apply transformations at read time. Calling `get_traces()` on the raw recording before preprocessing will load unfiltered data into RAM unnecessarily. Build the full chain before any data access.\n\n3. **Use `sparse=True` when creating a SortingAnalyzer**: For high-channel-count probes (64–384 channels), dense waveform extraction is 10–50× more expensive in RAM and disk than sparse. Sparse mode extracts waveforms only on the channels nearest each unit.\n\n4. **Run containerized sorters to avoid dependency conflicts**: Kilosort2\u002F3 (MATLAB), IronClust, and other sorters have complex dependencies. Use `docker_image=True` in `run_sorter()` to pull the official container and run the sorter in isolation:\n   ```python\n   sorting = ss.run_sorter(\"kilosort2_5\", recording_clean,\n                            output_folder=\".\u002Fks25_out\",\n                            docker_image=True)\n   ```\n\n5. **Compute metrics extensions in dependency order**: Extensions depend on each other. The canonical order is: `random_spikes` → `waveforms` → `templates` → `noise_levels` → `spike_amplitudes` → `principal_components`. Skipping an earlier step causes a `MissingExtensionError` when a downstream step is requested.\n\n6. **Save the SortingAnalyzer to disk for large recordings**: In-memory analyzers (`format=\"memory\"`) are lost when the process exits. For recordings longer than 30 minutes or with many units, always specify a `folder` path so the analyzer can be reloaded:\n   ```python\n   analyzer = si.load_sorting_analyzer(\".\u002Fanalyzer_sc2\")\n   ```\n\n7. **Do not compare sorters with mismatched preprocessing**: When benchmarking sorters, run all of them on the same preprocessed `recording_clean` object. Running sorters on different preprocessing chains invalidates the comparison.\n\n## Common Recipes\n\n### Recipe: Load and Inspect a Multi-Stream Recording\n\nWhen to use: Quickly check what streams are available in an unfamiliar recording and confirm channel counts and duration before committing to a full sort.\n\n```python\nimport spikeinterface.full as si\n\ndata_dir = \"\u002Fdata\u002Frecording_session\"\n\n# Try SpikeGLX first; if it fails, try OpenEphys\ntry:\n    streams = si.get_neo_streams(\"spikeglx\", data_dir)\n    fmt = \"spikeglx\"\nexcept Exception:\n    streams = si.get_neo_streams(\"openephys\", data_dir)\n    fmt = \"openephys\"\n\nprint(f\"Format: {fmt}\")\nprint(f\"Streams: {streams}\")\n\nfor stream in streams:\n    try:\n        rec = si.read_spikeglx(data_dir, stream_name=stream) if fmt == \"spikeglx\" \\\n              else si.read_openephys(data_dir, stream_name=stream)\n        print(f\"  {stream}: {rec.get_num_channels()} ch, \"\n              f\"{rec.get_sampling_frequency()} Hz, \"\n              f\"{rec.get_total_duration():.1f} s\")\n    except Exception as e:\n        print(f\"  {stream}: could not load ({e})\")\n```\n\n### Recipe: Export Quality Metrics Report to CSV\n\nWhen to use: After running quality metrics, save a tidy CSV summarizing all units with their metrics and a pass\u002Ffail column for downstream analysis or sharing with collaborators.\n\n```python\nimport spikeinterface.qualitymetrics as sqm\nimport pandas as pd\n\nmetrics = sqm.compute_quality_metrics(\n    analyzer,\n    metric_names=[\"snr\", \"firing_rate\", \"isi_violation\",\n                  \"presence_ratio\", \"amplitude_cutoff\"],\n)\n\n# Add pass\u002Ffail column based on standard thresholds\nmetrics[\"pass_qc\"] = (\n    (metrics[\"snr\"] >= 5) &\n    (metrics[\"isi_violations_ratio\"] \u003C= 0.1) &\n    (metrics[\"firing_rate\"] >= 0.1) &\n    (metrics[\"presence_ratio\"] >= 0.9) &\n    (metrics[\"amplitude_cutoff\"] \u003C= 0.1)\n)\n\nmetrics.to_csv(\"unit_quality_metrics.csv\")\nn_pass = metrics[\"pass_qc\"].sum()\nprint(f\"QC report saved: {len(metrics)} total units, {n_pass} pass ({100*n_pass\u002Flen(metrics):.0f}%)\")\nprint(metrics[metrics[\"pass_qc\"]].describe())\n```\n\n### Recipe: Probe Geometry Visualization\n\nWhen to use: Verify that the probe channel map loaded correctly before sorting. Incorrect channel maps silently degrade sorting quality on high-density probes.\n\n```python\nimport spikeinterface.full as si\nimport matplotlib.pyplot as plt\nimport probeinterface.plotting as pp\n\nrecording = si.read_spikeglx(\"\u002Fdata\u002Fsession_001\", stream_name=\"imec0.ap\")\nprobe = recording.get_probe()\nprint(f\"Probe name: {probe.name}\")\nprint(f\"N contacts: {probe.get_contact_count()}\")\nprint(f\"Contact positions (first 5):\\n{probe.contact_positions[:5]}\")\n\nfig, ax = plt.subplots(figsize=(3, 10))\npp.plot_probe(probe, ax=ax, with_channel_index=True)\nax.set_title(f\"{probe.name} — channel map\")\nplt.tight_layout()\nplt.savefig(\"probe_geometry.png\", dpi=150)\nprint(\"Saved probe_geometry.png\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `ValueError: stream_name not found` | Recording has multiple streams; none is specified | Run `si.get_neo_streams(format, path)` to list available streams; pass the correct one to the reader |\n| Sorter output has zero units | Detection threshold too high, or preprocessing removed all signal | Verify `recording_clean.get_traces()` returns non-zero data; lower detection threshold (e.g. `Th_learned=6` for Kilosort4) |\n| `MissingExtensionError` | Analyzer extension depends on an uncomputed prerequisite | Follow the canonical compute order: `random_spikes` → `waveforms` → `templates` → `noise_levels` → `spike_amplitudes` |\n| Docker sorter hangs at startup | Docker daemon not running or image not pulled | Run `docker ps` to confirm Docker is running; pull image manually with `docker pull spikeinterface\u002Fkilosort4-compiled-base` |\n| `MemoryError` during waveform extraction | Dense extraction on high-channel-count probe | Use `sparse=True` in `create_sorting_analyzer`; reduce `max_spikes_per_unit` (default 500) |\n| Bad channel detection removes too many channels | Threshold too aggressive or short recording | Set `method=\"std\"` for a simpler threshold; increase `bad_threshold` parameter |\n| Unit comparison shows 0% agreement between sorters | Delta time window too narrow or match score too strict | Increase `delta_time` (default 0.4 ms) and lower `match_score` (try 0.3) |\n| NWB export raises `TypeError` on unit properties | Sorting contains non-serializable properties from sorter | Remove problematic properties: `sorting.remove_unit_property(\"property_name\")` before export |\n| `read_spikeglx` fails on LF stream | LFP stream uses different file suffix (`.lf.bin`) | Specify `stream_name=\"imec0.lf\"` explicitly; confirm file exists with `ls data_dir\u002F*.lf.bin` |\n\n## Related Skills\n\n- **neuropixels-analysis** — Neuropixels-specific pipeline using SpikeInterface + Kilosort4 with PSTH, tuning curves, and population decoding for rodent and primate experiments\n- **neurokit2** — For biosignal processing (ECG, EEG, EDA, EMG, PPG) rather than spike sorting; use when data is not extracellular electrophysiology\n\n## References\n\n- [SpikeInterface documentation](https:\u002F\u002Fspikeinterface.readthedocs.io\u002F) — full API reference, tutorials, and sorter-specific guides\n- [SpikeInterface GitHub](https:\u002F\u002Fgithub.com\u002FSpikeInterface\u002Fspikeinterface) — source code, changelogs, and issue tracker\n- [Buccino et al. (2020), eLife — SpikeInterface paper](https:\u002F\u002Fdoi.org\u002F10.7554\u002FeLife.61834) — unified framework design and benchmarks across sorters\n- [ProbeInterface documentation](https:\u002F\u002Fprobeinterface.readthedocs.io\u002F) — probe geometry handling and channel map formats\n- [SpikeInterface sorter list](https:\u002F\u002Fspikeinterface.readthedocs.io\u002Fen\u002Flatest\u002Fmodules\u002Fsorters.html) — supported sorters, requirements, and container images\n- [NWB documentation](https:\u002F\u002Fwww.nwb.org\u002F) — Neurodata Without Borders format for neurophysiology data sharing\n","# SpikeInterface — Unified Extracellular Electrophysiology Framework\n\n## Overview\n\nSpikeInterface provides a common Python API to read extracellular recordings from 20+ file formats, preprocess raw voltage traces, run 10+ spike sorters, postprocess and quality-control sorted units, and export results — all without format-specific code. Its modular design lets users swap sorters, formats, and preprocessing steps without rewriting pipelines. SpikeInterface is built around lazy, chainable objects: a `Recording` holds raw data, a `Sorting` holds spike times, and a `SortingAnalyzer` ties them together for waveform and metric computation.\n\n## When to Use\n\n- Loading recordings from multiple acquisition systems (SpikeGLX, OpenEphys, Intan, NWB, Maxwell MEA, Blackrock) with a unified API rather than format-specific parsers\n- Running the same preprocessing and sorting pipeline across experiments recorded on different hardware\n- Comparing two or more spike sorters on the same recording to assess agreement and choose the best output\n- Running containerized sorters (Kilosort, IronClust, MountainSort5) via Docker or Singularity without local installation\n- Computing standard quality metrics (SNR, ISI violations, firing rate, presence ratio, amplitude cutoff) and applying threshold-based curation\n- Validating spike-sorting accuracy against synthetic or hybrid ground-truth recordings\n- Exporting sorted results to NWB for data sharing or to Phy for manual curation\n- Use `neuropixels-analysis` instead for a complete Neuropixels-specific Kilosort4 workflow including PSTH computation, tuning curves, and population decoding\n- For EEG, ECG, or other biosignal processing (not spike sorting), use `neurokit2` instead\n\n## Prerequisites\n\n- **Python packages**: `spikeinterface[full]>=0.101`, `probeinterface`, `numpy`, `matplotlib`\n- **Optional sorter deps**: `kilosort` (pip), or Docker\u002FSingularity for containerized sorters\n- **Data requirements**: raw binary recording files plus probe geometry (`.prb`, `.json`, or auto-detected from format)\n- **Hardware**: GPU required for Kilosort4; all other sorters run on CPU\n\n```bash\npip install \"spikeinterface[full]>=0.101\" probeinterface\n# Optional: Kilosort4 Python package\npip install kilosort\n# Optional: Phy for manual curation\npip install phy\n```\n\n## Quick Start\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.preprocessing as spre\nimport spikeinterface.sorters as ss\nimport spikeinterface.qualitymetrics as sqm\n\n# Load, preprocess, sort, and inspect quality metrics in 10 lines\nrecording = si.read_openephys(\"\u002Fdata\u002Fsession_001\", stream_name=\"Signals CH\")\nrecording_pp = spre.bandpass_filter(\n    spre.common_reference(recording, reference=\"global\", operator=\"median\"),\n    freq_min=300, freq_max=6000,\n)\nsorting = ss.run_sorter(\"spykingcircus2\", recording_pp, output_folder=\".\u002Fsc2_out\")\nanalyzer = si.create_sorting_analyzer(sorting, recording_pp, folder=\".\u002Fanalyzer\")\nanalyzer.compute([\"random_spikes\", \"waveforms\", \"templates\", \"noise_levels\"])\nmetrics = sqm.compute_quality_metrics(analyzer, metric_names=[\"snr\", \"firing_rate\", \"isi_violation\"])\nprint(metrics.describe())\n```\n\n## Core API\n\n### Module 1: Recording I\u002FO\n\nSpikeInterface wraps every acquisition format behind a common `BaseRecording` interface. Once loaded, all objects expose the same methods regardless of origin format.\n\n```python\nimport spikeinterface.full as si\n\n# SpikeGLX (.bin + .meta)\nrecording_sglx = si.read_spikeglx(\"\u002Fdata\u002Fsession_001\", stream_name=\"imec0.ap\")\n\n# OpenEphys (binary or classic)\nrecording_oe = si.read_openephys(\"\u002Fdata\u002Foe_session\", stream_name=\"Signals CH\")\n\n# NWB file\nrecording_nwb = si.read_nwb_recording(\"\u002Fdata\u002Frecording.nwb\",\n                                       electrical_series_name=\"ElectricalSeries\")\n\n# Intan RHD\u002FRHS\nrecording_intan = si.read_intan(\"\u002Fdata\u002Fsession.rhd\", stream_name=\"RHn\")\n\n# Inspect any recording with the same API\nprint(f\"Format:       {type(recording_sglx).__name__}\")\nprint(f\"Channels:     {recording_sglx.get_num_channels()}\")\nprint(f\"Sampling rate:{recording_sglx.get_sampling_frequency()} Hz\")\nprint(f\"Duration:     {recording_sglx.get_total_duration():.1f} s\")\nprint(f\"Probe:        {recording_sglx.get_probe().name}\")\n```\n\n```python\n# List available streams before loading (useful when a file has multiple streams)\nstreams = si.get_neo_streams(\"spikeglx\", \"\u002Fdata\u002Fsession_001\")\nprint(\"Available streams:\", streams)\n# e.g. ['imec0.ap', 'imec0.lf', 'nidq']\n\n# Select a time slice (lazy, no data loaded until get_traces() is called)\nrecording_slice = recording_sglx.frame_slice(\n    start_frame=0,\n    end_frame=int(60 * recording_sglx.get_sampling_frequency()),  # first 60 s\n)\nprint(f\"Sliced duration: {recording_slice.get_total_duration():.1f} s\")\n```\n\n### Module 2: Preprocessing\n\nPreprocessing functions return new `Recording` objects wrapping the original; the chain is applied lazily when data is read. This keeps memory usage low even for multi-hour recordings.\n\n```python\nimport spikeinterface.preprocessing as spre\n\n# 1. Common median reference — removes shared noise across all channels\nrecording_cmr = spre.common_reference(recording_sglx,\n                                       reference=\"global\",\n                                       operator=\"median\")\n\n# 2. Bandpass filter for action potentials (300–6000 Hz typical)\nrecording_filt = spre.bandpass_filter(recording_cmr,\n                                       freq_min=300,\n                                       freq_max=6000)\n\n# 3. Remove bad channels automatically (coherence-based detection)\nrecording_clean, removed_ids = spre.remove_bad_channels(recording_filt,\n                                                          method=\"coherence+psd\")\nprint(f\"Removed {len(removed_ids)} bad channels: {removed_ids}\")\nprint(f\"Clean channels: {recording_clean.get_num_channels()}\")\n```\n\n```python\n# Whitening — decorrelates channels; recommended before template-matching sorters\nrecording_white = spre.whiten(recording_clean, mode=\"local\")\n\n# Phase shift correction for Neuropixels (samples acquired with small time offsets)\nrecording_shifted = spre.phase_shift(recording_clean)\n\n# Inspect a short snippet of preprocessed data\ntraces = recording_white.get_traces(start_frame=0, end_frame=3000, segment_index=0)\nprint(f\"Trace snippet shape: {traces.shape}\")   # (3000, n_channels)\nprint(f\"Trace range: [{traces.min():.2f}, {traces.max():.2f}] µV\")\n```\n\n### Module 3: Spike Sorting\n\n`ss.run_sorter()` wraps every supported sorter behind a uniform call signature. Sorter-specific parameters are passed as keyword arguments; all other pipeline steps are identical.\n\n```python\nimport spikeinterface.sorters as ss\nfrom pathlib import Path\n\n# List all sorters available in the current environment\navailable = ss.available_sorters()\nprint(\"Available sorters:\", available)\n\n# List sorters that can run without local installation (via container)\ninstalled = ss.installed_sorters()\nprint(\"Installed locally:\", installed)\n\n# Run SpykingCircus2 (CPU, no external deps)\nsorting_sc2 = ss.run_sorter(\n    \"spykingcircus2\",\n    recording_clean,\n    output_folder=Path(\".\u002Fsorter_output\u002Fsc2\"),\n    remove_existing_folder=True,\n    verbose=True,\n)\nprint(f\"SpykingCircus2 units: {len(sorting_sc2.get_unit_ids())}\")\n```\n\n```python\n# Run Kilosort4 via Docker container (no local GPU\u002FMATLAB required)\nsorting_ks4 = ss.run_sorter(\n    \"kilosort4\",\n    recording_clean,\n    output_folder=Path(\".\u002Fsorter_output\u002Fks4\"),\n    singularity_image=False,   # use Docker; set True for Singularity\n    docker_image=True,\n    remove_existing_folder=True,\n    # Kilosort4-specific parameters\n    nblocks=5,\n    Th_learned=8,\n    do_correction=True,\n)\nprint(f\"Kilosort4 units: {len(sorting_ks4.get_unit_ids())}\")\n\n# Run MountainSort5 (CPU, fast, good for tetrode\u002Flow-channel-count probes)\nsorting_ms5 = ss.run_sorter(\n    \"mountainsort5\",\n    recording_clean,\n    output_folder=Path(\".\u002Fsorter_output\u002Fms5\"),\n    scheme=\"2\",          # scheme 2 is recommended for high-density probes\n    detect_threshold=5.5,\n)\nprint(f\"MountainSort5 units: {len(sorting_ms5.get_unit_ids())}\")\n```\n\n### Module 4: Postprocessing (SortingAnalyzer)\n\n`SortingAnalyzer` is the central postprocessing object in SpikeInterface >= 0.101. It replaces the older `WaveformExtractor` and provides a unified interface for waveforms, templates, PCAs, and downstream metrics.\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.postprocessing as spost\n\n# Create analyzer (saves to disk; use format=\"memory\" for in-RAM only)\nanalyzer = si.create_sorting_analyzer(\n    sorting_sc2,\n    recording_clean,\n    folder=\".\u002Fanalyzer_sc2\",\n    format=\"binary_folder\",\n    overwrite=True,\n    sparse=True,           # sparse=True: only nearby channels per unit\n    ms_before=1.0,\n    ms_after=2.0,\n)\n\n# Compute extensions in dependency order\nanalyzer.compute([\n    \"random_spikes\",       # subsample spike indices for waveform extraction\n    \"waveforms\",           # raw waveform snippets per unit\n    \"templates\",           # mean\u002Fstd template per unit\n    \"noise_levels\",        # per-channel noise estimate\n])\n\n# Retrieve templates\ntemplates = analyzer.get_extension(\"templates\").get_data(outputs=\"Templates\")\nprint(f\"Templates object: {templates}\")\nprint(f\"Unit 0 template shape: {templates.get_one_template_dense(0).shape}\")\n# (n_samples, n_channels)\n```\n\n```python\n# Compute amplitude and PCA extensions (needed for quality metrics)\nanalyzer.compute([\n    \"spike_amplitudes\",          # amplitude at peak channel per spike\n    \"principal_components\",      # PCA scores (n_components x n_spikes)\n    \"template_similarity\",       # pairwise template correlation matrix\n    \"correlograms\",              # auto- and cross-correlograms\n    \"unit_locations\",            # estimated unit position on probe (center of mass)\n])\n\n# Access spike amplitudes for first unit\next_amp = analyzer.get_extension(\"spike_amplitudes\")\nunit_ids = analyzer.unit_ids\namps = ext_amp.get_data()[analyzer.sorting.ids_to_indices([unit_ids[0]])]\nprint(f\"Unit {unit_ids[0]} — median amplitude: {abs(amps).median():.1f} µV\")\n```\n\n### Module 5: Quality Metrics\n\nQuality metrics summarize unit isolation quality. Metrics requiring only spike times (ISI violations, firing rate) are fast; metrics requiring waveforms (SNR, amplitude cutoff) need the `SortingAnalyzer` to be populated first.\n\n```python\nimport spikeinterface.qualitymetrics as sqm\n\n# Compute a standard panel of quality metrics\nmetrics = sqm.compute_quality_metrics(\n    analyzer,\n    metric_names=[\n        \"snr\",                    # signal-to-noise ratio of template peak\n        \"isi_violation\",          # fraction of ISIs \u003C refractory period\n        \"firing_rate\",            # mean firing rate (Hz) over recording\n        \"presence_ratio\",         # fraction of time windows with ≥1 spike\n        \"amplitude_cutoff\",       # estimated fraction of spikes below threshold\n        \"nearest_neighbor\",       # isolation distance in PCA space\n        \"silhouette_score\",       # cluster separation in PCA space\n    ],\n)\nprint(metrics.head())\nprint(f\"\\nShape: {metrics.shape}\")  # (n_units, n_metrics)\n```\n\n```python\nimport pandas as pd\n\n# Apply threshold-based curation (Allen Brain Institute defaults)\nthresholds = {\n    \"snr\":                   (\">=\", 5.0),\n    \"isi_violations_ratio\":  (\"\u003C=\", 0.1),\n    \"firing_rate\":           (\">=\", 0.1),\n    \"presence_ratio\":        (\">=\", 0.9),\n    \"amplitude_cutoff\":      (\"\u003C=\", 0.1),\n}\n\nkeep = pd.Series(True, index=metrics.index)\nfor col, (op, val) in thresholds.items():\n    if col not in metrics.columns:\n        continue\n    if op == \">=\":\n        keep &= metrics[col] >= val\n    else:\n        keep &= metrics[col] \u003C= val\n\ngood_unit_ids = metrics[keep].index.tolist()\nprint(f\"Total units:   {len(metrics)}\")\nprint(f\"Curated units: {len(good_unit_ids)} ({100*len(good_unit_ids)\u002Flen(metrics):.0f}%)\")\n\n# Filter analyzer to good units\nsorting_curated = sorting_sc2.select_units(good_unit_ids)\n```\n\n### Module 6: Comparison and Export\n\nCompare sorters against each other or against ground truth, then export results in shareable formats.\n\n```python\nimport spikeinterface.comparison as sc\n\n# Compare two sorters — matches units by spike train overlap\ncomparison = sc.compare_two_sorters(\n    sorting_sc2,\n    sorting_ks4,\n    sorting1_name=\"SpykingCircus2\",\n    sorting2_name=\"Kilosort4\",\n    match_score=0.5,        # minimum overlap to count as a match\n    delta_time=0.4,         # coincidence window (ms)\n)\n\n# Performance summary per matched unit pair\nperf = comparison.get_performance(method=\"by_unit\")\nprint(perf.head(10))\n# Columns: accuracy, recall, precision, false_discovery_rate, miss_rate\n\n# Agreement score matrix (fraction overlap between all unit pairs)\nagreement_matrix = comparison.get_agreement_fraction_table()\nprint(f\"Agreement matrix shape: {agreement_matrix.shape}\")\n```\n\n```python\nimport spikeinterface.exporters as sexp\n\n# Export curated sorting to NWB (Neurodata Without Borders)\nsexp.export_to_nwb(\n    sorting_curated,\n    nwb_file_path=\".\u002Fsession_sorted.nwb\",\n    overwrite=True,\n)\nprint(\"Exported to NWB: session_sorted.nwb\")\n\n# Export to Phy for manual curation\nsexp.export_to_phy(\n    analyzer,\n    output_folder=\".\u002Fphy_export\",\n    compute_pc_features=True,\n    copy_binary=True,\n    remove_if_exists=True,\n)\nprint(\"Phy export ready at: .\u002Fphy_export\")\nprint(\"Launch Phy with: phy template-gui phy_export\u002Fparams.py\")\n```\n\n## Common Workflows\n\n### Workflow 1: Multi-Sorter Comparison on OpenEphys Data\n\n**Goal**: Load an OpenEphys recording, preprocess, run two sorters, compare their agreement, curate the higher-yield output, and export to NWB.\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.preprocessing as spre\nimport spikeinterface.sorters as ss\nimport spikeinterface.comparison as sc\nimport spikeinterface.qualitymetrics as sqm\nimport spikeinterface.exporters as sexp\nfrom pathlib import Path\n\n# --- Step 1: Load ---\ndata_dir = Path(\"\u002Fdata\u002Foe_recording\")\nstreams = si.get_neo_streams(\"openephys\", data_dir)\nprint(\"Streams:\", streams)\n\nrecording = si.read_openephys(data_dir, stream_name=\"Signals CH\")\nprint(f\"Loaded: {recording.get_num_channels()} ch, \"\n      f\"{recording.get_sampling_frequency()} Hz, \"\n      f\"{recording.get_total_duration():.1f} s\")\n\n# --- Step 2: Preprocess ---\nrec = spre.bandpass_filter(recording, freq_min=300, freq_max=6000)\nrec = spre.common_reference(rec, reference=\"global\", operator=\"median\")\nrec, bad_ids = spre.remove_bad_channels(rec, method=\"coherence+psd\")\nprint(f\"Preprocessing complete. Removed channels: {bad_ids}\")\n\n# --- Step 3: Run two sorters ---\nout = Path(\".\u002Fsorting_outputs\")\nsorting_sc2 = ss.run_sorter(\"spykingcircus2\", rec,\n                              output_folder=out \u002F \"sc2\",\n                              remove_existing_folder=True)\nsorting_tdc = ss.run_sorter(\"tridesclous2\", rec,\n                              output_folder=out \u002F \"tdc\",\n                              remove_existing_folder=True)\nprint(f\"SC2 units: {len(sorting_sc2.unit_ids)}, \"\n      f\"TDC units: {len(sorting_tdc.unit_ids)}\")\n\n# --- Step 4: Compare ---\ncmp = sc.compare_two_sorters(sorting_sc2, sorting_tdc,\n                               sorting1_name=\"SC2\",\n                               sorting2_name=\"Tridesclous2\",\n                               match_score=0.5)\nperf = cmp.get_performance(method=\"pooled_with_average\")\nprint(f\"\\nAgreement performance:\\n{perf}\")\n\n# --- Step 5: Quality metrics on SC2 (higher yield) ---\nanalyzer = si.create_sorting_analyzer(sorting_sc2, rec,\n                                        folder=\".\u002Fanalyzer_sc2\",\n                                        overwrite=True, sparse=True)\nanalyzer.compute([\"random_spikes\", \"waveforms\", \"templates\",\n                  \"noise_levels\", \"spike_amplitudes\"])\nmetrics = sqm.compute_quality_metrics(\n    analyzer,\n    metric_names=[\"snr\", \"firing_rate\", \"isi_violation\",\n                  \"presence_ratio\", \"amplitude_cutoff\"],\n)\n\nkeep = (metrics[\"snr\"] >= 5) & (metrics[\"isi_violations_ratio\"] \u003C= 0.1) \\\n     & (metrics[\"firing_rate\"] >= 0.1) & (metrics[\"presence_ratio\"] >= 0.9)\nsorting_curated = sorting_sc2.select_units(metrics[keep].index.tolist())\nprint(f\"\\nCurated: {len(sorting_curated.unit_ids)} \u002F {len(sorting_sc2.unit_ids)} units\")\n\n# --- Step 6: Export winner to NWB ---\nsexp.export_to_nwb(sorting_curated,\n                    nwb_file_path=\".\u002Fsession_sorted.nwb\",\n                    overwrite=True)\nprint(\"Saved: session_sorted.nwb\")\n```\n\n### Workflow 2: Ground Truth Validation with Synthetic Recordings\n\n**Goal**: Generate a synthetic recording with known spike trains, run a sorter, and measure true accuracy (recall, precision) against ground truth — for benchmarking sorters or testing preprocessing pipelines.\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.preprocessing as spre\nimport spikeinterface.sorters as ss\nimport spikeinterface.comparison as sc\nimport numpy as np\n\n# --- Step 1: Generate ground-truth synthetic recording ---\n# Uses a Marsaglia noise model with realistic waveform templates\nrecording_gt, sorting_gt = si.generate_ground_truth_recording(\n    durations=[120.0],             # 120 s recording\n    sampling_frequency=30000.0,\n    num_channels=32,\n    num_units=10,\n    noise_kwargs={\"noise_level\": 10.0, \"dtype\": \"float32\"},\n    seed=42,\n)\nprint(f\"GT recording: {recording_gt.get_num_channels()} ch, \"\n      f\"{recording_gt.get_total_duration():.0f} s\")\nprint(f\"GT units: {len(sorting_gt.unit_ids)}\")\nprint(f\"GT firing rates: \"\n      f\"{[round(len(sorting_gt.get_unit_spike_train(u, 0))\u002F120, 1) for u in sorting_gt.unit_ids]} Hz\")\n\n# --- Step 2: Preprocess ---\nrec_pp = spre.bandpass_filter(recording_gt, freq_min=300, freq_max=6000)\nrec_pp = spre.common_reference(rec_pp, reference=\"global\", operator=\"median\")\n\n# --- Step 3: Sort with two sorters ---\nsorting_sc2 = ss.run_sorter(\"spykingcircus2\", rec_pp,\n                              output_folder=\".\u002Fgt_sc2\",\n                              remove_existing_folder=True)\nsorting_ms5 = ss.run_sorter(\"mountainsort5\", rec_pp,\n                              output_folder=\".\u002Fgt_ms5\",\n                              remove_existing_folder=True,\n                              scheme=\"2\")\n\n# --- Step 4: Compare each sorter against ground truth ---\nfor name, sorting_test in [(\"SC2\", sorting_sc2), (\"MS5\", sorting_ms5)]:\n    cmp = sc.compare_sorter_to_ground_truth(sorting_gt, sorting_test,\n                                              exhaustive_gt=True)\n    perf = cmp.get_performance(method=\"pooled_with_average\")\n    print(f\"\\n{name} vs Ground Truth:\")\n    print(f\"  Accuracy:  {perf['accuracy']:.3f}\")\n    print(f\"  Recall:    {perf['recall']:.3f}\")\n    print(f\"  Precision: {perf['precision']:.3f}\")\n    print(f\"  Well-detected units: {cmp.get_well_detected_units(well_detected_score=0.8)}\")\n```\n\n### Workflow 3: Batch Processing Multiple Sessions\n\n**Goal**: Apply the same preprocessing + sorting pipeline to multiple recording sessions and collect quality metrics across all sessions.\n\n```python\nimport spikeinterface.full as si\nimport spikeinterface.preprocessing as spre\nimport spikeinterface.sorters as ss\nimport spikeinterface.qualitymetrics as sqm\nimport pandas as pd\nfrom pathlib import Path\n\nsessions = list(Path(\"\u002Fdata\u002Fexperiment\").glob(\"session_*\u002F\"))\nall_metrics = []\n\nfor session_dir in sessions:\n    print(f\"Processing {session_dir.name} ...\")\n    try:\n        streams = si.get_neo_streams(\"spikeglx\", session_dir)\n        ap_stream = [s for s in streams if \"ap\" in s][0]\n        rec = si.read_spikeglx(session_dir, stream_name=ap_stream)\n\n        # Preprocess\n        rec = spre.bandpass_filter(\n            spre.common_reference(rec, reference=\"global\", operator=\"median\"),\n            freq_min=300, freq_max=6000,\n        )\n        rec, _ = spre.remove_bad_channels(rec)\n\n        # Sort\n        out_dir = session_dir \u002F \"sorting\"\n        sorting = ss.run_sorter(\"spykingcircus2\", rec,\n                                 output_folder=out_dir,\n                                 remove_existing_folder=True)\n\n        # Compute metrics\n        analyzer = si.create_sorting_analyzer(\n            sorting, rec, folder=session_dir \u002F \"analyzer\", overwrite=True, sparse=True\n        )\n        analyzer.compute([\"random_spikes\", \"waveforms\", \"templates\",\n                          \"noise_levels\", \"spike_amplitudes\"])\n        m = sqm.compute_quality_metrics(\n            analyzer, metric_names=[\"snr\", \"firing_rate\", \"isi_violation\"]\n        )\n        m[\"session\"] = session_dir.name\n        all_metrics.append(m)\n\n    except Exception as e:\n        print(f\"  FAILED: {e}\")\n        continue\n\n# Combine across sessions\ncombined = pd.concat(all_metrics)\ncombined.to_csv(\"all_sessions_metrics.csv\")\nprint(f\"\\nSaved metrics: {combined.shape[0]} units across {len(all_metrics)} sessions\")\nprint(combined.groupby(\"session\")[[\"snr\", \"firing_rate\"]].median())\n```\n\n## Key Parameters\n\n| Parameter | Module \u002F Function | Default | Range \u002F Options | Effect |\n|-----------|-------------------|---------|-----------------|--------|\n| `freq_min` \u002F `freq_max` | `spre.bandpass_filter` | 300 \u002F 6000 Hz | 150–500 \u002F 3000–10000 Hz | Spike band; use 300–6000 Hz for AP activity |\n| `reference` | `spre.common_reference` | `\"global\"` | `\"global\"`, `\"local\"`, `\"single\"` | Channel subset used for median reference subtraction |\n| `method` | `spre.remove_bad_channels` | `\"coherence+psd\"` | `\"coherence+psd\"`, `\"std\"`, `\"mad\"` | Algorithm for bad channel detection |\n| `scheme` | `ss.run_sorter(\"mountainsort5\")` | `\"2\"` | `\"1\"`, `\"2\"`, `\"3\"` | Sorting scheme; scheme 2 recommended for high-density probes |\n| `nblocks` | `ss.run_sorter(\"kilosort4\")` | `5` | `0–10` | Number of drift correction blocks; 0 disables drift correction |\n| `Th_learned` | `ss.run_sorter(\"kilosort4\")` | `8` | `6–12` | Detection threshold (× noise); lower = more units, more noise |\n| `match_score` | `sc.compare_two_sorters` | `0.5` | `0.1–0.9` | Minimum spike-train overlap to declare a unit match |\n| `sparse` | `si.create_sorting_analyzer` | `True` | `True`, `False` | Limit waveform extraction to channels near each unit; reduces memory |\n| `ms_before` \u002F `ms_after` | `si.create_sorting_analyzer` | `1.0` \u002F `2.0` ms | 0.5–2.0 \u002F 1.0–3.0 ms | Waveform snippet window relative to detected spike peak |\n| `snr` threshold | `sqm.compute_quality_metrics` | — | 5–10 recommended | Amplitude \u002F noise ratio; > 5 indicates well-isolated unit |\n| `isi_violations_ratio` | `sqm.compute_quality_metrics` | — | ≤ 0.1 recommended | Fraction of ISIs \u003C refractory period (1.5 ms); \u003C 0.1 = single unit |\n| `presence_ratio` | `sqm.compute_quality_metrics` | — | ≥ 0.9 recommended | Fraction of recording epochs where unit fires; \u003C 0.9 = drifting unit |\n\n## Best Practices\n\n1. **Always inspect available streams before loading**: Different acquisition systems save AP data, LFP data, and auxiliary channels as separate streams. Loading the wrong stream silently yields valid-looking but incorrect data.\n   ```python\n   streams = si.get_neo_streams(\"spikeglx\", data_dir)\n   print(streams)  # e.g. ['imec0.ap', 'imec0.lf', 'nidq']\n   recording = si.read_spikeglx(data_dir, stream_name=\"imec0.ap\")\n   ```\n\n2. **Chain preprocessing lazily; do not load to memory early**: Preprocessing objects are lazy and apply transformations at read time. Calling `get_traces()` on the raw recording before preprocessing will load unfiltered data into RAM unnecessarily. Build the full chain before any data access.\n\n3. **Use `sparse=True` when creating a SortingAnalyzer**: For high-channel-count probes (64–384 channels), dense waveform extraction is 10–50× more expensive in RAM and disk than sparse. Sparse mode extracts waveforms only on the channels nearest each unit.\n\n4. **Run containerized sorters to avoid dependency conflicts**: Kilosort2\u002F3 (MATLAB), IronClust, and other sorters have complex dependencies. Use `docker_image=True` in `run_sorter()` to pull the official container and run the sorter in isolation:\n   ```python\n   sorting = ss.run_sorter(\"kilosort2_5\", recording_clean,\n                            output_folder=\".\u002Fks25_out\",\n                            docker_image=True)\n   ```\n\n5. **Compute metrics extensions in dependency order**: Extensions depend on each other. The canonical order is: `random_spikes` → `waveforms` → `templates` → `noise_levels` → `spike_amplitudes` → `principal_components`. Skipping an earlier step causes a `MissingExtensionError` when a downstream step is requested.\n\n6. **Save the SortingAnalyzer to disk for large recordings**: In-memory analyzers (`format=\"memory\"`) are lost when the process exits. For recordings longer than 30 minutes or with many units, always specify a `folder` path so the analyzer can be reloaded:\n   ```python\n   analyzer = si.load_sorting_analyzer(\".\u002Fanalyzer_sc2\")\n   ```\n\n7. **Do not compare sorters with mismatched preprocessing**: When benchmarking sorters, run all of them on the same preprocessed `recording_clean` object. Running sorters on different preprocessing chains invalidates the comparison.\n\n## Common Recipes\n\n### Recipe: Load and Inspect a Multi-Stream Recording\n\nWhen to use: Quickly check what streams are available in an unfamiliar recording and confirm channel counts and duration before committing to a full sort.\n\n```python\nimport spikeinterface.full as si\n\ndata_dir = \"\u002Fdata\u002Frecording_session\"\n\n# Try SpikeGLX first; if it fails, try OpenEphys\ntry:\n    streams = si.get_neo_streams(\"spikeglx\", data_dir)\n    fmt = \"spikeglx\"\nexcept Exception:\n    streams = si.get_neo_streams(\"openephys\", data_dir)\n    fmt = \"openephys\"\n\nprint(f\"Format: {fmt}\")\nprint(f\"Streams: {streams}\")\n\nfor stream in streams:\n    try:\n        rec = si.read_spikeglx(data_dir, stream_name=stream) if fmt == \"spikeglx\" \\\n              else si.read_openephys(data_dir, stream_name=stream)\n        print(f\"  {stream}: {rec.get_num_channels()} ch, \"\n              f\"{rec.get_sampling_frequency()} Hz, \"\n              f\"{rec.get_total_duration():.1f} s\")\n    except Exception as e:\n        print(f\"  {stream}: could not load ({e})\")\n```\n\n### Recipe: Export Quality Metrics Report to CSV\n\nWhen to use: After running quality metrics, save a tidy CSV summarizing all units with their metrics and a pass\u002Ffail column for downstream analysis or sharing with collaborators.\n\n```python\nimport spikeinterface.qualitymetrics as sqm\nimport pandas as pd\n\nmetrics = sqm.compute_quality_metrics(\n    analyzer,\n    metric_names=[\"snr\", \"firing_rate\", \"isi_violation\",\n                  \"presence_ratio\", \"amplitude_cutoff\"],\n)\n\n# Add pass\u002Ffail column based on standard thresholds\nmetrics[\"pass_qc\"] = (\n    (metrics[\"snr\"] >= 5) &\n    (metrics[\"isi_violations_ratio\"] \u003C= 0.1) &\n    (metrics[\"firing_rate\"] >= 0.1) &\n    (metrics[\"presence_ratio\"] >= 0.9) &\n    (metrics[\"amplitude_cutoff\"] \u003C= 0.1)\n)\n\nmetrics.to_csv(\"unit_quality_metrics.csv\")\nn_pass = metrics[\"pass_qc\"].sum()\nprint(f\"QC report saved: {len(metrics)} total units, {n_pass} pass ({100*n_pass\u002Flen(metrics):.0f}%)\")\nprint(metrics[metrics[\"pass_qc\"]].describe())\n```\n\n### Recipe: Probe Geometry Visualization\n\nWhen to use: Verify that the probe channel map loaded correctly before sorting. Incorrect channel maps silently degrade sorting quality on high-density probes.\n\n```python\nimport spikeinterface.full as si\nimport matplotlib.pyplot as plt\nimport probeinterface.plotting as pp\n\nrecording = si.read_spikeglx(\"\u002Fdata\u002Fsession_001\", stream_name=\"imec0.ap\")\nprobe = recording.get_probe()\nprint(f\"Probe name: {probe.name}\")\nprint(f\"N contacts: {probe.get_contact_count()}\")\nprint(f\"Contact positions (first 5):\\n{probe.contact_positions[:5]}\")\n\nfig, ax = plt.subplots(figsize=(3, 10))\npp.plot_probe(probe, ax=ax, with_channel_index=True)\nax.set_title(f\"{probe.name} — channel map\")\nplt.tight_layout()\nplt.savefig(\"probe_geometry.png\", dpi=150)\nprint(\"Saved probe_geometry.png\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `ValueError: stream_name not found` | Recording has multiple streams; none is specified | Run `si.get_neo_streams(format, path)` to list available streams; pass the correct one to the reader |\n| Sorter output has zero units | Detection threshold too high, or preprocessing removed all signal | Verify `recording_clean.get_traces()` returns non-zero data; lower detection threshold (e.g. `Th_learned=6` for Kilosort4) |\n| `MissingExtensionError` | Analyzer extension depends on an uncomputed prerequisite | Follow the canonical compute order: `random_spikes` → `waveforms` → `templates` → `noise_levels` → `spike_amplitudes` |\n| Docker sorter hangs at startup | Docker daemon not running or image not pulled | Run `docker ps` to confirm Docker is running; pull image manually with `docker pull spikeinterface\u002Fkilosort4-compiled-base` |\n| `MemoryError` during waveform extraction | Dense extraction on high-channel-count probe | Use `sparse=True` in `create_sorting_analyzer`; reduce `max_spikes_per_unit` (default 500) |\n| Bad channel detection removes too many channels | Threshold too aggressive or short recording | Set `method=\"std\"` for a simpler threshold; increase `bad_threshold` parameter |\n| Unit comparison shows 0% agreement between sorters | Delta time window too narrow or match score too strict | Increase `delta_time` (default 0.4 ms) and lower `match_score` (try 0.3) |\n| NWB export raises `TypeError` on unit properties | Sorting contains non-serializable properties from sorter | Remove problematic properties: `sorting.remove_unit_property(\"property_name\")` before export |\n| `read_spikeglx` fails on LF stream | LFP stream uses different file suffix (`.lf.bin`) | Specify `stream_name=\"imec0.lf\"` explicitly; confirm file exists with `ls data_dir\u002F*.lf.bin` |\n\n## Related Skills\n\n- **neuropixels-analysis** — Neuropixels-specific pipeline using SpikeInterface + Kilosort4 with PSTH, tuning curves, and population decoding for rodent and primate experiments\n- **neurokit2** — For biosignal processing (ECG, EEG, EDA, EMG, PPG) rather than spike sorting; use when data is not extracellular electrophysiology\n\n## References\n\n- [SpikeInterface documentation](https:\u002F\u002Fspikeinterface.readthedocs.io\u002F) — full API reference, tutorials, and sorter-specific guides\n- [SpikeInterface GitHub](https:\u002F\u002Fgithub.com\u002FSpikeInterface\u002Fspikeinterface) — source code, changelogs, and issue tracker\n- [Buccino et al. (2020), eLife — SpikeInterface paper](https:\u002F\u002Fdoi.org\u002F10.7554\u002FeLife.61834) — unified framework design and benchmarks across sorters\n- [ProbeInterface documentation](https:\u002F\u002Fprobeinterface.readthedocs.io\u002F) — probe geometry handling and channel map formats\n- [SpikeInterface sorter list](https:\u002F\u002Fspikeinterface.readthedocs.io\u002Fen\u002Flatest\u002Fmodules\u002Fsorters.html) — supported sorters, requirements, and container images\n- [NWB documentation](https:\u002F\u002Fwww.nwb.org\u002F) — Neurodata Without Borders format for neurophysiology data sharing\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Fspikeinterface-electrophysiology",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill spikeinterface-electrophysiology",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill spikeinterface-electrophysiology",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill spikeinterface-electrophysiology","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fspikeinterface-electrophysiology\u002FSKILL.md",true,[],[49,57,64,71,78,85],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":56},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":56},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":56},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":56},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":56},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":56},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]