Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update LaminDB, Pennylane and Neuropixles skills

Timothy Kassisb2a969eb56d9
diff --git a/docs/skills.md b/docs/skills.md
index a47a72c1..1ec8e6a0 100644
--- a/docs/skills.md
+++ b/docs/skills.md
@@ -60,7 +60,7 @@
- **Zarr** - Python library (Zarr-Python 3.x) implementing chunked, compressed N-dimensional arrays for local disk and cloud object storage (S3, GCS via fsspec). Supports Zarr format 2 and 3, `zarr.codecs` compression (Blosc, gzip, zstd), partial chunk reads, consolidated metadata, sharding, and integration with NumPy, Dask, and Xarray. Use for out-of-core arrays, cloud-native pipelines, and large scientific datasets (genomics, imaging, climate). Skill: `zarr-python`
### Data Management & Infrastructure
-- **LaminDB** - Open-source data framework for biology that makes data queryable, traceable, reproducible, and FAIR (Findable, Accessible, Interoperable, Reusable). Provides unified platform combining lakehouse architecture, lineage tracking, feature stores, biological ontologies (via Bionty plugin with 20+ ontologies: genes, proteins, cell types, tissues, diseases, pathways), LIMS, and ELN capabilities through a single Python API. Key features include: automatic data lineage tracking (code, inputs, outputs, environment), versioned artifacts (DataFrame, AnnData, SpatialData, Parquet, Zarr), schema validation and data curation with standardization/synonym mapping, queryable metadata with feature-based filtering, cross-registry traversal, and streaming for large datasets. Supports integrations with workflow managers (Nextflow, Snakemake, Redun), MLOps platforms (Weights & Biases, MLflow, HuggingFace, scVI-tools), cloud storage (S3, GCS, S3-compatible), array stores (TileDB-SOMA, DuckDB), and visualization (Vitessce). Deployment options: local SQLite, cloud storage with SQLite, or cloud storage with PostgreSQL for production. Use cases: scRNA-seq standardization and analysis, flow cytometry/spatial data management, multi-modal dataset integration, computational workflow tracking with reproducibility, biological ontology-based annotation, data lakehouse construction for unified queries, ML pipeline integration with experiment tracking, and FAIR-compliant dataset publishing
+- **LaminDB** - Open-source lineage-native lakehouse for biology that makes datasets and models queryable, traceable, validated, reproducible, and FAIR. Covers LaminDB 2.x setup, artifact and collection registration, feature-based query/search, lineage tracking with `ln.track()`/`ln.finish()` and `@ln.flow()`/`@ln.step()`, schema validation for DataFrame/AnnData/SpatialData/TileDB-SOMA, and ontology-backed annotation with Bionty 2.x. Includes current guidance for projects, branches, spaces, storage backends (local, S3, GCS, S3-compatible, Hugging Face), SQLite/Postgres deployment, safe credential handling, external-data validation, and integrations with Nextflow/nf-lamin, Snakemake, Redun, W&B, MLflow, Lightning, scVI-tools, DuckDB, and Vitessce.
- **Modal** - Serverless cloud platform for running Python code with minimal configuration, specialized for AI/ML workloads and scientific computing. Execute functions on powerful GPUs (T4, L4, A10, A100, L40S, H100, H200, B200, B200+), scale automatically from zero to thousands of containers, and pay only for compute used. Key features include: declarative container image building with uv (recommended)/pip/apt package management, automatic autoscaling with configurable limits and buffer containers, GPU acceleration with multi-GPU support (up to 8 GPUs per container, up to 1,536 GB VRAM), persistent storage via Volumes (v1 and v2) for model weights and datasets, secret management for API keys and credentials, scheduled jobs with cron expressions, web endpoints for deploying serverless APIs (FastAPI, ASGI, WSGI, WebSockets), parallel execution with `.map()` for batch processing, input concurrency and dynamic batching for I/O-bound workloads, Sandboxes for isolated execution of untrusted or agent-generated code with network (CIDR) restrictions, and resource configuration (CPU cores, memory, ephemeral disk up to 3 TiB). Supports custom Docker images, Micromamba/Conda environments, integration with Hugging Face/Weights & Biases, and distributed multi-GPU training. Free tier includes $30/month credits. Use cases: ML model deployment and inference (LLMs, image generation, speech, embeddings), GPU-accelerated training and fine-tuning, batch processing large datasets in parallel, scheduled compute-intensive jobs, serverless API deployment with autoscaling, protein folding and computational biology, scientific computing requiring distributed compute or specialized hardware, and data pipeline automation
- **Optimize for GPU** - GPU-accelerate Python code using the NVIDIA RAPIDS ecosystem and related libraries for 10x–1000x speedups on suitable workloads. Covers 12 GPU libraries with decision framework for choosing the right tool: CuPy (drop-in NumPy/SciPy replacement for array operations, FFT, linear algebra), Numba CUDA (custom GPU kernels with fine-grained thread/block/shared-memory control), Warp (JIT-compiled simulation kernels with built-in spatial types for physics, mesh ray casting, differentiable programming, and robotics), cuDF (drop-in pandas replacement for dataframe ETL, groupby, joins), cuML (drop-in scikit-learn replacement for classification, regression, clustering, dimensionality reduction, preprocessing), cuGraph (drop-in NetworkX replacement for PageRank, centrality, community detection, shortest paths), KvikIO (GPUDirect Storage for high-performance file IO bypassing CPU memory, S3/HTTP direct-to-GPU reads, Zarr GPU backend), cuxfilter (GPU-accelerated interactive cross-filtering dashboards with Bokeh, Datashader, and Deck.gl), cuCIM (drop-in scikit-image replacement for image filtering, morphology, segmentation, plus fast whole-slide image reading for digital pathology), cuVS (GPU-accelerated vector/similarity search with CAGRA, IVF-Flat, IVF-PQ for RAG and recommender systems), cuSpatial (GPU-accelerated GeoPandas replacement for spatial joins, point-in-polygon, trajectory analysis), and RAFT/pylibraft (sparse eigensolvers, device memory management, multi-GPU communication). All libraries interoperate via CUDA Array Interface for zero-copy data sharing. Includes optimization workflow (profile first, assess GPU suitability, start with drop-in replacements, minimize host-device transfers), code transformation patterns for each library, memory management principles, and common pitfalls. Use cases: accelerating NumPy/pandas/scikit-learn/NetworkX/scikit-image/GeoPandas/Faiss workloads, physics simulation, differentiable rendering, particle systems, vector search for RAG pipelines, GPUDirect Storage file IO, interactive data exploration dashboards, geospatial analysis, medical imaging, and sparse eigenvalue problems
@@ -95,7 +95,7 @@
### Neuroscience & Electrophysiology
- **BIDS** - Brain Imaging Data Structure (BIDS) standard for organizing and describing neuroscience and biomedical research datasets. While originating for MRI, BIDS now covers 11 modalities: imaging (MRI structural/functional/diffusion/perfusion, PET, microscopy), electrophysiology (EEG, MEG, iEEG, EMG), and other data (NIRS, motion capture, behavioral, MR spectroscopy), with active BEPs extending to microelectrode electrophysiology (Neuropixels), stimuli, and more. Covers the BIDS directory hierarchy, file naming conventions with entities (subject, session, task, acquisition, run, etc.), and JSON sidecar metadata. Key features include: dataset creation and validation workflows, querying BIDS datasets with PyBIDS (BIDSLayout), DICOM-to-BIDS conversion using HeuDiConv (ReproIn turnkey, map-into-reproin, and custom heuristic modes), dcm2bids (config-file-based), and BIDScoin (GUI-based), metadata inheritance and sidecar management, events files for task fMRI, participants and scans TSV files, BIDS derivatives conventions for preprocessed data and analysis outputs, BIDS-Apps interface (fMRIPrep, MRIQC, QSIPrep), machine-readable BIDS schema (bids_schema.json) and BEP listing (beps.yml) with update script, and .bidsignore configuration. Includes detailed reference documentation for the complete BIDS specification entity table (35 entities in schema ordering), required and recommended metadata fields for every modality, standard template spaces, and conversion tool workflows with examples. Use cases: organizing neuroscience data for sharing and analysis, validating BIDS compliance before repository submission (OpenNeuro, DANDI), converting DICOM scanner data to BIDS format, creating BIDS-compliant derivatives, querying datasets programmatically, and preparing data for BIDS-Apps processing pipelines
-- **Neuropixels-Analysis** - Comprehensive toolkit for analyzing Neuropixels high-density neural recordings using SpikeInterface, Allen Institute, and International Brain Laboratory (IBL) best practices. Supports the full workflow from raw data to publication-ready curated units. Key features include: data loading from SpikeGLX, Open Ephys, and NWB formats, preprocessing pipelines (highpass filtering, phase shift correction for Neuropixels 1.0, bad channel detection, common average referencing), motion/drift estimation and correction (kilosort_like and nonrigid_accurate presets), spike sorting integration (Kilosort4 GPU, SpykingCircus2, Mountainsort5 CPU), comprehensive postprocessing (waveform extraction, template computation, spike amplitudes, correlograms, unit locations), quality metrics computation (SNR, ISI violations, presence ratio, amplitude cutoff, drift metrics), automated curation using Allen Institute and IBL criteria with configurable thresholds, AI-assisted visual curation for uncertain units using Claude API, and export to Phy for manual review or NWB for sharing. Supports Neuropixels 1.0 (960 electrodes, 384 channels) and Neuropixels 2.0 (single and 4-shank configurations). Use cases: extracellular electrophysiology analysis, spike sorting from silicon probes, neural population recordings, systems neuroscience research, unit quality assessment, publication-ready neural data processing, and integration of AI-assisted curation for borderline units
+- **Neuropixels-Analysis** - Comprehensive toolkit for analyzing Neuropixels high-density neural recordings using SpikeInterface, Allen Institute, and International Brain Laboratory (IBL) best practices. Supports the full workflow from raw data to publication-ready curated units. Key features include: data loading from SpikeGLX, Open Ephys, and NWB formats, preprocessing pipelines (highpass filtering, phase shift correction for Neuropixels 1.0, bad channel detection, common average referencing), motion/drift estimation and correction (nonrigid_fast_and_accurate, nonrigid_accurate, and DREDge presets), spike sorting integration (Kilosort4 GPU, SpykingCircus2, Tridesclous2, Mountainsort5 CPU), comprehensive postprocessing (waveform extraction, template computation, spike amplitudes, correlograms, unit locations), quality metrics computation (SNR, ISI violations, presence ratio, amplitude cutoff, drift metrics), automated curation using Allen Institute and IBL criteria with configurable thresholds, model-based curation with pretrained UnitRefine classifiers (noise/neural and SUA/MUA) loaded from Hugging Face via spikeinterface.curation, AI-assisted visual curation for uncertain units using vision-language models, and export to Phy for manual review or NWB for sharing. Supports Neuropixels 1.0 (960 electrodes, 384 channels) and Neuropixels 2.0 (single and 4-shank configurations). Use cases: extracellular electrophysiology analysis, spike sorting from silicon probes, neural population recordings, systems neuroscience research, unit quality assessment, publication-ready neural data processing, and integration of AI-assisted curation for borderline units
### Protein Engineering & Design
- **Adaptyv** - Cloud laboratory platform for automated protein testing and validation. Submit protein sequences via API or web interface and receive experimental results in approximately 21 days. Supports multiple assay types including binding assays (biolayer interferometry for protein-target interactions, KD/kon/koff measurements), expression testing (quantify protein expression levels in E. coli, mammalian, yeast, or insect cells), thermostability measurements (DSF and CD for Tm determination and thermal stability profiling), and enzyme activity assays (kinetic parameters, substrate specificity, inhibitor testing). Includes computational optimization tools for pre-screening sequences: NetSolP/SoluProt for solubility prediction, SolubleMPNN for sequence redesign to improve expression, ESM for sequence likelihood scoring, ipTM (AlphaFold-Multimer) for interface stability assessment, and pSAE for aggregation risk quantification. Platform features automated workflows from expression through purification to assay execution with quality control, webhook notifications for experiment completion, batch submission support for high-throughput screening, and comprehensive results with kinetic parameters, confidence metrics, and raw data access. Use cases: antibody affinity maturation, therapeutic protein developability assessment, enzyme engineering and optimization, protein stability improvement, AI-driven protein design validation, library screening for expression and function, lead optimization with experimental feedback, and integration of computational design with wet-lab validation in iterative design-build-test-learn cycles
diff --git a/skills/lamindb/SKILL.md b/skills/lamindb/SKILL.md
index 30c3ec45..a2e8baf1 100644
--- a/skills/lamindb/SKILL.md
+++ b/skills/lamindb/SKILL.md
@@ -1,9 +1,9 @@
---
name: lamindb
-description: This skill should be used when working with LaminDB, an open-source data framework for biology that makes data queryable, traceable, reproducible, and FAIR. Use when managing biological datasets (scRNA-seq, spatial, flow cytometry, etc.), tracking computational workflows, curating and validating data with biological ontologies, building data lakehouses, or ensuring data lineage and reproducibility in biological research. Covers data management, annotation, ontologies (genes, cell types, diseases, tissues), schema validation, integrations with workflow managers (Nextflow, Snakemake) and MLOps platforms (W&B, MLflow), and deployment strategies.
+description: Use when working with LaminDB, the open-source lineage-native lakehouse for biological datasets and models. Covers setup, artifact registration, query/search, lineage tracking, validation, ontology-backed annotation with Bionty, collections, branches, storage, and workflow integrations.
license: Apache-2.0 license
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,25 +11,26 @@ metadata:
## Overview
-LaminDB is an open-source data framework for biology designed to make data queryable, traceable, reproducible, and FAIR (Findable, Accessible, Interoperable, Reusable). It provides a unified platform that combines lakehouse architecture, lineage tracking, feature stores, biological ontologies, LIMS (Laboratory Information Management System), and ELN (Electronic Lab Notebook) capabilities through a single Python API.
+LaminDB is an open-source, lineage-native lakehouse for biology. It makes datasets and models queryable, traceable, validated, reproducible, and FAIR (Findable, Accessible, Interoperable, Reusable) while storing data in open formats across local filesystems, S3, GCS, Hugging Face, SQLite, and Postgres.
**Core Value Proposition:**
-- **Queryability**: Search and filter datasets by metadata, features, and ontology terms
-- **Traceability**: Automatic lineage tracking from raw data through analysis to results
-- **Reproducibility**: Version control for data, code, and environment
-- **FAIR Compliance**: Standardized annotations using biological ontologies
+- **Queryability**: Search and filter artifacts, records, runs, features, schemas, and collections
+- **Traceability**: Track inputs, outputs, parameters, source code, and environments for notebooks, scripts, functions, and pipelines
+- **Validation**: Curate DataFrame, AnnData, SpatialData, TileDB-SOMA, Parquet, Zarr, and other biological formats with schemas
+- **FAIR Compliance**: Standardize annotations with Bionty-backed ontologies and custom registries
+- **Change management**: Organize work with projects, branches, spaces, collections, and saved notes or plans
## When to Use This Skill
Use this skill when:
- **Managing biological datasets**: scRNA-seq, bulk RNA-seq, spatial transcriptomics, flow cytometry, multi-modal data, EHR data
-- **Tracking computational workflows**: Notebooks, scripts, pipeline execution (Nextflow, Snakemake, Redun)
+- **Tracking computational workflows**: Notebooks, scripts, functions, shell scripts, and pipeline execution (Nextflow, Snakemake, Redun)
- **Curating and validating data**: Schema validation, standardization, ontology-based annotation
- **Working with biological ontologies**: Genes, proteins, cell types, tissues, diseases, pathways (via Bionty)
- **Building data lakehouses**: Unified query interface across multiple datasets
- **Ensuring reproducibility**: Automatic versioning, lineage tracking, environment capture
-- **Integrating ML pipelines**: Connecting with Weights & Biases, MLflow, HuggingFace, scVI-tools
+- **Integrating ML pipelines**: Connecting with Weights & Biases, MLflow, Hugging Face, Lightning, scVI-tools
- **Deploying data infrastructure**: Setting up local or cloud-based data management systems
- **Collaborating on datasets**: Sharing curated, annotated data with standardized metadata
@@ -41,14 +42,17 @@ LaminDB provides six interconnected capability areas, each documented in detail
**Core entities:**
- **Artifacts**: Versioned datasets (DataFrame, AnnData, Parquet, Zarr, etc.)
-- **Records**: Experimental entities (samples, perturbations, instruments)
+- **Records & ULabels**: Experimental entities, typed records, and simple labels
+- **Collections**: Versioned, immutable sets of artifacts
- **Runs & Transforms**: Computational lineage tracking (what code produced what data)
- **Features**: Typed metadata fields for annotation and querying
+- **Projects, Branches & Spaces**: Project grouping, change management, and access boundaries
**Key workflows:**
- Create and version artifacts from files or Python objects
- Track notebook/script execution with `ln.track()` and `ln.finish()`
-- Annotate artifacts with typed features
+- Track function workflows with `@ln.flow()` and `@ln.step()`
+- Annotate artifacts with records, ulabels, projects, and typed features
- Visualize data lineage graphs with `artifact.view_lineage()`
- Query by provenance (find all outputs from specific code/inputs)
@@ -60,10 +64,10 @@ LaminDB provides six interconnected capability areas, each documented in detail
- Registry exploration and lookup with auto-complete
- Single record retrieval with `get()`, `one()`, `one_or_none()`
- Filtering with comparison operators (`__gt`, `__lte`, `__contains`, `__startswith`)
-- Feature-based queries (query by annotated metadata)
+- Feature-based queries, including expression-style queries with `Feature` objects
- Cross-registry traversal with double-underscore syntax
- Full-text search across registries
-- Advanced logical queries with Q objects (AND, OR, NOT)
+- Advanced logical queries with `ln.Q` objects (AND, OR, NOT)
- Streaming large datasets without loading into memory
**Key workflows:**
@@ -96,7 +100,7 @@ LaminDB provides six interconnected capability areas, each documented in detail
**Key workflows:**
- Define features and schemas for data validation
-- Use `DataFrameCurator` or `AnnDataCurator` for validation
+- Use `DataFrameCurator`, `AnnDataCurator`, `SpatialDataCurator`, or `TiledbsomaExperimentCurator` for validation
- Standardize values with `.cat.standardize()`
- Map to ontologies with `.cat.add_ontology()`
- Save curated artifacts with schema linkage
@@ -132,11 +136,12 @@ LaminDB provides six interconnected capability areas, each documented in detail
- Nextflow: Track pipeline processes and outputs
- Snakemake: Integrate into Snakemake rules
- Redun: Combine with Redun task tracking
+- Lightning: Persist checkpoints and training metadata
**MLOps platforms:**
- Weights & Biases: Link experiments with data artifacts
- MLflow: Track models and experiments
-- HuggingFace: Track model fine-tuning
+- Hugging Face: Track model fine-tuning
- scVI-tools: Single-cell analysis workflows
**Storage systems:**
@@ -160,9 +165,12 @@ LaminDB provides six interconnected capability areas, each documented in detail
### 6. Setup and Deployment
**Installation:**
-- Basic: `uv pip install lamindb`
-- With extras: `uv pip install 'lamindb[gcp,zarr,fcs]'`
-- Modules: bionty, wetlab, clinical
+- Current stable baseline: `lamindb==2.5.1` (released 2026-06-01; Python >=3.10, <=3.14)
+- Basic: `uv pip install 'lamindb==2.5.1'`
+- With extras: `uv pip install 'lamindb[gcp,zarr-v2,fcs]==2.5.1'`
+- Minimal namespace only: `uv pip install 'lamindb-core==2.5.1'`
+- Bionty module: included in the LaminDB docs and available as `uv pip install 'bionty==2.4.0'`
+- Optional modules: pin reviewed releases for wetlab or clinical schema modules rather than installing floating latest versions
**Instance types:**
- Local SQLite (development)
@@ -179,7 +187,7 @@ LaminDB provides six interconnected capability areas, each documented in detail
- Cache management for cloud files
- Multi-user system configurations
- Git repository sync
-- Environment variables
+- Named environment variables for credentials and connection URLs
**Deployment patterns:**
- Local dev → Cloud production migration
@@ -188,6 +196,15 @@ LaminDB provides six interconnected capability areas, each documented in detail
**Reference:** `references/setup-deployment.md` - Read this for detailed installation, configuration, storage setup, database management, security best practices, and troubleshooting.
+## Safety and Security Defaults
+
+When helping with LaminDB setup or integrations:
+
+- Never display, log, or transmit actual API keys, cloud credentials, database passwords, or full connection strings that include secrets.
+- Prefer IAM roles, workload identity, secret managers, or named environment variables such as `LAMIN_DB_URL`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `GOOGLE_APPLICATION_CREDENTIALS`; only check whether a named variable is present, not its value.
+- Before saving content from REST APIs, external databases, or user-provided files, validate and sanitize it with an explicit schema or curator.
+- For reproducible installs, pin package versions or use a lock file. Floating installs are acceptable only when the user explicitly wants the latest upstream release.
+
## Common Use Case Workflows
### Use Case 1: Single-Cell RNA-seq Analysis with Ontology Validation
@@ -197,7 +214,7 @@ import lamindb as ln
import bionty as bt
import anndata as ad
-# Start tracking
+# Start tracking a notebook/script run
ln.track(params={"analysis": "scRNA-seq QC and annotation"})
# Import cell type ontology
@@ -214,9 +231,9 @@ curator = ln.curators.AnnDataCurator(adata, schema)
curator.validate()
artifact = curator.save_artifact(key="scrna/validated.h5ad")
-# Link ontology annotations
-cell_types = bt.CellType.from_values(adata.obs.cell_type)
-artifact.feature_sets.add_ontology(cell_types)
+# Link ontology-backed annotations for queryability
+cell_types = bt.CellType.from_values(adata.obs["cell_type"])
+artifact.cell_types.add(*cell_types)
ln.finish()
```
@@ -235,13 +252,13 @@ for i, file in enumerate(data_files):
).save()
# Annotate with features
- artifact.features.add_values({
+ artifact.features.set_values({
"batch": i,
"tissue": tissues[i],
"condition": conditions[i]
})
-# Query across all experiments
+# Query across all experiments by annotated features
immune_datasets = ln.Artifact.filter(
key__startswith="scrna/",
tissue="PBMC",
@@ -278,7 +295,7 @@ wandb.log({"accuracy": 0.95})
import joblib
joblib.dump(model, "model.pkl")
model_artifact = ln.Artifact("model.pkl", key="models/exp-42.pkl").save()
-model_artifact.features.add_values({"wandb_run_id": wandb.run.id})
+model_artifact.features.set_values({"wandb_run_id": wandb.run.id})
ln.finish()
wandb.finish()
@@ -308,23 +325,25 @@ output_artifact = ln.Artifact(
ln.finish()
```
+For native Nextflow projects, prefer the `nf-lamin` plugin and current `nextflow.config` patterns when available; use inline Python tracking for small or custom pipeline steps.
+
## Getting Started Checklist
To start using LaminDB effectively:
1. **Installation & Setup** (`references/setup-deployment.md`)
- - Install LaminDB and required extras
+ - Install pinned LaminDB and required extras
- Authenticate with `lamin login`
- Initialize instance with `lamin init --storage ...`
2. **Learn Core Concepts** (`references/core-concepts.md`)
- Understand Artifacts, Records, Runs, Transforms
- Practice creating and retrieving artifacts
- - Implement `ln.track()` and `ln.finish()` in workflows
+ - Implement `ln.track()`/`ln.finish()` or `@ln.flow()`/`@ln.step()` in workflows
3. **Master Querying** (`references/data-management.md`)
- Practice filtering and searching registries
- - Learn feature-based queries
+ - Learn feature-based queries and expression-style filters
- Experiment with streaming large files
4. **Set Up Validation** (`references/annotation-validation.md`)
@@ -358,7 +377,7 @@ Follow these principles when working with LaminDB:
6. **Version, don't duplicate**: Use built-in versioning instead of creating new keys for modifications
-7. **Annotate with features**: Define typed features for queryable metadata
+7. **Annotate with features**: Define typed features and use `artifact.features.set_values()` for queryable metadata
8. **Document thoroughly**: Add descriptions to artifacts, schemas, and transforms
diff --git a/skills/lamindb/references/annotation-validation.md b/skills/lamindb/references/annotation-validation.md
index cd7f7a31..097f77a9 100644
--- a/skills/lamindb/references/annotation-validation.md
+++ b/skills/lamindb/references/annotation-validation.md
@@ -309,7 +309,7 @@ soma_schema = ln.Schema(
).save()
# Curate
-curator = ln.curators.TileDBSOMACurator(soma_exp, soma_schema)
+curator = ln.curators.TiledbsomaExperimentCurator(soma_exp, soma_schema)
curator.validate()
```
@@ -331,11 +331,8 @@ ln.Feature(name="age_str", dtype=int, coerce_dtype=True).save() # Auto-convert
### Value Validation
```python
-# Validate against allowed values
-cell_type_feature = ln.Feature(name="cell_type", dtype=str).save()
-
-# Link to registry for controlled vocabulary
-cell_type_feature.link_to_registry(bt.CellType)
+# Validate against allowed values in the Bionty CellType registry
+cell_type_feature = ln.Feature(name="cell_type", dtype=bt.CellType).save()
# Now validation checks against CellType registry
curator = ln.curators.DataFrameCurator(df, schema)
diff --git a/skills/lamindb/references/core-concepts.md b/skills/lamindb/references/core-concepts.md
index a473ce4a..5ed48215 100644
--- a/skills/lamindb/references/core-concepts.md
+++ b/skills/lamindb/references/core-concepts.md
@@ -184,10 +184,10 @@ ln.Run.filter(project=project).to_dataframe()
### Function-Level Tracking
-Use the `@ln.tracked()` decorator for fine-grained lineage:
+Use `@ln.flow()` for workflow entry points and `@ln.step()` for fine-grained lineage inside workflows:
```python
def preprocess_data(input_key: str, output_key: str, normalize: bool = True) -> None:
"""Preprocess raw data and save result."""
# Load input (automatically tracked)
@@ -201,9 +201,12 @@ def preprocess_data(input_key: str, output_key: str, normalize: bool = True) ->
# Save output (automatically tracked)
ln.Artifact.from_dataframe(data, key=output_key).save()
-# Each call creates a separate Transform and Run
-preprocess_data("raw/batch1.csv", "processed/batch1.csv", normalize=True)
-preprocess_data("raw/batch2.csv", "processed/batch2.csv", normalize=False)
+def run_preprocessing() -> None:
+ preprocess_data("raw/batch1.csv", "processed/batch1.csv", normalize=True)
+ preprocess_data("raw/batch2.csv", "processed/batch2.csv", normalize=False)
+
+run_preprocessing()
```
### Accessing Lineage Information
@@ -250,7 +253,7 @@ ln.Feature(name="treatment", dtype=str).save()
```python
# Single values
-artifact.features.add_values({
+artifact.features.set_values({
"gc_content": 0.55,
"experiment_date": "2025-10-31"
})
diff --git a/skills/lamindb/references/data-management.md b/skills/lamindb/references/data-management.md
index 7681552e..c74dbdbe 100644
--- a/skills/lamindb/references/data-management.md
+++ b/skills/lamindb/references/data-management.md
@@ -150,9 +150,10 @@ ln.Artifact.filter(created_by__handle__startswith="test").to_dataframe()
# Find artifacts by transform name
ln.Artifact.filter(transform__name="preprocess.py").to_dataframe()
-# Find artifacts measuring specific genes
-ln.Artifact.filter(feature_sets__genes__symbol="CD8A").to_dataframe()
-ln.Artifact.filter(feature_sets__genes__ensembl_gene_id="ENSG00000153563").to_dataframe()
+# Find artifacts measuring specific genes through schemas
+cd8a = bt.Gene.get(symbol="CD8A")
+schemas_with_cd8a = ln.Schema.filter(genes=cd8a)
+ln.Artifact.filter(schemas__in=schemas_with_cd8a).to_dataframe()
# Find runs with specific parameters
ln.Run.filter(params__learning_rate=0.01).to_dataframe()
@@ -181,16 +182,14 @@ ln.Artifact.order_by("-created_at", "size").to_dataframe()
### OR Logic
```python
-from lamindb import Q
-
# OR condition
artifacts = ln.Artifact.filter(
- Q(suffix=".jpg") | Q(suffix=".png")
+ ln.Q(suffix=".jpg") | ln.Q(suffix=".png")
).to_dataframe()
# Complex OR with multiple conditions
artifacts = ln.Artifact.filter(
- Q(suffix=".h5ad", size__gt=1e6) | Q(suffix=".csv", size__lt=1e3)
+ ln.Q(suffix=".h5ad", size__gt=1e6) | ln.Q(suffix=".csv", size__lt=1e3)
).to_dataframe()
```
@@ -199,12 +198,12 @@ artifacts = ln.Artifact.filter(
```python
# Exclude condition
artifacts = ln.Artifact.filter(
- ~Q(suffix=".tmp")
+ ~ln.Q(suffix=".tmp")
).to_dataframe()
# Complex exclusion
artifacts = ln.Artifact.filter(
- ~Q(created_by__handle="testuser")
+ ~ln.Q(created_by__handle="testuser")
).to_dataframe()
```
@@ -213,9 +212,9 @@ artifacts = ln.Artifact.filter(
```python
# Complex query
artifacts = ln.Artifact.filter(
- (Q(suffix=".h5ad") | Q(suffix=".csv")) &
- Q(size__gt=1e6) &
- ~Q(created_by__handle__startswith="test")
+ (ln.Q(suffix=".h5ad") | ln.Q(suffix=".csv")) &
+ ln.Q(size__gt=1e6) &
+ ~ln.Q(created_by__handle__startswith="test")
).to_dataframe()
```
@@ -380,7 +379,7 @@ Group related artifacts into collections:
# Create collection
collection = ln.Collection(
[artifact1, artifact2, artifact3],
- name="scRNA-seq batch 1-3",
+ key="scrna/batch_1_3",
description="Complete dataset across three batches"
).save()
@@ -389,7 +388,7 @@ for artifact in collection.artifacts:
print(artifact.key)
# Query collections
-ln.Collection.filter(name__contains="batch").to_dataframe()
+ln.Collection.filter(key__contains="batch").to_dataframe()
```
## Best Practices
diff --git a/skills/lamindb/references/integrations.md b/skills/lamindb/references/integrations.md
index 523177b4..77dd59d1 100644
--- a/skills/lamindb/references/integrations.md
+++ b/skills/lamindb/references/integrations.md
@@ -10,12 +10,13 @@ LaminDB supports extensive integrations across data storage, computational workf
### Local Filesystem
+```bash
+lamin init --storage ./mydata
+```
+
```python
import lamindb as ln
-# Initialize with local storage
-lamin init --storage ./mydata
-
# Save artifacts to local storage
artifact = ln.Artifact("data.csv", key="local/data.csv").save()
@@ -25,11 +26,14 @@ data = artifact.load()
### AWS S3
-```python
+```bash
# Initialize with S3 storage
+export LAMIN_DB_URL='<set-in-secret-manager>'
lamin init --storage s3://my-bucket/path \
- --db postgresql://user:pwd@host:port/db
+ --db "$LAMIN_DB_URL"
+```
+```python
# Artifacts automatically sync to S3
artifact = ln.Artifact("data.csv", key="experiments/data.csv").save()
@@ -41,25 +45,28 @@ data = artifact.load() # Downloads from S3 if not cached
Support for MinIO, Cloudflare R2, and other S3-compatible endpoints:
-```python
+```bash
# Initialize with custom S3 endpoint
lamin init --storage 's3://bucket?endpoint_url=http://minio.example.com:9000'
-# Configure credentials
-export AWS_ACCESS_KEY_ID=minioadmin
-export AWS_SECRET_ACCESS_KEY=minioadmin
+# Configure credentials outside shared scripts and do not echo values
+export AWS_ACCESS_KEY_ID='<redacted>'
+export AWS_SECRET_ACCESS_KEY='<redacted>'
```
### Google Cloud Storage
-```python
+```bash
# Install GCP extras
-pip install 'lamindb[gcp]'
+uv pip install 'lamindb[gcp]==2.5.1'
# Initialize with GCS
+export LAMIN_DB_URL='<set-in-secret-manager>'
lamin init --storage gs://my-bucket/path \
- --db postgresql://user:pwd@host:port/db
+ --db "$LAMIN_DB_URL"
+```
+```python
# Artifacts sync to GCS
artifact = ln.Artifact("data.csv", key="experiments/data.csv").save()
```
@@ -98,7 +105,7 @@ artifact = ln.Artifact.from_dataframe(
### Nextflow
-Track Nextflow pipeline execution and outputs:
+Track Nextflow pipeline execution and outputs. For current native Nextflow projects, prefer the `nf-lamin` plugin and its `nextflow.config` integration. Inline Python tracking is still useful for custom process scripts.
```python
# In your Nextflow process script
@@ -183,7 +190,7 @@ from redun import task
import lamindb as ln
@task()
def process_dataset(input_key: str, output_key: str):
"""Redun task with LaminDB tracking."""
# Load input
@@ -235,7 +242,7 @@ model_artifact = ln.Artifact(
).save()
# Link W&B run ID
-model_artifact.features.add_values({"wandb_run_id": wandb.run.id})
+model_artifact.features.set_values({"wandb_run_id": wandb.run.id})
ln.finish()
wandb.finish()
@@ -249,14 +256,13 @@ Integrate MLflow model tracking with LaminDB:
import mlflow
import lamindb as ln
-# Start runs
+# Start runs and record parameters in LaminDB
mlflow.start_run()
-ln.track()
-
-# Log parameters to both
params = {"max_depth": 5, "n_estimators": 100}
+ln.track(params=params)
+
+# Log parameters to MLflow too
mlflow.log_params(params)
-ln.context.params = params
# Load data from LaminDB
data_artifact = ln.Artifact.get(key="datasets/features.parquet")
@@ -458,10 +464,12 @@ cell_types = bt.CellType.from_values(adata.obs.cell_type)
Track wet lab experiments:
-```python
+```bash
# Install wetlab module
-pip install 'lamindb[wetlab]'
+uv pip install 'lamindb-wetlab==<reviewed-version>'
+```
+```python
# Use wetlab registries
import lamindb_wetlab as wetlab
@@ -469,14 +477,16 @@ import lamindb_wetlab as wetlab
experiment = wetlab.Experiment(name="RNA-seq batch 1").save()
```
-### Clinical Data (OMOP)
+### Clinical Data
-```python
-# Install clinical module
-pip install 'lamindb[clinical]'
+```bash
+# Install the relevant clinical schema module after confirming its current release
+uv pip install '<clinical-module>==<reviewed-version>'
+```
-# Use OMOP common data model
-import lamindb_clinical as clinical
+```python
+# Use the selected clinical schema module, such as clinicore or an OMOP module
+import clinicore as clinical
# Track clinical data
patient = clinical.Patient(patient_id="P001").save()
@@ -486,15 +496,16 @@ patient = clinical.Patient(patient_id="P001").save()
### Sync with Git Repositories
-```python
-# Configure git sync
+```bash
export LAMINDB_SYNC_GIT_REPO=https://github.com/user/repo.git
+lamin settings set dev-dir .
+```
+```python
# Or programmatically
-ln.settings.sync_git_repo = "https://github.com/user/repo.git"
+import lamindb as ln
-# Set development directory
-lamin settings set dev-dir .
+ln.settings.sync_git_repo = "https://github.com/user/repo.git"
# Scripts tracked with git commits
ln.track() # Automatically captures git commit hash
@@ -525,6 +536,8 @@ Sync with Benchling registries (requires team/enterprise plan):
### REST API Integration
+Validate and sanitize external content before registering it as a LaminDB artifact. Treat REST responses as untrusted until schema validation passes.
+
```python
import requests
import lamindb as ln
@@ -539,14 +552,17 @@ data = response.json()
import pandas as pd
df = pd.DataFrame(data)
-# Save to LaminDB
-artifact = ln.Artifact.from_dataframe(
- df,
+# Validate before saving to LaminDB
+schema = ln.Schema.get(name="external_api_schema")
+curator = ln.curators.DataFrameCurator(df, schema)
+curator.validate()
+
+artifact = curator.save_artifact(
key="api/fetched_data.parquet",
description="Data fetched from external API"
-).save()
+)
-artifact.features.add_values({"api_url": response.url})
+artifact.features.set_values({"api_url": response.url})
ln.finish()
```
@@ -554,24 +570,29 @@ ln.finish()
### Database Integration
```python
+import os
+import pandas as pd
import sqlalchemy as sa
import lamindb as ln
ln.track()
-# Connect to external database
-engine = sa.create_engine("postgresql://user:pwd@host:port/db")
+# Connect using a named secret; never paste or print the URL value
+engine = sa.create_engine(os.environ["SOURCE_DB_URL"])
# Query data
query = "SELECT * FROM experiments WHERE date > '2025-01-01'"
df = pd.read_sql(query, engine)
-# Save to LaminDB
-artifact = ln.Artifact.from_dataframe(
- df,
+# Validate external rows before registration
+schema = ln.Schema.get(name="external_experiments_schema")
+curator = ln.curators.DataFrameCurator(df, schema)
+curator.validate()
+
+artifact = curator.save_artifact(
key="external_db/experiments_2025.parquet",
description="Experiments from external database"
-).save()
+)
ln.finish()
```
@@ -595,12 +616,12 @@ artifact = ln.Artifact.from_dataframe(
## Best Practices for Integrations
1. **Track consistently**: Use `ln.track()` in all integrated workflows
-2. **Link IDs**: Store external system IDs (W&B run ID, MLflow experiment ID) as features
+2. **Link IDs**: Store external system IDs (W&B run ID, MLflow experiment ID) as non-secret features
3. **Centralize data**: Use LaminDB as single source of truth for data artifacts
4. **Sync parameters**: Log parameters to both LaminDB and ML platforms
5. **Version together**: Keep code (git), data (LaminDB), and experiments (ML platform) in sync
6. **Cache strategically**: Configure appropriate cache locations for cloud storage
-7. **Use feature sets**: Link ontology terms from Bionty to artifacts
+7. **Use ontology-backed annotations**: Link validated Bionty records through module-specific managers such as `artifact.cell_types.add(...)`, schemas, or typed features
8. **Document integrations**: Add descriptions explaining integration context
9. **Test incrementally**: Verify integration with small datasets first
10. **Monitor lineage**: Use `view_lineage()` to ensure integration tracking works
@@ -609,15 +630,15 @@ artifact = ln.Artifact.from_dataframe(
**Issue: S3 credentials not found**
```bash
-export AWS_ACCESS_KEY_ID=your_key
-export AWS_SECRET_ACCESS_KEY=your_secret
+test -n "$AWS_ACCESS_KEY_ID" && echo "AWS_ACCESS_KEY_ID is set"
+test -n "$AWS_SECRET_ACCESS_KEY" && echo "AWS_SECRET_ACCESS_KEY is set"
export AWS_DEFAULT_REGION=us-east-1
```
**Issue: GCS authentication failure**
```bash
gcloud auth application-default login
-export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
+test -n "$GOOGLE_APPLICATION_CREDENTIALS" && echo "GOOGLE_APPLICATION_CREDENTIALS is set"
```
**Issue: Git sync not working**
diff --git a/skills/lamindb/references/ontologies.md b/skills/lamindb/references/ontologies.md
index 5f3a3152..445a15b8 100644
--- a/skills/lamindb/references/ontologies.md
+++ b/skills/lamindb/references/ontologies.md
@@ -28,10 +28,12 @@ LaminDB provides access to multiple curated ontology sources:
## Installation and Import
-```python
-# Install bionty (included with lamindb)
-pip install lamindb
+```bash
+# Install the current validated baseline
+uv pip install 'lamindb==2.5.1' 'bionty==2.4.0'
+```
+```python
# Import
import lamindb as ln
import bionty as bt
@@ -225,7 +227,7 @@ artifact = ln.Artifact.from_anndata(
).save()
# Link ontology records to artifact
-artifact.feature_sets.add_ontology(cell_types)
+artifact.cell_types.add(*cell_types)
```
### Annotating DataFrames
@@ -254,8 +256,8 @@ artifact = ln.Artifact.from_dataframe(
cell_type_records = bt.CellType.from_values(df["cell_type"])
tissue_records = bt.Tissue.from_values(df["tissue"])
-artifact.feature_sets.add_ontology(cell_type_records)
-artifact.feature_sets.add_ontology(tissue_records)
+artifact.cell_types.add(*cell_type_records)
+artifact.tissues.add(*tissue_records)
```
## Managing Custom Terms and Hierarchies
@@ -421,8 +423,8 @@ artifact = ln.Artifact.from_dataframe(
).save()
# Link ontology records
-artifact.feature_sets.add_ontology(bt.CellType.from_values(df["cell_type"]))
-artifact.feature_sets.add_ontology(bt.Tissue.from_values(df["tissue"]))
+artifact.cell_types.add(*bt.CellType.from_values(df["cell_type"]))
+artifact.tissues.add(*bt.Tissue.from_values(df["tissue"]))
ln.finish() # Complete tracking
```
@@ -445,20 +447,19 @@ mouse_records = bt.Gene.from_values(mouse_orthologs, organism="mouse")
## Querying Ontology-Annotated Data
```python
-# Find all datasets with specific cell type
+# Find all datasets annotated with a specific cell type
t_cell = bt.CellType.get(name="T cell")
-ln.Artifact.filter(feature_sets__cell_types=t_cell).to_dataframe()
+ln.Artifact.filter(cell_types=t_cell).to_dataframe()
# Find datasets measuring specific genes
cd8a = bt.Gene.get(symbol="CD8A", organism="human")
-ln.Artifact.filter(feature_sets__genes=cd8a).to_dataframe()
+schemas_with_cd8a = ln.Schema.filter(genes=cd8a)
+ln.Artifact.filter(schemas__in=schemas_with_cd8a).to_dataframe()
# Query across ontology hierarchy
# Find all datasets with T cell or T cell subtypes
t_cell_subtypes = t_cell.query_children()
-ln.Artifact.filter(
- feature_sets__cell_types__in=t_cell_subtypes
-).to_dataframe()
+ln.Artifact.filter(cell_types__in=t_cell_subtypes).to_dataframe()
```
## Best Practices
diff --git a/skills/lamindb/references/setup-deployment.md b/skills/lamindb/references/setup-deployment.md
index 9e7a9c44..df53f11c 100644
--- a/skills/lamindb/references/setup-deployment.md
+++ b/skills/lamindb/references/setup-deployment.md
@@ -7,11 +7,11 @@ This document covers installation, configuration, instance management, storage o
### Basic Installation
```bash
-# Install LaminDB
-pip install lamindb
+# Install the current validated baseline
+uv pip install 'lamindb==2.5.1'
-# Or with pip3
-pip3 install lamindb
+# Minimal namespace-only package for lightweight clients
+uv pip install 'lamindb-core==2.5.1'
```
### Installation with Extras
@@ -20,34 +20,36 @@ Install optional dependencies for specific functionality:
```bash
# Google Cloud Platform support
-pip install 'lamindb[gcp]'
+uv pip install 'lamindb[gcp]==2.5.1'
# Flow cytometry formats
-pip install 'lamindb[fcs]'
+uv pip install 'lamindb[fcs]==2.5.1'
-# Array storage and streaming (Zarr support)
-pip install 'lamindb[zarr]'
+# Array storage and streaming (Zarr v2 support)
+uv pip install 'lamindb[zarr-v2]==2.5.1'
# AWS S3 support (usually included by default)
-pip install 'lamindb[aws]'
+uv pip install 'lamindb==2.5.1'
# Multiple extras
-pip install 'lamindb[gcp,zarr,fcs]'
+uv pip install 'lamindb[gcp,zarr-v2,fcs]==2.5.1'
```
### Module Plugins
```bash
# Biological ontologies (Bionty)
-pip install bionty
+uv pip install 'bionty==2.4.0'
# Wet lab functionality
-pip install lamindb-wetlab
+uv pip install 'lamindb-wetlab==<reviewed-version>'
-# Clinical data (OMOP CDM)
-pip install lamindb-clinical
+# Clinical schemas, such as clinicore or OMOP-focused modules
+uv pip install '<clinical-module>==<reviewed-version>'
```
+Use a project lock file for production deployments. The pinned LaminDB and Bionty versions above reflect the current refresh baseline; for optional modules, look up the current official package and pin the reviewed version rather than installing a floating latest release.
+
### Verify Installation
```python
@@ -81,7 +83,9 @@ lamin login
**Data Privacy:** LaminDB authentication only collects basic metadata (email, user information). Your actual data remains private and is not sent to LaminDB servers.
-**Local vs Cloud:** Authentication is required even for local-only usage to enable collaboration features and instance management.
+**Local vs Cloud:** Local `lamin init` instances do not require LaminHub login. Login is required for LaminHub-managed collaboration and cloud-hosted metadata.
+
+**Credential handling:** Never ask the agent to print API keys, cloud secrets, or database URLs containing passwords. When debugging, check only whether named variables exist and redact values in terminal output and logs.
## Instance Initialization
@@ -124,16 +128,20 @@ For production deployments:
```bash
# S3 + PostgreSQL
+export LAMIN_DB_URL='<set-in-secret-manager>'
lamin init --storage s3://my-bucket/path \
- --db postgresql://user:password@hostname:5432/dbname \
+ --db "$LAMIN_DB_URL" \
--modules bionty
# GCS + PostgreSQL
+export LAMIN_DB_URL='<set-in-secret-manager>'
lamin init --storage gs://my-bucket/path \
- --db postgresql://user:password@hostname:5432/dbname \
+ --db "$LAMIN_DB_URL" \
--modules bionty
```
+Set `LAMIN_DB_URL` through a secret manager or secure shell session. Do not commit it to configuration files, notebooks, or chat transcripts.
+
### Instance Naming
```bash
@@ -201,14 +209,16 @@ lamin init --storage ./data
**Setup:**
```bash
-# Set credentials
-export AWS_ACCESS_KEY_ID=your_key_id
-export AWS_SECRET_ACCESS_KEY=your_secret_key
-export AWS_DEFAULT_REGION=us-east-1
+# Prefer IAM roles or workload identity. If local variables are needed,
+# set them outside shared scripts and never echo their values.
+export AWS_ACCESS_KEY_ID='<redacted>'
+export AWS_SECRET_ACCESS_KEY='<redacted>'
+export AWS_DEFAULT_REGION='us-east-1'
# Initialize
+export LAMIN_DB_URL='<set-in-secret-manager>'
lamin init --storage s3://my-bucket/project-data \
- --db postgresql://user:pwd@host:5432/db
+ --db "$LAMIN_DB_URL"
```
**S3 Permissions Required:**
@@ -241,11 +251,12 @@ lamin init --storage s3://my-bucket/project-data \
gcloud auth application-default login
# Or use service account
-export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
+export GOOGLE_APPLICATION_CREDENTIALS=/secure/path/to/service-account.json
# Initialize
+export LAMIN_DB_URL='<set-in-secret-manager>'
lamin init --storage gs://my-bucket/project-data \
- --db postgresql://user:pwd@host:5432/db
+ --db "$LAMIN_DB_URL"
```
### S3-Compatible Storage
@@ -254,14 +265,14 @@ For MinIO, Cloudflare R2, or other S3-compatible services:
```bash
# MinIO example
-export AWS_ACCESS_KEY_ID=minioadmin
-export AWS_SECRET_ACCESS_KEY=minioadmin
+export AWS_ACCESS_KEY_ID='<redacted>'
+export AWS_SECRET_ACCESS_KEY='<redacted>'
lamin init --storage 's3://my-bucket?endpoint_url=http://minio.example.com:9000'
# Cloudflare R2 example
-export AWS_ACCESS_KEY_ID=your_r2_access_key
-export AWS_SECRET_ACCESS_KEY=your_r2_secret_key
+export AWS_ACCESS_KEY_ID='<redacted>'
+export AWS_SECRET_ACCESS_KEY='<redacted>'
lamin init --storage 's3://bucket?endpoint_url=https://account-id.r2.cloudflarestorage.com'
```
@@ -295,13 +306,15 @@ lamin init --storage ./data
**Setup:**
```bash
-# Full connection string
+# Full connection string stored in a named secret
+export LAMIN_DB_URL='<set-in-secret-manager>'
lamin init --storage s3://bucket/path \
- --db postgresql://username:password@hostname:5432/database
+ --db "$LAMIN_DB_URL"
# With SSL
+export LAMIN_DB_URL='<set-in-secret-manager-with-ssl>'
lamin init --storage s3://bucket/path \
- --db "postgresql://user:pwd@host:5432/db?sslmode=require"
+ --db "$LAMIN_DB_URL"
```
**PostgreSQL Versions:** Compatible with PostgreSQL 12+
@@ -421,6 +434,9 @@ export LAMIN_SETTINGS_DIR=/path/to/settings
# Git sync
export LAMINDB_SYNC_GIT_REPO=https://github.com/user/repo.git
+
+# Database URL for setup examples; keep the value secret
+export LAMIN_DB_URL='<set-in-secret-manager>'
```
## Instance Management
@@ -485,8 +501,9 @@ lamin init --storage ./dev-data --modules bionty
**Production:**
```bash
# Cloud production
+export LAMIN_DB_URL='<set-in-secret-manager>'
lamin init --storage s3://prod-bucket/data \
- --db postgresql://user:pwd@db-host:5432/prod-db \
+ --db "$LAMIN_DB_URL" \
--modules bionty \
--name production
```
@@ -512,13 +529,15 @@ Deploy instances in multiple regions for data sovereignty:
```bash
# US instance
+export LAMIN_DB_URL_US='<set-in-secret-manager>'
lamin init --storage s3://us-bucket/data \
- --db postgresql://user:pwd@us-db:5432/db \
+ --db "$LAMIN_DB_URL_US" \
--name us-production
# EU instance
+export LAMIN_DB_URL_EU='<set-in-secret-manager>'
lamin init --storage s3://eu-bucket/data \
- --db postgresql://user:pwd@eu-db:5432/db \
+ --db "$LAMIN_DB_URL_EU" \
--name eu-production
```
@@ -528,12 +547,14 @@ Multiple users, shared data:
```bash
# Shared storage with user-specific DB
+export LAMIN_DB_URL_USER1='<set-in-secret-manager>'
lamin init --storage s3://shared-bucket/data \
- --db postgresql://user1:pwd@host:5432/user1_db \
+ --db "$LAMIN_DB_URL_USER1" \
--name user1-workspace
+export LAMIN_DB_URL_USER2='<set-in-secret-manager>'
lamin init --storage s3://shared-bucket/data \
- --db postgresql://user2:pwd@host:5432/user2_db \
+ --db "$LAMIN_DB_URL_USER2" \
--name user2-workspace
```
@@ -577,6 +598,7 @@ adata = artifact.backed() # Don't load into memory
- Use environment variables, not hardcoded credentials
- Use IAM roles on AWS/GCP instead of access keys
- Rotate credentials regularly
+ - Never print, paste, or commit actual database URLs, API keys, or cloud secret values
2. **Access Control:**
- Use PostgreSQL for multi-user access control
@@ -671,7 +693,7 @@ gsutil ls gs://your-bucket/
**Issue: Database connection error**
```bash
# Test PostgreSQL connection
-psql postgresql://user:pwd@host:5432/db
+psql "$LAMIN_DB_URL"
# Check database version compatibility
lamin migrate check
@@ -693,8 +715,8 @@ lamin cache set /larger/disk/cache
### Upgrading LaminDB
```bash
-# Upgrade to latest version
-pip install --upgrade lamindb
+# Upgrade after reviewing changelog and compatibility matrix
+uv pip install --upgrade 'lamindb==2.5.1'
# Upgrade database schema
lamin migrate deploy
diff --git a/skills/neuropixels-analysis/SKILL.md b/skills/neuropixels-analysis/SKILL.md
index 87c33c18..556caa54 100644
--- a/skills/neuropixels-analysis/SKILL.md
+++ b/skills/neuropixels-analysis/SKILL.md
@@ -1,9 +1,9 @@
---
name: neuropixels-analysis
-description: Neuropixels neural recording analysis. Load SpikeGLX/OpenEphys data, preprocess, motion correction, Kilosort4 spike sorting, quality metrics, Allen/IBL curation, AI-assisted visual analysis, for Neuropixels 1.0/2.0 extracellular electrophysiology. Use when working with neural recordings, spike sorting, extracellular electrophysiology, or when the user mentions Neuropixels, SpikeGLX, Open Ephys, Kilosort, quality metrics, or unit curation.
+description: Analyze Neuropixels extracellular recordings end-to-end with SpikeInterface. Covers loading SpikeGLX/Open Ephys/NWB data, preprocessing, drift/motion correction, Kilosort4 (and CPU) spike sorting, quality metrics, and unit curation (threshold-based, model-based UnitRefine, and AI-assisted visual review). Use when working with Neuropixels 1.0/2.0 recordings, spike sorting, or extracellular electrophysiology analysis.
license: MIT license
metadata:
- version: "1.0"
+ version: "2.0"
skill-author: K-Dense Inc.
---
@@ -11,26 +11,34 @@ metadata:
## Overview
-Comprehensive toolkit for analyzing Neuropixels high-density neural recordings using current best practices from SpikeInterface, Allen Institute, and International Brain Laboratory (IBL). Supports the full workflow from raw data to publication-ready curated units.
+Toolkit for analyzing Neuropixels high-density neural recordings using current best
+practices from [SpikeInterface](https://spikeinterface.readthedocs.io/), the Allen
+Institute, and the International Brain Laboratory (IBL). It covers the full workflow from
+raw data to publication-ready curated units.
+
+All examples use the real SpikeInterface API (`spikeinterface.full as si`) plus the
+companion curation module (`spikeinterface.curation as sc`). The skill ships runnable
+scripts in `scripts/` and a copy-and-edit template in `assets/` that implement this
+workflow directly on top of SpikeInterface — there is no separate package to install
+beyond the dependencies listed under [Installation](#installation).
## When to Use This Skill
This skill should be used when:
-- Working with Neuropixels recordings (.ap.bin, .lf.bin, .meta files)
+- Working with Neuropixels recordings (`.ap.bin`, `.lf.bin`, `.meta` files)
- Loading data from SpikeGLX, Open Ephys, or NWB formats
-- Preprocessing neural recordings (filtering, CAR, bad channel detection)
-- Detecting and correcting motion/drift in recordings
-- Running spike sorting (Kilosort4, SpykingCircus2, Mountainsort5)
-- Computing quality metrics (SNR, ISI violations, presence ratio)
-- Curating units using Allen/IBL criteria
-- Creating visualizations of neural data
-- Exporting results to Phy or NWB
+- Preprocessing neural recordings (filtering, common reference, bad-channel detection)
+- Detecting and correcting motion/drift
+- Running spike sorting (Kilosort4, SpykingCircus2, Mountainsort5, Tridesclous2)
+- Computing quality metrics (SNR, ISI violations, presence ratio, amplitude cutoff)
+- Curating units (threshold-based, model-based, or AI-assisted)
+- Creating visualizations and exporting to Phy or NWB
## Supported Hardware & Formats
| Probe | Electrodes | Channels | Notes |
|-------|-----------|----------|-------|
-| Neuropixels 1.0 | 960 | 384 | Requires phase_shift correction |
+| Neuropixels 1.0 | 960 | 384 | Use `phase_shift` for ADC correction |
| Neuropixels 2.0 (single) | 1280 | 384 | Denser geometry |
| Neuropixels 2.0 (4-shank) | 5120 | 384 | Multi-region recording |
@@ -42,205 +50,253 @@ This skill should be used when:
## Quick Start
-### Basic Import and Setup
+### Import and configure parallel processing
```python
import spikeinterface.full as si
-import neuropixels_analysis as npa
-# Configure parallel processing
-job_kwargs = dict(n_jobs=-1, chunk_duration='1s', progress_bar=True)
+# Global job kwargs are reused by all parallelizable steps
+si.set_global_job_kwargs(n_jobs=-1, chunk_duration="1s", progress_bar=True)
```
-### Loading Data
+### Loading data
```python
-# SpikeGLX (most common)
-recording = si.read_spikeglx('/path/to/data', stream_id='imec0.ap')
+# Inspect available streams first
+stream_names, stream_ids = si.get_neo_streams("spikeglx", "/path/to/run_g0/")
+print(stream_names) # e.g. ['imec0.ap', 'imec0.lf', 'nidq']
-# Open Ephys (common for many labs)
-recording = si.read_openephys('/path/to/Record_Node_101/')
+# SpikeGLX (most common) — select the AP stream by name
+recording = si.read_spikeglx("/path/to/run_g0/", stream_name="imec0.ap", load_sync_channel=False)
-# Check available streams
-streams, ids = si.get_neo_streams('spikeglx', '/path/to/data')
-print(streams) # ['imec0.ap', 'imec0.lf', 'nidq']
+# Open Ephys
+recording = si.read_openephys("/path/to/Record_Node_101/")
-# For testing with subset of data
-recording = recording.frame_slice(0, int(60 * recording.get_sampling_frequency()))
+# For quick iteration, slice the first 60 s
+fs = recording.get_sampling_frequency()
+recording_sub = recording.frame_slice(0, int(60 * fs))
```
-### Complete Pipeline (One Command)
+### Full pipeline (bundled script)
-```python
-# Run full analysis pipeline
-results = npa.run_pipeline(
- recording,
- output_dir='output/',
- sorter='kilosort4',
- curation_method='allen',
-)
+The repository ships an end-to-end pipeline built on SpikeInterface:
-# Access results
-sorting = results['sorting']
-metrics = results['metrics']
-labels = results['labels']
+```bash
+python scripts/neuropixels_pipeline.py /path/to/spikeglx/data output/ --sorter kilosort4 --curation allen
```
+It performs load → preprocess → drift check → optional motion correction → sorting →
+postprocessing → quality metrics → curation → export. Read the steps below to run them
+interactively or customize the pipeline.
+
## Standard Analysis Workflow
### 1. Preprocessing
+Recommended chain, following the SpikeInterface Neuropixels how-to (IBL-style destriping
+with channel removal + common reference):
+
+```python
+rec = si.highpass_filter(recording, freq_min=400.0)
+bad_channel_ids, channel_labels = si.detect_bad_channels(rec)
+rec = rec.remove_channels(bad_channel_ids)
+rec = si.phase_shift(rec) # ADC phase correction (Neuropixels 1.0)
+rec = si.common_reference(rec, operator="median", reference="global")
+```
+
+Save the preprocessed recording (Kilosort needs a binary file, and it speeds up reuse):
+
```python
-# Recommended preprocessing chain
-rec = si.highpass_filter(recording, freq_min=400)
-rec = si.phase_shift(rec) # Required for Neuropixels 1.0
-bad_ids, _ = si.detect_bad_channels(rec)
-rec = rec.remove_channels(bad_ids)
-rec = si.common_reference(rec, operator='median')
-
-# Or use our wrapper
-rec = npa.preprocess(recording)
+rec = rec.save(folder="preprocessed/", format="binary")
```
-### 2. Check and Correct Drift
+### 2. Check and correct drift
+
+Always inspect drift before sorting:
```python
-# Check for drift (always do this!)
-motion_info = npa.estimate_motion(rec, preset='kilosort_like')
-npa.plot_drift(rec, motion_info, output='drift_map.png')
+from spikeinterface.sortingcomponents.peak_detection import detect_peaks
+from spikeinterface.sortingcomponents.peak_localization import localize_peaks
+
+noise_levels = si.get_noise_levels(rec, return_in_uV=False)
+peaks = detect_peaks(rec, method="locally_exclusive", noise_levels=noise_levels,
+ detect_threshold=5, radius_um=50.0)
+peak_locations = localize_peaks(rec, peaks, method="center_of_mass")
+
+# Visualize the drift raster
+si.plot_drift_raster_map(peaks=peaks, peak_locations=peak_locations,
+ recording=rec, clim=(-50, 50))
+```
+
+Apply correction if needed (presets: `rigid_fast`, `kilosort_like`,
+`nonrigid_accurate`, `nonrigid_fast_and_accurate`, `dredge`, `dredge_fast`):
-# Apply correction if needed
-if motion_info['motion'].max() > 10: # microns
- rec = npa.correct_motion(rec, preset='nonrigid_accurate')
+```python
+rec_corrected = si.correct_motion(rec, preset="nonrigid_fast_and_accurate", folder="motion/")
```
-### 3. Spike Sorting
+### 3. Spike sorting
```python
-# Kilosort4 (recommended, requires GPU)
-sorting = si.run_sorter('kilosort4', rec, folder='ks4_output')
+# Kilosort4 (recommended, requires a CUDA GPU)
+sorting = si.run_sorter("kilosort4", rec_corrected, folder="ks4_output")
+
+# CPU alternatives (internally developed, no external install)
+sorting = si.run_sorter("spykingcircus2", rec_corrected, folder="sc2_output")
+sorting = si.run_sorter("tridesclous2", rec_corrected, folder="tdc2_output")
+sorting = si.run_sorter("mountainsort5", rec_corrected, folder="ms5_output")
-# CPU alternatives
-sorting = si.run_sorter('tridesclous2', rec, folder='tdc2_output')
-sorting = si.run_sorter('spykingcircus2', rec, folder='sc2_output')
-sorting = si.run_sorter('mountainsort5', rec, folder='ms5_output')
+# External sorters can run in containers without local install
+sorting = si.run_sorter("kilosort2_5", rec_corrected, folder="ks25_output", docker_image=True)
-# Check available sorters
print(si.installed_sorters())
```
+> Note: `run_sorter` uses the `folder=` argument. The older `output_folder=` is deprecated.
+
### 4. Postprocessing
```python
-# Create analyzer and compute all extensions
-analyzer = si.create_sorting_analyzer(sorting, rec, sparse=True)
-
-analyzer.compute('random_spikes', max_spikes_per_unit=500)
-analyzer.compute('waveforms', ms_before=1.0, ms_after=2.0)
-analyzer.compute('templates', operators=['average', 'std'])
-analyzer.compute('spike_amplitudes')
-analyzer.compute('correlograms', window_ms=50.0, bin_ms=1.0)
-analyzer.compute('unit_locations', method='monopolar_triangulation')
-analyzer.compute('quality_metrics')
-
-metrics = analyzer.get_extension('quality_metrics').get_data()
+analyzer = si.create_sorting_analyzer(sorting, rec_corrected, sparse=True,
+ format="binary_folder", folder="analyzer/")
+
+analyzer.compute("random_spikes", method="uniform", max_spikes_per_unit=500)
+analyzer.compute("waveforms", ms_before=1.0, ms_after=2.0)
+analyzer.compute("templates", operators=["average", "std"])
+analyzer.compute("noise_levels")
+analyzer.compute("spike_amplitudes")
+analyzer.compute("correlograms", window_ms=50.0, bin_ms=1.0)
+analyzer.compute("unit_locations", method="monopolar_triangulation")
+analyzer.compute("template_similarity")
+
+metric_names = ["firing_rate", "presence_ratio", "snr", "isi_violation", "amplitude_cutoff"]
+analyzer.compute("quality_metrics", metric_names=metric_names)
+metrics = analyzer.get_extension("quality_metrics").get_data()
```
-### 5. Curation
+### 5. Curation by metric thresholds
```python
-# Allen Institute criteria (conservative)
-good_units = metrics.query("""
- presence_ratio > 0.9 and
- isi_violations_ratio < 0.5 and
- amplitude_cutoff < 0.1
-""").index.tolist()
-
-# Or use automated curation
-labels = npa.curate(metrics, method='allen') # 'allen', 'ibl', 'strict'
+# Allen-style query (note: column is isi_violations_ratio)
+query = "(amplitude_cutoff < 0.1) & (isi_violations_ratio < 0.5) & (presence_ratio > 0.9)"
+good_unit_ids = metrics.query(query).index.values
```
-### 6. AI-Assisted Curation (For Uncertain Units)
+For reusable, multi-threshold logic with `allen` / `ibl` / `strict` presets, use the
+bundled `scripts/compute_metrics.py`. See
+[references/AUTOMATED_CURATION.md](references/AUTOMATED_CURATION.md) for details and the
+Bombcell / UnitMatch tools.
-When using this skill with Claude Code, Claude can directly analyze waveform plots and provide expert curation decisions. For programmatic API access:
+### 6. Model-based curation (UnitRefine)
-```python
-from anthropic import Anthropic
+SpikeInterface can apply pretrained machine-learning classifiers from Hugging Face via the
+`spikeinterface.curation` module. The UnitRefine models were trained on real Neuropixels
+data (V1, SC, ALM):
-# Setup API client
-client = Anthropic()
+```python
+import spikeinterface.curation as sc
-# Analyze uncertain units visually
-uncertain = metrics.query('snr > 3 and snr < 8').index.tolist()
+# 1) noise vs neural
+noise_labels = sc.model_based_label_units(
+ sorting_analyzer=analyzer,
+ repo_id="SpikeInterface/UnitRefine_noise_neural_classifier",
+ trust_model=True,
+)
+neural = analyzer.remove_units(noise_labels[noise_labels["prediction"] == "noise"].index)
-for unit_id in uncertain:
- result = npa.analyze_unit_visually(analyzer, unit_id, api_client=client)
- print(f"Unit {unit_id}: {result['classification']}")
- print(f" Reasoning: {result['reasoning'][:100]}...")
+# 2) single-unit (sua) vs multi-unit (mua) on the surviving units
+sua_mua_labels = sc.model_based_label_units(
+ sorting_analyzer=neural,
+ repo_id="SpikeInterface/UnitRefine_sua_mua_classifier",
+ trust_model=True,
+)
```
-**Claude Code Integration**: When running within Claude Code, ask Claude to examine waveform/correlogram plots directly - no API setup required.
+Each call returns a DataFrame with `prediction` and `probability` (confidence) per unit.
+`trust_model=True` (or an explicit `trusted=[...]` list) is required to load the `.skops`
+model — only load models from sources you trust. Models trained on other brain
+areas/datasets may not transfer; validate against a manually labelled subset.
+
+### 7. AI-assisted curation (for uncertain units)
+
+When running inside an agent such as Cursor or Claude Code, the agent can directly inspect
+waveform/correlogram plots and give an expert read — no API setup required. Generate plots
+and ask the agent to assess isolation quality.
-### 7. Generate Analysis Report
+For programmatic vision-model access, **read API keys from the environment — never hardcode
+credentials in analysis scripts** (they leak into version control and logs):
```python
-# Generate comprehensive HTML report with visualizations
-report_dir = npa.generate_analysis_report(results, 'output/')
-# Opens report.html with summary stats, figures, and unit table
+import os
+from anthropic import Anthropic
-# Print formatted summary to console
-npa.print_analysis_summary(results)
+client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) # set this in your shell, not in code
```
-### 8. Export Results
+See [references/AI_CURATION.md](references/AI_CURATION.md) for the full pattern (rendering a
+unit summary image, building the prompt, and parsing the response).
+
+### 8. Export results
```python
-# Export to Phy for manual review
-si.export_to_phy(analyzer, output_folder='phy_export/',
+# Keep only good units, then export
+analyzer_clean = analyzer.select_units(good_unit_ids, folder="analyzer_clean/", format="binary_folder")
+
+# Phy for manual review
+si.export_to_phy(analyzer_clean, output_folder="phy_export/",
compute_pc_features=True, compute_amplitudes=True)
-# Export to NWB
+# Figures report
+si.export_report(analyzer_clean, "report/", format="png")
+
+# NWB
from spikeinterface.exporters import export_to_nwb
-export_to_nwb(rec, sorting, 'output.nwb')
+export_to_nwb(analyzer_clean, "output.nwb")
-# Save quality metrics
-metrics.to_csv('quality_metrics.csv')
+# Metrics table
+metrics.to_csv("quality_metrics.csv")
```
## Common Pitfalls and Best Practices
-1. **Always check drift** before spike sorting - drift > 10μm significantly impacts quality
-2. **Use phase_shift** for Neuropixels 1.0 probes (not needed for 2.0)
-3. **Save preprocessed data** to avoid recomputing - use `rec.save(folder='preprocessed/')`
-4. **Use GPU** for Kilosort4 - it's 10-50x faster than CPU alternatives
-5. **Review uncertain units manually** - automated curation is a starting point
-6. **Combine metrics with AI** - use metrics for clear cases, AI for borderline units
-7. **Document your thresholds** - different analyses may need different criteria
-8. **Export to Phy** for critical experiments - human oversight is valuable
+1. **Always check drift** before spike sorting — drift > ~10 μm meaningfully degrades quality.
+2. **Use `phase_shift`** for Neuropixels 1.0 to correct ADC sampling offsets.
+3. **Save the preprocessed recording** with `rec.save(folder=...)` to avoid recomputation (Kilosort also needs a binary file).
+4. **Use a GPU** for Kilosort4 — it is far faster than CPU sorters.
+5. **Review uncertain units** — automated/model-based curation is a starting point, not a verdict.
+6. **Combine approaches** — thresholds for clear cases, model/AI for borderline units.
+7. **Document thresholds and model repo IDs** for reproducibility.
+8. **Export to Phy** for critical experiments — human oversight is valuable.
## Key Parameters to Adjust
### Preprocessing
-- `freq_min`: Highpass cutoff (300-400 Hz typical)
-- `detect_threshold`: Bad channel detection sensitivity
+- `freq_min`: highpass cutoff (300–400 Hz typical)
+- `detect_bad_channels`: returns `(bad_channel_ids, channel_labels)`
### Motion Correction
-- `preset`: 'kilosort_like' (fast) or 'nonrigid_accurate' (better for severe drift)
+- `preset`: `nonrigid_fast_and_accurate` (balanced), `nonrigid_accurate` (severe drift), `dredge` (state of the art)
### Spike Sorting (Kilosort4)
-- `batch_size`: Samples per batch (30000 default)
-- `nblocks`: Number of drift blocks (increase for long recordings)
-- `Th_learned`: Detection threshold (lower = more spikes)
+- `batch_size`: samples per batch (60000 default)
+- `nblocks`: drift blocks (increase for long, drifty recordings)
+- `Th_universal` / `Th_learned`: detection thresholds (lower = more spikes)
### Quality Metrics
-- `snr_threshold`: Signal-to-noise cutoff (3-5 typical)
-- `isi_violations_ratio`: Refractory violations (0.01-0.5)
-- `presence_ratio`: Recording coverage (0.5-0.95)
+- `snr`: signal-to-noise cutoff (3–5 typical)
+- `isi_violations_ratio`: refractory violations (0.01–0.5)
+- `presence_ratio`: recording coverage (0.5–0.95)
## Bundled Resources
+### scripts/explore_recording.py
+Quick inspection of a recording (streams, channels, duration, bad channels):
+```bash
+python scripts/explore_recording.py /path/to/data
+```
+
### scripts/preprocess_recording.py
-Automated preprocessing script:
+Automated preprocessing:
```bash
python scripts/preprocess_recording.py /path/to/data --output preprocessed/
```
@@ -263,59 +319,59 @@ Export to Phy for manual curation:
python scripts/export_to_phy.py metrics/analyzer --output phy_export/
```
+### scripts/neuropixels_pipeline.py
+Complete end-to-end pipeline (see [Quick Start](#full-pipeline-bundled-script)).
+
### assets/analysis_template.py
-Complete analysis template. Copy and customize:
+Complete, editable analysis template. Copy and customize:
```bash
cp assets/analysis_template.py my_analysis.py
-# Edit parameters and run
+# Edit the PARAMETERS section, then run
python my_analysis.py
```
-### references/standard_workflow.md
-Detailed step-by-step workflow with explanations for each stage.
-
-### references/api_reference.md
-Quick function reference organized by module.
-
-### references/plotting_guide.md
-Comprehensive visualization guide for publication-quality figures.
-
## Detailed Reference Guides
| Topic | Reference |
|-------|-----------|
| Full workflow | [references/standard_workflow.md](references/standard_workflow.md) |
-| API reference | [references/api_reference.md](references/api_reference.md) |
+| API reference (SpikeInterface) | [references/api_reference.md](references/api_reference.md) |
| Plotting guide | [references/plotting_guide.md](references/plotting_guide.md) |
| Preprocessing | [references/PREPROCESSING.md](references/PREPROCESSING.md) |
| Spike sorting | [references/SPIKE_SORTING.md](references/SPIKE_SORTING.md) |
| Motion correction | [references/MOTION_CORRECTION.md](references/MOTION_CORRECTION.md) |
| Quality metrics | [references/QUALITY_METRICS.md](references/QUALITY_METRICS.md) |
-| Automated curation | [references/AUTOMATED_CURATION.md](references/AUTOMATED_CURATION.md) |
+| Automated & model-based curation | [references/AUTOMATED_CURATION.md](references/AUTOMATED_CURATION.md) |
| AI-assisted curation | [references/AI_CURATION.md](references/AI_CURATION.md) |
| Waveform analysis | [references/ANALYSIS.md](references/ANALYSIS.md) |
## Installation
+Requires Python ≥ 3.10. Using [uv](https://docs.astral.sh/uv/) is recommended.
+
```bash
-# Core packages
-pip install spikeinterface[full] probeinterface neo
+# Core packages (SpikeInterface bundles the curation/model tooling)
+uv pip install "spikeinterface[full]" probeinterface neo
# Spike sorters
-pip install kilosort # Kilosort4 (GPU required)
-pip install spykingcircus # SpykingCircus2 (CPU)
-pip install mountainsort5 # Mountainsort5 (CPU)
+uv pip install kilosort # Kilosort4 (CUDA GPU required)
+uv pip install spykingcircus # SpykingCircus (legacy; SpykingCircus2 ships with SpikeInterface)
+uv pip install mountainsort5 # Mountainsort5 (CPU)
-# Our toolkit
-pip install neuropixels-analysis
+# Model-based curation (UnitRefine) downloads from Hugging Face
+uv pip install "huggingface_hub" skops
-# Optional: AI curation
-pip install anthropic
+# Optional: AI-assisted visual curation
+uv pip install anthropic
-# Optional: IBL tools
-pip install ibl-neuropixel ibllib
+# Optional: IBL tools and Bombcell
+uv pip install ibl-neuropixel ibllib bombcell
```
+For reproducible environments, pin versions (current as of 2026-06: `spikeinterface==0.104.3`,
+`kilosort==4.1.7`, `probeinterface==0.3.2`, `neo==0.14.4`). Unpinned installs are fine for
+quick experimentation but should be pinned in production pipelines.
+
## Project Structure
```
@@ -341,9 +397,10 @@ project/
- **SpikeInterface Docs**: https://spikeinterface.readthedocs.io/
- **Neuropixels Tutorial**: https://spikeinterface.readthedocs.io/en/stable/how_to/analyze_neuropixels.html
+- **Model-based Curation Tutorial**: https://spikeinterface.readthedocs.io/en/stable/tutorials/curation/plot_1_automated_curation.html
+- **UnitRefine Models (Hugging Face)**: https://huggingface.co/SpikeInterface
- **Kilosort4 GitHub**: https://github.com/MouseLand/Kilosort
- **IBL Neuropixel Tools**: https://github.com/int-brain-lab/ibl-neuropixel
- **Allen Institute ecephys**: https://github.com/AllenInstitute/ecephys_spike_sorting
- **Bombcell (Automated QC)**: https://github.com/Julie-Fabre/bombcell
-- **SpikeAgent (AI Curation)**: https://github.com/SpikeAgent/SpikeAgent
-
+- **Awesome Neuropixels**: https://github.com/Julie-Fabre/awesome_neuropixels
diff --git a/skills/neuropixels-analysis/assets/analysis_template.py b/skills/neuropixels-analysis/assets/analysis_template.py
index e6df66a1..e24204a7 100644
--- a/skills/neuropixels-analysis/assets/analysis_template.py
+++ b/skills/neuropixels-analysis/assets/analysis_template.py
@@ -70,7 +70,7 @@ def main():
print("=" * 60)
if DATA_FORMAT == 'spikeglx':
- recording = si.read_spikeglx(DATA_PATH, stream_id=STREAM_ID)
+ recording = si.read_spikeglx(DATA_PATH, stream_name=STREAM_ID)
elif DATA_FORMAT == 'openephys':
recording = si.read_openephys(DATA_PATH)
elif DATA_FORMAT == 'nwb':
@@ -143,7 +143,7 @@ def main():
sorting = si.run_sorter(
SORTER,
rec,
- output_folder=output_path / f'{SORTER}_output',
+ folder=output_path / f'{SORTER}_output',
verbose=True,
**SORTER_PARAMS,
)
diff --git a/skills/neuropixels-analysis/references/AI_CURATION.md b/skills/neuropixels-analysis/references/AI_CURATION.md
index b0d8650b..a2464722 100644
--- a/skills/neuropixels-analysis/references/AI_CURATION.md
+++ b/skills/neuropixels-analysis/references/AI_CURATION.md
@@ -1,345 +1,164 @@
# AI-Assisted Curation Reference
-Guide to using AI visual analysis for unit curation, inspired by SpikeAgent's approach.
-
-## Overview
-
-AI-assisted curation uses vision-language models to analyze spike sorting visualizations,
-providing expert-level quality assessments similar to human curators.
-
-### Workflow
+Use vision-language models to analyze spike-sorting visualizations for borderline units,
+complementing quantitative quality metrics.
```
Traditional: Metrics → Threshold → Labels
-AI-Enhanced: Metrics → AI Visual Analysis → Confidence Score → Labels
+AI-Enhanced: Metrics → Render plots → Vision model → Confidence → Labels
```
-## Claude Code Integration
+> **Credential safety:** never hardcode API keys in analysis scripts — they end up in
+> version control and logs. Read them from environment variables that you set in your shell
+> (e.g. `export ANTHROPIC_API_KEY=...`). All examples below follow this pattern.
-When using this skill within Claude Code, Claude can directly analyze waveform plots without requiring API setup. Simply:
+## Agent integration (no API key needed)
-1. Generate a unit report or plot
-2. Ask Claude to analyze the visualization
-3. Claude will provide expert-level curation decisions
+When you run this skill inside an agent (Cursor, Claude Code, etc.), the agent can inspect
+images directly. Generate a unit summary figure and ask the agent to assess it:
-Example workflow in Claude Code:
```python
-# Generate plots for a unit
-npa.plot_unit_summary(analyzer, unit_id=0, output='unit_0_summary.png')
+import spikeinterface.widgets as sw
+import matplotlib.pyplot as plt
-# Then ask Claude: "Please analyze this unit's waveforms and autocorrelogram
-# to determine if it's a well-isolated single unit, multi-unit activity, or noise"
+sw.plot_unit_summary(analyzer, unit_id=0)
+plt.savefig("unit_0_summary.png", dpi=150, bbox_inches="tight")
+# Then ask the agent: "Is unit 0 a well-isolated single unit, MUA, or noise? Consider
+# waveform consistency, the refractory gap in the autocorrelogram, and amplitude stability."
```
-Claude can assess:
-- Waveform consistency and shape
-- Refractory period violations from autocorrelograms
-- Amplitude stability over time
-- Overall unit isolation quality
+The agent can assess waveform shape/consistency, refractory-period violations, amplitude
+stability over time, and overall isolation quality.
-## Quick Start
+## Programmatic API access
-### Generate Unit Report
+### Render a unit summary image
```python
-import neuropixels_analysis as npa
+import io, base64
+import matplotlib.pyplot as plt
+import spikeinterface.widgets as sw
-# Create visual report for a unit
-report = npa.generate_unit_report(analyzer, unit_id=0, output_dir='reports/')
-
-# Report includes:
-# - Waveforms, templates, autocorrelogram
-# - Amplitudes over time, ISI histogram
-# - Quality metrics summary
-# - Base64 encoded image for API
+def render_unit_image(analyzer, unit_id) -> str:
+ """Return a base64-encoded PNG summary for one unit."""
+ fig = plt.figure(figsize=(12, 8))
+ sw.plot_unit_summary(analyzer, unit_id=unit_id, figure=fig)
+ buf = io.BytesIO()
+ fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
+ plt.close(fig)
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
```
-### AI Visual Analysis
+### Anthropic (Claude) example
```python
+import os
from anthropic import Anthropic
-# Setup API client
-client = Anthropic()
+client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) # set in shell, not in code
-# Analyze single unit
-result = npa.analyze_unit_visually(
- analyzer,
- unit_id=0,
- api_client=client,
- model='claude-opus-4.5',
- task='quality_assessment'
+PROMPT = (
+ "You are an expert electrophysiologist curating a spike-sorted unit. "
+ "Based on the waveform, template, autocorrelogram, amplitude-over-time, and ISI "
+ "histogram, classify this unit as exactly one of: good (well-isolated single unit), "
+ "mua (multi-unit), or noise. Reply with the label and a one-sentence justification."
)
-print(f"Classification: {result['classification']}")
-print(f"Reasoning: {result['reasoning']}")
-```
-
-### Batch Analysis
+def analyze_unit_visually(analyzer, unit_id, model="claude-opus-4-5"):
+ img_b64 = render_unit_image(analyzer, unit_id)
+ msg = client.messages.create(
+ model=model,
+ max_tokens=300,
+ messages=[{
+ "role": "user",
+ "content": [
+ {"type": "image",
+ "source": {"type": "base64", "media_type": "image/png", "data": img_b64}},
+ {"type": "text", "text": PROMPT},
+ ],
+ }],
+ )
+ return msg.content[0].text
-```python
-# Analyze all units
-results = npa.batch_visual_curation(
- analyzer,
- api_client=client,
- output_dir='ai_curation/',
- progress_callback=lambda i, n: print(f"Progress: {i}/{n}")
-)
-
-# Get labels
-ai_labels = {uid: r['classification'] for uid, r in results.items()}
+print(analyze_unit_visually(analyzer, unit_id=0))
```
-## Interactive Curation Session
-
-For human-in-the-loop curation with AI assistance:
+### OpenAI example
```python
-# Create session
-session = npa.CurationSession.create(
- analyzer,
- output_dir='curation_session/',
- sort_by_confidence=True # Show uncertain units first
-)
-
-# Process units
-while True:
- unit = session.current_unit()
- if unit is None:
- break
-
- print(f"Unit {unit.unit_id}:")
- print(f" Auto: {unit.auto_classification} (conf: {unit.confidence:.2f})")
-
- # Generate report
- report = npa.generate_unit_report(analyzer, unit.unit_id)
-
- # Get AI opinion
- ai_result = npa.analyze_unit_visually(analyzer, unit.unit_id, api_client=client)
- session.set_ai_classification(unit.unit_id, ai_result['classification'])
-
- # Human decision
- decision = input("Decision (good/mua/noise/skip): ")
- if decision != 'skip':
- session.set_decision(unit.unit_id, decision)
-
- session.next_unit()
-
-# Export results
-labels = session.get_final_labels()
-session.export_decisions('final_curation.csv')
-```
-
-## Analysis Tasks
-
-### Quality Assessment (Default)
-
-Analyzes waveform shape, refractory period, amplitude stability.
-
-```python
-result = npa.analyze_unit_visually(analyzer, uid, task='quality_assessment')
-# Returns: 'good', 'mua', or 'noise'
-```
-
-### Merge Candidate Detection
-
-Determines if two units should be merged.
-
-```python
-result = npa.analyze_unit_visually(analyzer, uid, task='merge_candidate')
-# Returns: 'merge' or 'keep_separate'
-```
-
-### Drift Assessment
+import os
+from openai import OpenAI
-Evaluates motion/drift in the recording.
+client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
-```python
-result = npa.analyze_unit_visually(analyzer, uid, task='drift_assessment')
-# Returns drift magnitude and correction recommendation
+def analyze_unit_visually_openai(analyzer, unit_id, model="gpt-4o"):
+ img_b64 = render_unit_image(analyzer, unit_id)
+ resp = client.responses.create(
+ model=model,
+ input=[{
+ "role": "user",
+ "content": [
+ {"type": "input_text", "text": PROMPT},
+ {"type": "input_image", "image_url": f"data:image/png;base64,{img_b64}"},
+ ],
+ }],
+ )
+ return resp.output_text
```
-## Custom Prompts
+> Model names change frequently. Use your provider's current vision-capable model
+> (e.g. a current Claude or GPT multimodal model) rather than an old preview ID.
-Create custom analysis prompts:
+## Cost optimization: only call the model on uncertain units
```python
-from neuropixels_analysis.ai_curation import create_curation_prompt
+uncertain = metrics.query(
+ "snr > 2 and snr < 8 and isi_violations_ratio > 0.001 and isi_violations_ratio < 0.1"
+).index.tolist()
-# Get base prompt
-prompt = create_curation_prompt(
- task='quality_assessment',
- additional_context='Focus on waveform amplitude consistency'
-)
-
-# Or fully custom
-custom_prompt = """
-Analyze this unit and determine if it represents a fast-spiking interneuron.
-
-Look for:
-1. Narrow waveform (peak-to-trough < 0.5ms)
-2. High firing rate
-3. Regular ISI distribution
-
-Classify as: FSI (fast-spiking interneuron) or OTHER
-"""
-
-result = npa.analyze_unit_visually(
- analyzer, uid,
- api_client=client,
- custom_prompt=custom_prompt
-)
+ai_labels = {}
+for uid in uncertain:
+ ai_labels[uid] = analyze_unit_visually(analyzer, uid)
```
-## Combining AI with Metrics
-
-Best practice: use both AI and quantitative metrics:
+## Hybrid curation: metrics + AI
```python
-def hybrid_curation(analyzer, metrics, api_client):
- """Combine metrics and AI for robust curation."""
+def hybrid_curation(analyzer, metrics):
labels = {}
-
for unit_id in metrics.index:
row = metrics.loc[unit_id]
-
- # High confidence from metrics alone
- if row['snr'] > 10 and row['isi_violations_ratio'] < 0.001:
- labels[unit_id] = 'good'
- continue
-
- if row['snr'] < 1.5:
- labels[unit_id] = 'noise'
- continue
-
- # Uncertain cases: use AI
- result = npa.analyze_unit_visually(
- analyzer, unit_id, api_client=api_client
- )
- labels[unit_id] = result['classification']
-
+ if row["snr"] > 10 and row["isi_violations_ratio"] < 0.001:
+ labels[unit_id] = "good" # clearly good from metrics
+ elif row["snr"] < 1.5:
+ labels[unit_id] = "noise" # clearly noise from metrics
+ else:
+ labels[unit_id] = analyze_unit_visually(analyzer, unit_id) # ask the model
return labels
```
-## Session Management
-
-### Resume Session
-
-```python
-# Resume interrupted session
-session = npa.CurationSession.load('curation_session/20250101_120000/')
-
-# Check progress
-summary = session.get_summary()
-print(f"Progress: {summary['progress_pct']:.1f}%")
-print(f"Remaining: {summary['remaining']} units")
-
-# Continue from where we left off
-unit = session.current_unit()
-```
-
-### Navigate Session
-
-```python
-# Go to specific unit
-session.go_to_unit(42)
-
-# Previous/next
-session.prev_unit()
-session.next_unit()
-
-# Update decision
-session.set_decision(42, 'good', notes='Clear refractory period')
-```
-
-### Export Results
-
-```python
-# Get final labels (priority: human > AI > auto)
-labels = session.get_final_labels()
-
-# Export detailed results
-df = session.export_decisions('curation_results.csv')
-
-# Summary
-summary = session.get_summary()
-print(f"Good: {summary['decisions'].get('good', 0)}")
-print(f"MUA: {summary['decisions'].get('mua', 0)}")
-print(f"Noise: {summary['decisions'].get('noise', 0)}")
-```
-
-## Visual Report Components
-
-The generated report includes 6 panels:
+## What each panel tells you
-| Panel | Content | What to Look For |
+| Panel | Content | What to look for |
|-------|---------|------------------|
| Waveforms | Individual spike waveforms | Consistency, shape |
| Template | Mean ± std | Clean negative peak, physiological shape |
-| Autocorrelogram | Spike timing | Gap at 0ms (refractory period) |
+| Autocorrelogram | Spike timing | Gap at 0 ms (refractory period) |
| Amplitudes | Amplitude over time | Stability, no drift |
-| ISI Histogram | Inter-spike intervals | Refractory gap < 1.5ms |
-| Metrics | Quality numbers | SNR, ISI violations, presence |
-
-## API Support
-
-Currently supported APIs:
-
-| Provider | Client | Model Examples |
-|----------|--------|----------------|
-| Anthropic | `anthropic.Anthropic()` | claude-opus-4.5 |
-| OpenAI | `openai.OpenAI()` | gpt-4-vision-preview |
-| Google | `google.generativeai` | gemini-pro-vision |
-
-### Anthropic Example
-
-```python
-from anthropic import Anthropic
-
-client = Anthropic(api_key="your-api-key")
-result = npa.analyze_unit_visually(analyzer, uid, api_client=client)
-```
-
-### OpenAI Example
-
-```python
-from openai import OpenAI
-
-client = OpenAI(api_key="your-api-key")
-result = npa.analyze_unit_visually(
- analyzer, uid,
- api_client=client,
- model='gpt-4-vision-preview'
-)
-```
+| ISI histogram | Inter-spike intervals | Refractory gap < ~1.5 ms |
## Best Practices
-1. **Use AI for uncertain cases** - Don't waste API calls on obvious good/noise units
-2. **Combine with metrics** - AI should supplement, not replace, quantitative measures
-3. **Human oversight** - Review AI decisions, especially for important analyses
-4. **Save sessions** - Always use CurationSession to track decisions
-5. **Document reasoning** - Use notes field to record decision rationale
-
-## Cost Optimization
-
-```python
-# Only use AI for uncertain units
-uncertain_units = metrics.query("""
- snr > 2 and snr < 8 and
- isi_violations_ratio > 0.001 and isi_violations_ratio < 0.1
-""").index.tolist()
-
-# Batch process only these
-results = npa.batch_visual_curation(
- analyzer,
- unit_ids=uncertain_units,
- api_client=client
-)
-```
+1. **Use AI for uncertain cases** — don't spend API calls on obvious good/noise units.
+2. **Combine with metrics and model-based curation** — AI supplements, not replaces,
+ quantitative measures (see [AUTOMATED_CURATION.md](AUTOMATED_CURATION.md)).
+3. **Keep a human in the loop** for important analyses.
+4. **Record reasoning** for each decision for reproducibility.
+5. **Never commit credentials** — keep keys in environment variables.
## References
-- [SpikeAgent](https://github.com/SpikeAgent/SpikeAgent) - AI-powered spike sorting assistant
-- [Anthropic Vision API](https://docs.anthropic.com/en/docs/vision)
-- [GPT-4 Vision](https://platform.openai.com/docs/guides/vision)
+- [Anthropic Vision API](https://docs.anthropic.com/en/docs/build-with-claude/vision)
+- [OpenAI Vision/Images](https://platform.openai.com/docs/guides/images-vision)
+- [SpikeInterface model-based curation](https://spikeinterface.readthedocs.io/en/stable/tutorials/curation/plot_1_automated_curation.html)
+- [SpikeAgent](https://github.com/SpikeAgent/SpikeAgent) — AI-powered spike-sorting assistant
diff --git a/skills/neuropixels-analysis/references/ANALYSIS.md b/skills/neuropixels-analysis/references/ANALYSIS.md
index bf20d133..48f64689 100644
--- a/skills/neuropixels-analysis/references/ANALYSIS.md
+++ b/skills/neuropixels-analysis/references/ANALYSIS.md
@@ -254,7 +254,7 @@ si.plot_unit_summary(analyzer, unit_id=0)
### Load LFP Data
```python
-lfp = si.read_spikeglx('/path/to/data', stream_id='imec0.lf')
+lfp = si.read_spikeglx('/path/to/data', stream_name='imec0.lf')
print(f"LFP: {lfp.get_sampling_frequency()} Hz")
```
diff --git a/skills/neuropixels-analysis/references/AUTOMATED_CURATION.md b/skills/neuropixels-analysis/references/AUTOMATED_CURATION.md
index 4efc4819..3bafed81 100644
--- a/skills/neuropixels-analysis/references/AUTOMATED_CURATION.md
+++ b/skills/neuropixels-analysis/references/AUTOMATED_CURATION.md
@@ -69,8 +69,8 @@ unit_labels = results['unit_labels']
```python
import spikeinterface.full as si
-# After spike sorting
-sorting = si.run_sorter('kilosort4', recording, output_folder='ks4/')
+# After spike sorting (run_sorter uses folder=, not output_folder=)
+sorting = si.run_sorter('kilosort4', recording, folder='ks4/')
# Create analyzer and compute required extensions
analyzer = si.create_sorting_analyzer(sorting, recording, sparse=True)
@@ -116,6 +116,81 @@ results = bc.run_bombcell(
)
```
+## UnitRefine: Model-Based Curation
+
+SpikeInterface ships pretrained machine-learning classifiers (the **UnitRefine** family) and
+a loader for any scikit-learn pipeline shared on Hugging Face. Instead of hand-tuning
+thresholds, you pass a `SortingAnalyzer` (with quality + template metrics computed) and the
+model predicts a label and confidence per unit.
+
+### Prepare the analyzer
+
+The model needs the metrics it was trained on. Compute quality metrics and template metrics:
+
+```python
+import spikeinterface.full as si
+import spikeinterface.curation as sc
+
+analyzer = si.create_sorting_analyzer(sorting, recording, sparse=True, folder='analyzer/')
+analyzer.compute([
+ 'noise_levels', 'random_spikes', 'waveforms', 'templates',
+ 'spike_locations', 'spike_amplitudes', 'correlograms',
+ 'principal_components', 'quality_metrics', 'template_metrics',
+])
+analyzer.compute('template_metrics', include_multi_channel_metrics=True)
+```
+
+### Apply the UnitRefine classifiers
+
+The recommended flow chains two models: first noise vs neural, then SUA vs MUA on the
+neural units. These models were trained on real Neuropixels data (V1, SC, ALM from 11 mice):
+
+```python
+# 1) noise vs neural
+noise_labels = sc.model_based_label_units(
+ sorting_analyzer=analyzer,
+ repo_id='SpikeInterface/UnitRefine_noise_neural_classifier',
+ trust_model=True,
+)
+neural = analyzer.remove_units(noise_labels[noise_labels['prediction'] == 'noise'].index)
+
+# 2) single-unit (sua) vs multi-unit (mua)
+sua_mua_labels = sc.model_based_label_units(
+ sorting_analyzer=neural,
+ repo_id='SpikeInterface/UnitRefine_sua_mua_classifier',
+ trust_model=True,
+)
+
+import pandas as pd
+all_labels = pd.concat(
+ [sua_mua_labels, noise_labels[noise_labels['prediction'] == 'noise']]
+).sort_index()
+print(all_labels) # columns: prediction, probability
+```
+
+### Loading a model explicitly
+
+```python
+model, model_info = sc.load_model(
+ repo_id='SpikeInterface/toy_tetrode_model',
+ trusted=['numpy.dtype'],
+)
+print(model.feature_names_in_) # metrics the model expects
+print(model_info['label_conversion']) # integer -> human-readable label
+
+# Apply a model from a local folder
+labels = sc.model_based_label_units(sorting_analyzer=analyzer, model_folder='path/to/model/')
+```
+
+### Security and validation notes
+
+- `trust_model=True` (or an explicit `trusted=[...]` list) is required to unpack the
+ `.skops` model file. Only load models from sources you trust — treat `.skops`/`.pkl`
+ files like any other executable artifact.
+- Models trained on one brain area/dataset may not transfer. Use the confidence
+ (`probability`) to decide which units to auto-accept vs. send to manual review, and
+ validate against a manually labelled subset before trusting a model on new data.
+
## SpikeInterface Auto-Curation
### Threshold-Based Curation
@@ -227,12 +302,12 @@ unique_ids = um.get_unique_ids()
# 3. Run UnitMatch for cross-session tracking
# Session 1
-sorting1 = si.run_sorter('kilosort4', rec1, output_folder='session1/ks4/')
+sorting1 = si.run_sorter('kilosort4', rec1, folder='session1/ks4/')
# Run Bombcell
labels1 = bc.run_bombcell('session1/ks4/', raw1_path)
# Session 2
-sorting2 = si.run_sorter('kilosort4', rec2, output_folder='session2/ks4/')
+sorting2 = si.run_sorter('kilosort4', rec2, folder='session2/ks4/')
labels2 = bc.run_bombcell('session2/ks4/', raw2_path)
# Track units across sessions
@@ -284,7 +359,7 @@ manual_labels = si.read_phy('phy_review/').get_property('quality')
| **Manual (Phy)** | Gold standard, flexible | Slow, subjective |
| **SpikeInterface QM** | Fast, reproducible | Simple thresholds only |
| **Bombcell** | Multi-class, validated | Requires waveform extraction |
-| **UnitRefine** | ML-based, learns from data | Needs training data |
+| **UnitRefine** | ML-based, pretrained models on Hugging Face | May not transfer across datasets |
## Best Practices
@@ -354,5 +429,7 @@ sorting_curated, labels = curate_sorting(sorting, recording, 'output/')
- [Bombcell GitHub](https://github.com/Julie-Fabre/bombcell)
- [UnitMatch GitHub](https://github.com/EnnyvanBeest/UnitMatch)
- [SpikeInterface Curation](https://spikeinterface.readthedocs.io/en/stable/modules/curation.html)
+- [Model-based curation tutorial](https://spikeinterface.readthedocs.io/en/stable/tutorials/curation/plot_1_automated_curation.html)
+- [UnitRefine models (Hugging Face)](https://huggingface.co/SpikeInterface)
- Fabre et al. (2023) "Bombcell: automated curation and cell classification"
- van Beest et al. (2024) "UnitMatch: tracking neurons across days with high-density probes"
diff --git a/skills/neuropixels-analysis/references/MOTION_CORRECTION.md b/skills/neuropixels-analysis/references/MOTION_CORRECTION.md
index 488860d3..72d9719e 100644
--- a/skills/neuropixels-analysis/references/MOTION_CORRECTION.md
+++ b/skills/neuropixels-analysis/references/MOTION_CORRECTION.md
@@ -200,7 +200,7 @@ rec_corrected = rec_corrected.save(folder='preprocessed_motion_corrected/',
format='binary', n_jobs=8)
# Run spike sorting on corrected data
-sorting = si.run_sorter('kilosort4', rec_corrected, output_folder='ks4/')
+sorting = si.run_sorter('kilosort4', rec_corrected, folder='ks4/')
```
### Option 2: Let Kilosort Handle It
@@ -211,7 +211,7 @@ Kilosort 2.5+ has built-in drift correction:
sorting = si.run_sorter(
'kilosort4',
rec, # Not motion corrected
- output_folder='ks4/',
+ folder='ks4/',
nblocks=5, # Non-rigid blocks for drift correction
do_correction=True # Enable Kilosort's drift correction
)
@@ -221,7 +221,7 @@ sorting = si.run_sorter(
```python
# Sort first
-sorting = si.run_sorter('kilosort4', rec, output_folder='ks4/')
+sorting = si.run_sorter('kilosort4', rec, folder='ks4/')
# Then estimate motion from sorted spikes
# (More accurate as it uses actual spike times)
diff --git a/skills/neuropixels-analysis/references/PREPROCESSING.md b/skills/neuropixels-analysis/references/PREPROCESSING.md
index bc5117e8..fe5ffc95 100644
--- a/skills/neuropixels-analysis/references/PREPROCESSING.md
+++ b/skills/neuropixels-analysis/references/PREPROCESSING.md
@@ -8,7 +8,7 @@ Comprehensive preprocessing techniques for Neuropixels neural recordings.
import spikeinterface.full as si
# Load raw data
-recording = si.read_spikeglx('/path/to/data', stream_id='imec0.ap')
+recording = si.read_spikeglx('/path/to/data', stream_name='imec0.ap')
# 1. Phase shift correction (for Neuropixels 1.0)
rec = si.phase_shift(recording)
@@ -226,7 +226,7 @@ def preprocess_neuropixels(data_path, output_path):
"""Standard Neuropixels preprocessing pipeline."""
# Load data
- recording = si.read_spikeglx(data_path, stream_id='imec0.ap')
+ recording = si.read_spikeglx(data_path, stream_name='imec0.ap')
print(f"Loaded: {recording.get_num_channels()} channels, "
f"{recording.get_total_duration():.1f}s")
diff --git a/skills/neuropixels-analysis/references/SPIKE_SORTING.md b/skills/neuropixels-analysis/references/SPIKE_SORTING.md
index 085fc63a..adae1a7b 100644
--- a/skills/neuropixels-analysis/references/SPIKE_SORTING.md
+++ b/skills/neuropixels-analysis/references/SPIKE_SORTING.md
@@ -28,7 +28,7 @@ import spikeinterface.full as si
sorting = si.run_sorter(
'kilosort4',
recording,
- output_folder='ks4_output',
+ folder='ks4_output',
verbose=True
)
@@ -40,7 +40,7 @@ print(f"Found {len(sorting.unit_ids)} units")
sorting = si.run_sorter(
'kilosort4',
recording,
- output_folder='ks4_output',
+ folder='ks4_output',
# Detection
Th_universal=9, # Spike detection threshold
Th_learned=8, # Learned threshold
@@ -92,7 +92,7 @@ ks4_params = {
sorting = si.run_sorter(
'kilosort3',
recording,
- output_folder='ks3_output',
+ folder='ks3_output',
# Key parameters
detect_threshold=6,
projection_threshold=[9, 9],
@@ -114,7 +114,7 @@ pip install spykingcircus
sorting = si.run_sorter(
'spykingcircus2',
recording,
- output_folder='sc2_output',
+ folder='sc2_output',
# Parameters
detect_threshold=5,
selection_method='all',
@@ -133,7 +133,7 @@ pip install mountainsort5
sorting = si.run_sorter(
'mountainsort5',
recording,
- output_folder='ms5_output',
+ folder='ms5_output',
# Parameters
detect_threshold=5.0,
scheme='2', # '1', '2', or '3'
@@ -145,9 +145,9 @@ sorting = si.run_sorter(
### Compare Sorters
```python
# Run multiple sorters
-sorting_ks4 = si.run_sorter('kilosort4', recording, output_folder='ks4/')
-sorting_sc2 = si.run_sorter('spykingcircus2', recording, output_folder='sc2/')
-sorting_ms5 = si.run_sorter('mountainsort5', recording, output_folder='ms5/')
+sorting_ks4 = si.run_sorter('kilosort4', recording, folder='ks4/')
+sorting_sc2 = si.run_sorter('spykingcircus2', recording, folder='sc2/')
+sorting_ms5 = si.run_sorter('mountainsort5', recording, folder='ms5/')
# Compare results
comparison = si.compare_multiple_sorters(
@@ -176,7 +176,7 @@ sorting_ensemble = si.create_ensemble_sorting(
sorting = si.run_sorter(
'kilosort3',
recording,
- output_folder='ks3_docker/',
+ folder='ks3_docker/',
docker_image='spikeinterface/kilosort3-compiled-base:latest',
verbose=True
)
@@ -187,7 +187,7 @@ sorting = si.run_sorter(
sorting = si.run_sorter(
'kilosort3',
recording,
- output_folder='ks3_singularity/',
+ folder='ks3_singularity/',
singularity_image='/path/to/kilosort3.sif',
verbose=True
)
@@ -199,7 +199,7 @@ sorting = si.run_sorter(
```python
# Multiple recording files
recordings = [
- si.read_spikeglx(f'/path/to/recording_{i}', stream_id='imec0.ap')
+ si.read_spikeglx(f'/path/to/recording_{i}', stream_name='imec0.ap')
for i in range(3)
]
@@ -207,7 +207,7 @@ recordings = [
recording_concat = si.concatenate_recordings(recordings)
# Sort
-sorting = si.run_sorter('kilosort4', recording_concat, output_folder='ks4/')
+sorting = si.run_sorter('kilosort4', recording_concat, folder='ks4/')
# Split back by original recording
sortings_split = si.split_sorting(sorting, recording_concat)
@@ -225,7 +225,7 @@ for i, segment in enumerate(recording.split_by_times([0, 3600, 7200, 10800])):
sorting_seg = si.run_sorter(
'kilosort4',
segment,
- output_folder=segments_output / f'segment_{i}'
+ folder=segments_output / f'segment_{i}'
)
sortings.append(sorting_seg)
```
@@ -302,7 +302,7 @@ for unit_id in sorting.unit_ids:
sorting = si.run_sorter(
'kilosort4',
recording,
- output_folder='ks4/',
+ folder='ks4/',
batch_size=30000 # Smaller batch
)
```
@@ -313,7 +313,7 @@ sorting = si.run_sorter(
sorting = si.run_sorter(
'kilosort4',
recording,
- output_folder='ks4/',
+ folder='ks4/',
Th_universal=7, # Lower from default 9
Th_learned=6
)
@@ -325,7 +325,7 @@ sorting = si.run_sorter(
sorting = si.run_sorter(
'kilosort4',
recording,
- output_folder='ks4/',
+ folder='ks4/',
dmin=20, # Increase from 15
dminx=16 # Increase from 12
)
diff --git a/skills/neuropixels-analysis/references/api_reference.md b/skills/neuropixels-analysis/references/api_reference.md
index 01f9032d..c9c3d474 100644
--- a/skills/neuropixels-analysis/references/api_reference.md
+++ b/skills/neuropixels-analysis/references/api_reference.md
@@ -1,415 +1,229 @@
-# API Reference
+# API Reference (SpikeInterface)
-Quick reference for neuropixels_analysis functions organized by module.
-
-## Core Module
-
-### load_recording
+Quick reference for the SpikeInterface functions used throughout this skill. Import with:
```python
-npa.load_recording(
- path: str,
- format: str = 'auto', # 'spikeglx', 'openephys', 'nwb'
- stream_id: str = None, # e.g., 'imec0.ap'
-) -> Recording
+import spikeinterface.full as si
+import spikeinterface.curation as sc
+import spikeinterface.widgets as sw
```
-Load Neuropixels recording from various formats.
-
-### run_pipeline
+All examples target SpikeInterface ≥ 0.104. Set global parallelization once:
```python
-npa.run_pipeline(
- recording: Recording,
- output_dir: str,
- sorter: str = 'kilosort4',
- preprocess: bool = True,
- correct_motion: bool = True,
- postprocess: bool = True,
- curate: bool = True,
- curation_method: str = 'allen',
-) -> dict
+si.set_global_job_kwargs(n_jobs=-1, chunk_duration="1s", progress_bar=True)
```
-Run complete analysis pipeline. Returns dictionary with all results.
-
-## Preprocessing Module
+## Loading
-### preprocess
+### Inspect streams
```python
-npa.preprocess(
- recording: Recording,
- freq_min: float = 300,
- freq_max: float = 6000,
- phase_shift: bool = True,
- common_ref: bool = True,
- bad_channel_detection: bool = True,
-) -> Recording
+stream_names, stream_ids = si.get_neo_streams("spikeglx", "/path/to/run_g0/")
+# stream_names -> ['imec0.ap', 'imec0.lf', 'nidq']
```
-Apply standard preprocessing chain.
-
-### detect_bad_channels
+### Readers
```python
-npa.detect_bad_channels(
- recording: Recording,
- method: str = 'coherence+psd',
- **kwargs,
-) -> list
+si.read_spikeglx(folder_path, stream_name="imec0.ap", load_sync_channel=False)
+si.read_openephys(folder_path, stream_name=None)
+si.read_nwb(file_path)
```
-Detect and return list of bad channel IDs.
+Prefer `stream_name` (a value from `get_neo_streams`) over `stream_id`.
-### apply_filters
+### Recording introspection
```python
-npa.apply_filters(
- recording: Recording,
- freq_min: float = 300,
- freq_max: float = 6000,
- filter_type: str = 'bandpass',
-) -> Recording
+recording.get_num_channels()
+recording.get_total_duration() # seconds
+recording.get_sampling_frequency() # Hz
+recording.get_channel_locations()
+recording.get_probe()
+recording.frame_slice(start_frame, end_frame)
```
-Apply frequency filters.
-
-### common_reference
+## Preprocessing
```python
-npa.common_reference(
- recording: Recording,
- operator: str = 'median',
- reference: str = 'global',
-) -> Recording
+si.highpass_filter(recording, freq_min=400.0)
+si.bandpass_filter(recording, freq_min=300.0, freq_max=6000.0)
+si.phase_shift(recording) # ADC phase correction (NP 1.0)
+si.detect_bad_channels(recording) # -> (bad_channel_ids, channel_labels)
+recording.remove_channels(bad_channel_ids)
+si.common_reference(recording, operator="median", reference="global")
+si.highpass_spatial_filter(recording) # IBL-style destriping
+si.get_noise_levels(recording, return_in_uV=False)
+recording.save(folder="preprocessed/", format="binary")
```
-Apply common reference (CMR/CAR).
+> `detect_bad_channels` returns a 2-tuple; always unpack both values.
-## Motion Module
-
-### check_drift
+## Drift detection and motion correction
```python
-npa.check_drift(
- recording: Recording,
- plot: bool = True,
- output: str = None,
-) -> dict
-```
+from spikeinterface.sortingcomponents.peak_detection import detect_peaks
+from spikeinterface.sortingcomponents.peak_localization import localize_peaks
-Check recording for drift. Returns drift statistics.
+peaks = detect_peaks(rec, method="locally_exclusive", noise_levels=noise_levels,
+ detect_threshold=5, radius_um=50.0)
+peak_locations = localize_peaks(rec, peaks, method="center_of_mass")
-### estimate_motion
-
-```python
-npa.estimate_motion(
- recording: Recording,
- preset: str = 'kilosort_like',
- **kwargs,
-) -> dict
+# One-call correction with a preset
+rec_corrected = si.correct_motion(rec, preset="nonrigid_fast_and_accurate", folder="motion/")
```
-Estimate motion without applying correction.
+**Presets:** `rigid_fast`, `kilosort_like`, `nonrigid_accurate`,
+`nonrigid_fast_and_accurate` (recommended default), `dredge`, `dredge_fast`.
-### correct_motion
+## Spike sorting
```python
-npa.correct_motion(
- recording: Recording,
- preset: str = 'nonrigid_accurate',
- folder: str = None,
- **kwargs,
-) -> Recording
-```
-
-Apply motion correction.
-
-**Presets:**
-- `'kilosort_like'`: Fast, rigid correction
-- `'nonrigid_accurate'`: Slower, better for severe drift
-- `'nonrigid_fast_and_accurate'`: Balanced option
+si.installed_sorters()
+si.available_sorters()
+si.get_default_sorter_params("kilosort4")
-## Sorting Module
-
-### run_sorting
-
-```python
-npa.run_sorting(
- recording: Recording,
- sorter: str = 'kilosort4',
- output_folder: str = None,
- sorter_params: dict = None,
- **kwargs,
-) -> Sorting
-```
-
-Run spike sorter.
-
-**Supported sorters:**
-- `'kilosort4'`: GPU-based, recommended
-- `'kilosort3'`: Legacy, requires MATLAB
-- `'spykingcircus2'`: CPU-based alternative
-- `'mountainsort5'`: Fast, good for short recordings
+sorting = si.run_sorter(
+ "kilosort4", # sorter name
+ recording,
+ folder="ks4_output", # NOT output_folder (deprecated)
+ verbose=True,
+ # sorter-specific kwargs, e.g. Th_universal=9, Th_learned=8, nblocks=5, batch_size=60000
+)
-### compare_sorters
+# Containerized external sorters (no local install needed)
+si.run_sorter("kilosort2_5", recording, folder="ks25/", docker_image=True)
-```python
-npa.compare_sorters(
- sortings: list,
- delta_time: float = 0.4, # ms
- match_score: float = 0.5,
-) -> Comparison
+# Read a sorter folder back
+sorting = si.read_sorter_folder("ks4_output")
```
-Compare results from multiple sorters.
-
-## Postprocessing Module
-
-### create_analyzer
+**Sorting introspection:**
```python
-npa.create_analyzer(
- sorting: Sorting,
- recording: Recording,
- output_folder: str = None,
- sparse: bool = True,
-) -> SortingAnalyzer
+sorting.unit_ids
+sorting.get_total_num_spikes()
+sorting.get_unit_spike_train(unit_id)
+sorting.select_units(unit_ids)
+sorting.to_spike_vector()
```
-Create SortingAnalyzer for postprocessing.
-
-### postprocess
+## Postprocessing: SortingAnalyzer
```python
-npa.postprocess(
- sorting: Sorting,
- recording: Recording,
- output_folder: str = None,
- compute_all: bool = True,
- n_jobs: int = -1,
-) -> tuple[SortingAnalyzer, DataFrame]
-```
-
-Full postprocessing. Returns (analyzer, metrics).
-
-### compute_quality_metrics
-
-```python
-npa.compute_quality_metrics(
- analyzer: SortingAnalyzer,
- metric_names: list = None, # None = all
- **kwargs,
-) -> DataFrame
-```
-
-Compute quality metrics for all units.
-
-**Available metrics:**
-- `snr`: Signal-to-noise ratio
-- `isi_violations_ratio`: ISI violations
-- `presence_ratio`: Recording presence
-- `amplitude_cutoff`: Amplitude distribution cutoff
-- `firing_rate`: Average firing rate
-- `amplitude_cv`: Amplitude coefficient of variation
-- `sliding_rp_violation`: Sliding window refractory violations
-- `d_prime`: Isolation quality
-- `nearest_neighbor`: Nearest-neighbor overlap
-
-## Curation Module
-
-### curate
+analyzer = si.create_sorting_analyzer(
+ sorting, recording,
+ sparse=True,
+ format="binary_folder", # or "memory" / "zarr"
+ folder="analyzer/",
+)
-```python
-npa.curate(
- metrics: DataFrame,
- method: str = 'allen', # 'allen', 'ibl', 'strict', 'custom'
- **thresholds,
-) -> dict
-```
+# Extensions (order matters: random_spikes -> waveforms -> templates -> ...)
+analyzer.compute("random_spikes", method="uniform", max_spikes_per_unit=500)
+analyzer.compute("waveforms", ms_before=1.0, ms_after=2.0)
+analyzer.compute("templates", operators=["average", "std"])
+analyzer.compute("noise_levels")
+analyzer.compute("spike_amplitudes")
+analyzer.compute("correlograms", window_ms=50.0, bin_ms=1.0)
+analyzer.compute("unit_locations", method="monopolar_triangulation")
+analyzer.compute("spike_locations", method="center_of_mass")
+analyzer.compute("template_similarity")
+analyzer.compute("principal_components", n_components=5, mode="by_channel_local")
-Apply automated curation. Returns {unit_id: label}.
+# Or compute several at once
+analyzer.compute(["random_spikes", "waveforms", "templates", "noise_levels"])
-### auto_classify
+# Access extension data
+analyzer.get_extension("quality_metrics").get_data()
+analyzer.get_extension("templates").get_unit_template(unit_id, operator="average")
-```python
-npa.auto_classify(
- metrics: DataFrame,
- snr_threshold: float = 5.0,
- isi_threshold: float = 0.01,
- presence_threshold: float = 0.9,
-) -> dict
+# Persist / reload / subset
+si.load_sorting_analyzer("analyzer/")
+analyzer.select_units(unit_ids, folder="analyzer_clean/", format="binary_folder")
+analyzer.remove_units(unit_ids)
```
-Classify units based on custom thresholds.
-
-### filter_units
+## Quality metrics
```python
-npa.filter_units(
- sorting: Sorting,
- labels: dict,
- keep: list = ['good'],
-) -> Sorting
-```
-
-Filter sorting to keep only specified labels.
-
-## AI Curation Module
-
-### generate_unit_report
+metric_names = ["firing_rate", "presence_ratio", "snr", "isi_violation",
+ "amplitude_cutoff", "amplitude_cv", "sliding_rp_violation"]
+analyzer.compute("quality_metrics", metric_names=metric_names)
+metrics = analyzer.get_extension("quality_metrics").get_data()
-```python
-npa.generate_unit_report(
- analyzer: SortingAnalyzer,
- unit_id: int,
- output_dir: str = None,
- figsize: tuple = (16, 12),
-) -> dict
+# Equivalent standalone helper
+metrics = si.compute_quality_metrics(analyzer, metric_names=metric_names)
```
-Generate visual report for AI analysis.
+**Common columns:** `snr`, `firing_rate`, `presence_ratio`, `amplitude_cutoff`,
+`isi_violations_ratio`, `isi_violations_count`. PCA-based metrics
+(`isolation_distance`, `l_ratio`, `d_prime`, `nn_hit_rate`) require
+`analyzer.compute("principal_components")` first.
-Returns:
-- `'image_path'`: Path to saved figure
-- `'image_base64'`: Base64 encoded image
-- `'metrics'`: Quality metrics dict
-- `'unit_id'`: Unit ID
+## Curation
-### analyze_unit_visually
+### Threshold-based
```python
-npa.analyze_unit_visually(
- analyzer: SortingAnalyzer,
- unit_id: int,
- api_client: Any = None,
- model: str = 'claude-opus-4.5',
- task: str = 'quality_assessment',
- custom_prompt: str = None,
-) -> dict
+query = "(amplitude_cutoff < 0.1) & (isi_violations_ratio < 0.5) & (presence_ratio > 0.9)"
+good_unit_ids = metrics.query(query).index.values
+clean = sorting.select_units(good_unit_ids)
```
-Analyze unit using vision-language model.
-
-**Tasks:**
-- `'quality_assessment'`: Classify as good/mua/noise
-- `'merge_candidate'`: Check if units should merge
-- `'drift_assessment'`: Assess motion/drift
-
-### batch_visual_curation
+### Model-based (UnitRefine / Hugging Face)
```python
-npa.batch_visual_curation(
- analyzer: SortingAnalyzer,
- unit_ids: list = None,
- api_client: Any = None,
- model: str = 'claude-opus-4.5',
- output_dir: str = None,
- progress_callback: callable = None,
-) -> dict
-```
+import spikeinterface.curation as sc
-Run visual curation on multiple units.
-
-### CurationSession
-
-```python
-session = npa.CurationSession.create(
- analyzer: SortingAnalyzer,
- output_dir: str,
- session_id: str = None,
- unit_ids: list = None,
- sort_by_confidence: bool = True,
+labels = sc.model_based_label_units(
+ sorting_analyzer=analyzer,
+ repo_id="SpikeInterface/UnitRefine_noise_neural_classifier",
+ trust_model=True,
)
+# labels -> DataFrame with 'prediction' and 'probability' columns
-# Navigation
-session.current_unit() -> UnitCuration
-session.next_unit() -> UnitCuration
-session.prev_unit() -> UnitCuration
-session.go_to_unit(unit_id: int) -> UnitCuration
-
-# Decisions
-session.set_decision(unit_id, decision, notes='')
-session.set_ai_classification(unit_id, classification)
-
-# Export
-session.get_final_labels() -> dict
-session.export_decisions(output_path) -> DataFrame
-session.get_summary() -> dict
-
-# Persistence
-session.save()
-session = npa.CurationSession.load(session_dir)
+# Load a model object explicitly (e.g. to inspect feature_names_in_)
+model, model_info = sc.load_model(repo_id="SpikeInterface/toy_tetrode_model", trusted=["numpy.dtype"])
```
-## Visualization Module
-
-### plot_drift
+### Manual edits
```python
-npa.plot_drift(
- recording: Recording,
- motion: dict = None,
- output: str = None,
- figsize: tuple = (12, 8),
-)
+from spikeinterface.curation import CurationSorting
+cur = CurationSorting(sorting)
+cur.remove_units(noise_unit_ids)
+sorting_curated = cur.sorting
```
-Plot drift/motion map.
-
-### plot_quality_metrics
+## Visualization (widgets)
```python
-npa.plot_quality_metrics(
- analyzer: SortingAnalyzer,
- metrics: DataFrame = None,
- output: str = None,
-)
+sw.plot_probe_map(recording, with_channel_ids=True)
+sw.plot_traces({"filtered": rec1, "cmr": rec2}, backend="matplotlib", clim=(-50, 50))
+si.plot_drift_raster_map(peaks=peaks, peak_locations=peak_locations, recording=rec, clim=(-50, 50))
+sw.plot_unit_waveforms(analyzer, unit_ids=[0])
+sw.plot_unit_templates(analyzer, unit_ids=[0, 1, 2])
+sw.plot_autocorrelograms(analyzer, unit_ids=[0])
+sw.plot_amplitudes(analyzer, unit_ids=[0], plot_histograms=True)
+sw.plot_unit_locations(analyzer)
+si.plot_sorting_summary(analyzer, backend="sortingview") # web-based viewer
```
-Plot quality metrics overview.
+See [plotting_guide.md](plotting_guide.md) for publication-quality figure recipes.
-### plot_unit_summary
+## Export
```python
-npa.plot_unit_summary(
- analyzer: SortingAnalyzer,
- unit_id: int,
- output: str = None,
-)
-```
-
-Plot comprehensive unit summary.
+si.export_to_phy(analyzer, output_folder="phy_export/",
+ compute_pc_features=True, compute_amplitudes=True, copy_binary=True)
+si.export_report(analyzer, "report/", format="png")
-## SpikeInterface Integration
+from spikeinterface.exporters import export_to_nwb
+export_to_nwb(analyzer, "output.nwb")
-All neuropixels_analysis functions work with SpikeInterface objects:
-
-```python
-import spikeinterface.full as si
-import neuropixels_analysis as npa
-
-# SpikeInterface recording works with npa functions
-recording = si.read_spikeglx('/path/')
-rec = npa.preprocess(recording)
-
-# Access SpikeInterface directly for advanced usage
-rec_filtered = si.bandpass_filter(recording, freq_min=300, freq_max=6000)
+si.read_phy("phy_export/") # load Phy curation back
```
-## Common Parameters
-
-### Recording parameters
-- `freq_min`: Highpass cutoff (Hz)
-- `freq_max`: Lowpass cutoff (Hz)
-- `n_jobs`: Parallel jobs (-1 = all cores)
-
-### Sorting parameters
-- `output_folder`: Where to save results
-- `sorter_params`: Dict of sorter-specific params
-
-### Quality metric thresholds
-- `snr_threshold`: SNR cutoff (typically 5)
-- `isi_threshold`: ISI violations cutoff (typically 0.01)
-- `presence_threshold`: Presence ratio cutoff (typically 0.9)
+> Note: `export_to_phy` / `export_report` take `output_folder` — this is correct and
+> distinct from `run_sorter`/`create_sorting_analyzer`, which take `folder`.
diff --git a/skills/neuropixels-analysis/references/plotting_guide.md b/skills/neuropixels-analysis/references/plotting_guide.md
index 3c07056e..4eedbee6 100644
--- a/skills/neuropixels-analysis/references/plotting_guide.md
+++ b/skills/neuropixels-analysis/references/plotting_guide.md
@@ -9,7 +9,6 @@ import matplotlib.pyplot as plt
import numpy as np
import spikeinterface.full as si
import spikeinterface.widgets as sw
-import neuropixels_analysis as npa
# High-quality settings
plt.rcParams['figure.dpi'] = 150
@@ -23,16 +22,15 @@ plt.rcParams['font.family'] = 'sans-serif'
### Basic Drift Map
```python
-# Using npa
-npa.plot_drift(recording, output='drift_map.png')
+from spikeinterface.sortingcomponents.peak_detection import detect_peaks
+from spikeinterface.sortingcomponents.peak_localization import localize_peaks
-# Using SpikeInterface widgets
-from spikeinterface.preprocessing import detect_peaks, localize_peaks
-
-peaks = detect_peaks(recording, method='locally_exclusive')
+noise_levels = si.get_noise_levels(recording, return_in_uV=False)
+peaks = detect_peaks(recording, method='locally_exclusive', noise_levels=noise_levels,
+ detect_threshold=5, radius_um=50.0)
peak_locations = localize_peaks(recording, peaks, method='center_of_mass')
-sw.plot_drift_raster_map(
+si.plot_drift_raster_map(
peaks=peaks,
peak_locations=peak_locations,
recording=recording,
@@ -43,28 +41,26 @@ plt.savefig('drift_raster.png', bbox_inches='tight')
### Motion Estimate Visualization
+`correct_motion(..., output_motion_info=True)` returns `(recording, motion_info)`. The
+`motion_info` dict can be plotted directly with the built-in widget:
+
```python
-motion_info = npa.estimate_motion(recording)
-
-fig, axes = plt.subplots(1, 2, figsize=(12, 5))
-
-# Motion over time
-ax = axes[0]
-for i in range(motion_info['motion'].shape[1]):
- ax.plot(motion_info['temporal_bins'], motion_info['motion'][:, i], alpha=0.5)
-ax.set_xlabel('Time (s)')
-ax.set_ylabel('Motion (um)')
-ax.set_title('Estimated Motion')
-
-# Motion histogram
-ax = axes[1]
-ax.hist(motion_info['motion'].flatten(), bins=50, edgecolor='black')
-ax.set_xlabel('Motion (um)')
-ax.set_ylabel('Count')
-ax.set_title('Motion Distribution')
+rec_corrected, motion_info = si.correct_motion(
+ recording, preset='nonrigid_fast_and_accurate', output_motion_info=True, folder='motion/'
+)
-plt.tight_layout()
-plt.savefig('motion_analysis.png', dpi=300)
+# Built-in motion visualization (drift raster + motion field)
+sw.plot_motion_info(motion_info, recording=recording)
+plt.savefig('motion_analysis.png', dpi=300, bbox_inches='tight')
+
+# Or inspect the Motion object directly
+motion = motion_info['motion']
+displacement = motion.displacement[0] # (n_temporal_bins, n_spatial_bins)
+temporal_bins = motion.temporal_bins_s[0]
+plt.figure(figsize=(10, 4))
+plt.plot(temporal_bins, displacement, alpha=0.5)
+plt.xlabel('Time (s)'); plt.ylabel('Displacement (um)'); plt.title('Estimated Motion')
+plt.savefig('motion_traces.png', dpi=300, bbox_inches='tight')
```
## Waveform Plots
@@ -109,7 +105,9 @@ plt.savefig(f'unit_{unit_id}_probe.png')
### Metrics Overview
```python
-npa.plot_quality_metrics(analyzer, metrics, output='quality_overview.png')
+# Built-in quality-metrics widget (scatter matrix of all computed metrics)
+sw.plot_quality_metrics(analyzer)
+plt.savefig('quality_overview.png', dpi=300, bbox_inches='tight')
```
### Metrics Distribution
@@ -332,7 +330,9 @@ plt.savefig(f'unit_{unit_id}_isi_detailed.png', dpi=300)
### Unit Summary Panel
```python
-npa.plot_unit_summary(analyzer, unit_id, output=f'unit_{unit_id}_summary.png')
+# Built-in one-call summary (waveform, template, ACG, amplitudes, location)
+sw.plot_unit_summary(analyzer, unit_id=unit_id)
+plt.savefig(f'unit_{unit_id}_summary.png', dpi=300, bbox_inches='tight')
```
### Manual Multi-Panel Summary
diff --git a/skills/neuropixels-analysis/references/standard_workflow.md b/skills/neuropixels-analysis/references/standard_workflow.md
index 35bfba6c..a71ea0be 100644
--- a/skills/neuropixels-analysis/references/standard_workflow.md
+++ b/skills/neuropixels-analysis/references/standard_workflow.md
@@ -1,306 +1,225 @@
# Standard Neuropixels Analysis Workflow
-Complete step-by-step guide for analyzing Neuropixels recordings from raw data to curated units.
+Complete step-by-step guide for analyzing Neuropixels recordings from raw data to curated
+units, using the SpikeInterface API directly.
## Overview
-This reference documents the complete analysis pipeline:
-
```
Raw Recording → Preprocessing → Motion Correction → Spike Sorting →
Postprocessing → Quality Metrics → Curation → Export
```
+```python
+import spikeinterface.full as si
+import spikeinterface.curation as sc
+
+si.set_global_job_kwargs(n_jobs=-1, chunk_duration="1s", progress_bar=True)
+```
+
## 1. Data Loading
-### Supported Formats
+### Supported formats
```python
-import spikeinterface.full as si
-import neuropixels_analysis as npa
+# Inspect streams first
+stream_names, stream_ids = si.get_neo_streams("spikeglx", "/path/to/run_g0/")
# SpikeGLX (most common)
-recording = si.read_spikeglx('/path/to/run/', stream_id='imec0.ap')
+recording = si.read_spikeglx("/path/to/run_g0/", stream_name="imec0.ap", load_sync_channel=False)
# Open Ephys
-recording = si.read_openephys('/path/to/experiment/')
-
-# NWB format
-recording = si.read_nwb('/path/to/file.nwb')
+recording = si.read_openephys("/path/to/experiment/")
-# Or use our convenience wrapper
-recording = npa.load_recording('/path/to/data/', format='spikeglx')
+# NWB
+recording = si.read_nwb("/path/to/file.nwb")
```
-### Verify Recording Properties
+### Verify recording properties
```python
-# Basic properties
print(f"Channels: {recording.get_num_channels()}")
print(f"Duration: {recording.get_total_duration():.1f}s")
print(f"Sampling rate: {recording.get_sampling_frequency()}Hz")
-
-# Probe geometry
-print(f"Probe: {recording.get_probe().name}")
-
-# Channel locations
+print(f"Probe: {recording.get_probe()}")
locations = recording.get_channel_locations()
```
## 2. Preprocessing
-### Standard Preprocessing Chain
+### Standard chain (IBL-style)
```python
-# Option 1: Full pipeline (recommended)
-rec_preprocessed = npa.preprocess(recording)
-
-# Option 2: Step-by-step control
-rec = si.bandpass_filter(recording, freq_min=300, freq_max=6000)
-rec = si.phase_shift(rec) # Correct ADC phase
-bad_channels = si.detect_bad_channels(rec)
-rec = rec.remove_channels(bad_channels)
-rec = si.common_reference(rec, operator='median')
-rec_preprocessed = rec
+rec = si.highpass_filter(recording, freq_min=400.0)
+bad_channel_ids, channel_labels = si.detect_bad_channels(rec)
+rec = rec.remove_channels(bad_channel_ids)
+rec = si.phase_shift(rec) # ADC phase (NP 1.0)
+rec = si.common_reference(rec, operator="median", reference="global")
```
-### IBL-Style Destriping
-
-For recordings with strong artifacts:
+A bandpass alternative (some labs prefer an explicit passband):
```python
-from ibldsp.voltage import decompress_destripe_cbin
+rec = si.bandpass_filter(recording, freq_min=300.0, freq_max=6000.0)
+rec = si.phase_shift(rec)
+bad_channel_ids, _ = si.detect_bad_channels(rec)
+rec = rec.remove_channels(bad_channel_ids)
+rec = si.common_reference(rec, operator="median", reference="global")
+```
+
+### Spatial destriping (strong artifacts)
-# IBL destriping (very effective)
-rec = si.highpass_filter(recording, freq_min=400)
+```python
+rec = si.highpass_filter(recording, freq_min=400.0)
rec = si.phase_shift(rec)
-rec = si.highpass_spatial_filter(rec) # Destriping
-rec = si.common_reference(rec, reference='global', operator='median')
+rec = si.highpass_spatial_filter(rec) # destriping
+rec = si.common_reference(rec, operator="median", reference="global")
```
-### Save Preprocessed Data
+### Save preprocessed data
```python
-# Save for reuse (speeds up iteration)
-rec_preprocessed.save(folder='preprocessed/', n_jobs=4)
+rec = rec.save(folder="preprocessed/", format="binary")
```
## 3. Motion/Drift Correction
-### Check if Correction Needed
+### Check whether correction is needed
```python
-# Estimate motion
-motion_info = npa.estimate_motion(rec_preprocessed, preset='kilosort_like')
+from spikeinterface.sortingcomponents.peak_detection import detect_peaks
+from spikeinterface.sortingcomponents.peak_localization import localize_peaks
-# Visualize drift
-npa.plot_drift(rec_preprocessed, motion_info, output='drift_map.png')
+noise_levels = si.get_noise_levels(rec, return_in_uV=False)
+peaks = detect_peaks(rec, method="locally_exclusive", noise_levels=noise_levels,
+ detect_threshold=5, radius_um=50.0)
+peak_locations = localize_peaks(rec, peaks, method="center_of_mass")
-# Check magnitude
-if motion_info['motion'].max() > 10: # microns
- print("Significant drift detected - correction recommended")
+si.plot_drift_raster_map(peaks=peaks, peak_locations=peak_locations, recording=rec, clim=(-50, 50))
```
-### Apply Correction
+### Apply correction
```python
-# DREDge-based correction (default)
-rec_corrected = npa.correct_motion(
- rec_preprocessed,
- preset='nonrigid_accurate', # or 'kilosort_like' for speed
-)
-
-# Or full control
-from spikeinterface.preprocessing import correct_motion
-
-rec_corrected = correct_motion(
- rec_preprocessed,
- preset='nonrigid_accurate',
- folder='motion_output/',
- output_motion=True,
-)
+# One-call correction with a preset
+rec_corrected = si.correct_motion(rec, preset="nonrigid_fast_and_accurate", folder="motion/")
```
+See [MOTION_CORRECTION.md](MOTION_CORRECTION.md) for the full estimate/interpolate pipeline
+and DREDge usage.
+
## 4. Spike Sorting
### Recommended: Kilosort4
```python
-# Run Kilosort4 (requires GPU)
-sorting = npa.run_sorting(
- rec_corrected,
- sorter='kilosort4',
- output_folder='sorting_KS4/',
-)
+sorting = si.run_sorter("kilosort4", rec_corrected, folder="sorting_KS4/", verbose=True)
# With custom parameters
-sorting = npa.run_sorting(
- rec_corrected,
- sorter='kilosort4',
- output_folder='sorting_KS4/',
- sorter_params={
- 'batch_size': 30000,
- 'nblocks': 5, # For nonrigid drift
- 'Th_learned': 8, # Detection threshold
- },
+sorting = si.run_sorter(
+ "kilosort4", rec_corrected, folder="sorting_KS4/",
+ nblocks=5, # non-rigid drift blocks
+ Th_universal=9, # detection threshold
+ Th_learned=8,
+ batch_size=60000,
)
```
-### Alternative Sorters
+### Alternative sorters
```python
-# SpykingCircus2 (CPU-based)
-sorting = npa.run_sorting(rec_corrected, sorter='spykingcircus2')
-
-# Mountainsort5 (fast, good for short recordings)
-sorting = npa.run_sorting(rec_corrected, sorter='mountainsort5')
+sorting = si.run_sorter("spykingcircus2", rec_corrected, folder="sc2/") # CPU
+sorting = si.run_sorter("tridesclous2", rec_corrected, folder="tdc2/") # CPU
+sorting = si.run_sorter("mountainsort5", rec_corrected, folder="ms5/") # CPU
```
-### Compare Multiple Sorters
+### Compare multiple sorters
```python
-# Run multiple sorters
-sortings = {}
-for sorter in ['kilosort4', 'spykingcircus2']:
- sortings[sorter] = npa.run_sorting(rec_corrected, sorter=sorter)
-
-# Compare results
-comparison = npa.compare_sorters(list(sortings.values()))
-agreement_matrix = comparison.get_agreement_matrix()
+sortings = {s: si.run_sorter(s, rec_corrected, folder=f"{s}/")
+ for s in ["kilosort4", "spykingcircus2"]}
+
+comparison = si.compare_multiple_sorters(list(sortings.values()),
+ name_list=list(sortings.keys()))
+agreement = comparison.get_agreement_sorting(minimum_agreement_count=2)
```
## 5. Postprocessing
-### Create Analyzer
+### Create analyzer and compute extensions
```python
-# Create sorting analyzer (central object for all postprocessing)
-analyzer = npa.create_analyzer(
- sorting,
- rec_corrected,
- output_folder='analyzer/',
-)
-
-# Compute all standard extensions
-analyzer = npa.postprocess(
- sorting,
- rec_corrected,
- output_folder='analyzer/',
- compute_all=True, # Waveforms, templates, metrics, etc.
-)
-```
-
-### Compute Individual Extensions
-
-```python
-# Waveforms
-analyzer.compute('waveforms', ms_before=1.0, ms_after=2.0, max_spikes_per_unit=500)
-
-# Templates
-analyzer.compute('templates', operators=['average', 'std'])
-
-# Spike amplitudes
-analyzer.compute('spike_amplitudes')
-
-# Correlograms
-analyzer.compute('correlograms', window_ms=50.0, bin_ms=1.0)
-
-# Unit locations
-analyzer.compute('unit_locations', method='monopolar_triangulation')
-
-# Spike locations
-analyzer.compute('spike_locations', method='center_of_mass')
+analyzer = si.create_sorting_analyzer(sorting, rec_corrected, sparse=True,
+ format="binary_folder", folder="analyzer/")
+
+analyzer.compute("random_spikes", method="uniform", max_spikes_per_unit=500)
+analyzer.compute("waveforms", ms_before=1.0, ms_after=2.0)
+analyzer.compute("templates", operators=["average", "std"])
+analyzer.compute("noise_levels")
+analyzer.compute("spike_amplitudes")
+analyzer.compute("correlograms", window_ms=50.0, bin_ms=1.0)
+analyzer.compute("unit_locations", method="monopolar_triangulation")
+analyzer.compute("template_similarity")
```
## 6. Quality Metrics
-### Compute All Metrics
-
```python
-# Compute comprehensive metrics
-metrics = npa.compute_quality_metrics(
- analyzer,
- metric_names=[
- 'snr',
- 'isi_violations_ratio',
- 'presence_ratio',
- 'amplitude_cutoff',
- 'firing_rate',
- 'amplitude_cv',
- 'sliding_rp_violation',
- 'd_prime',
- 'nearest_neighbor',
- ],
-)
-
-# View metrics
+metric_names = ["snr", "isi_violation", "presence_ratio", "amplitude_cutoff",
+ "firing_rate", "amplitude_cv", "sliding_rp_violation"]
+analyzer.compute("quality_metrics", metric_names=metric_names)
+metrics = analyzer.get_extension("quality_metrics").get_data()
print(metrics.head())
```
-### Key Metrics Explained
+### Key metrics
-| Metric | Good Value | Description |
-|--------|------------|-------------|
+| Metric (column) | Good value | Description |
+|-----------------|------------|-------------|
| `snr` | > 5 | Signal-to-noise ratio |
-| `isi_violations_ratio` | < 0.01 | Refractory period violations |
+| `isi_violations_ratio` | < 0.5 (strict: < 0.01) | Refractory period violations |
| `presence_ratio` | > 0.9 | Fraction of recording with spikes |
| `amplitude_cutoff` | < 0.1 | Estimated missed spikes |
| `firing_rate` | > 0.1 Hz | Average firing rate |
## 7. Curation
-### Automated Curation
+### Threshold-based
```python
-# Allen Institute criteria
-labels = npa.curate(metrics, method='allen')
-
-# IBL criteria
-labels = npa.curate(metrics, method='ibl')
-
-# Custom thresholds
-labels = npa.curate(
- metrics,
- snr_threshold=5,
- isi_violations_threshold=0.01,
- presence_threshold=0.9,
-)
+query = "(amplitude_cutoff < 0.1) & (isi_violations_ratio < 0.5) & (presence_ratio > 0.9)"
+good_unit_ids = metrics.query(query).index.values
```
-### AI-Assisted Curation
-
-```python
-from anthropic import Anthropic
+For `allen` / `ibl` / `strict` presets in one call, use `scripts/compute_metrics.py`.
-# Setup API
-client = Anthropic()
+### Model-based (UnitRefine)
-# Visual analysis for uncertain units
-uncertain = metrics.query('snr > 3 and snr < 8').index.tolist()
-
-for unit_id in uncertain:
- result = npa.analyze_unit_visually(analyzer, unit_id, api_client=client)
- labels[unit_id] = result['classification']
+```python
+noise_labels = sc.model_based_label_units(
+ sorting_analyzer=analyzer,
+ repo_id="SpikeInterface/UnitRefine_noise_neural_classifier",
+ trust_model=True,
+)
+neural = analyzer.remove_units(noise_labels[noise_labels["prediction"] == "noise"].index)
+sua_mua = sc.model_based_label_units(
+ sorting_analyzer=neural,
+ repo_id="SpikeInterface/UnitRefine_sua_mua_classifier",
+ trust_model=True,
+)
```
-### Interactive Curation Session
-
-```python
-# Create session
-session = npa.CurationSession.create(analyzer, output_dir='curation/')
+### AI-assisted (uncertain units)
-# Review units
-while session.current_unit():
- unit = session.current_unit()
- report = npa.generate_unit_report(analyzer, unit.unit_id)
+Read API keys from the environment — never hardcode them (see [AI_CURATION.md](AI_CURATION.md)):
- # Your decision
- decision = input(f"Unit {unit.unit_id}: ")
- session.set_decision(unit.unit_id, decision)
- session.next_unit()
+```python
+import os
+from anthropic import Anthropic
-# Export
-labels = session.get_final_labels()
+client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
+uncertain = metrics.query("snr > 3 and snr < 8").index.tolist()
+# Render each uncertain unit's summary image and ask the model to classify it.
```
## 8. Export Results
@@ -308,78 +227,79 @@ labels = session.get_final_labels()
### Export to Phy
```python
-from spikeinterface.exporters import export_to_phy
-
-export_to_phy(
- analyzer,
- output_folder='phy_export/',
- copy_binary=True,
-)
+analyzer_clean = analyzer.select_units(good_unit_ids, folder="analyzer_clean/", format="binary_folder")
+si.export_to_phy(analyzer_clean, output_folder="phy_export/",
+ compute_pc_features=True, compute_amplitudes=True)
```
### Export to NWB
```python
from spikeinterface.exporters import export_to_nwb
-
-export_to_nwb(
- analyzer,
- nwbfile_path='results.nwb',
- metadata={
- 'session_description': 'Neuropixels recording',
- 'experimenter': 'Lab Name',
- },
-)
+export_to_nwb(analyzer_clean, "results.nwb")
```
-### Save Quality Summary
+### Save quality summary
```python
-# Save metrics CSV
-metrics.to_csv('quality_metrics.csv')
+metrics.to_csv("quality_metrics.csv")
-# Save labels
import json
-with open('curation_labels.json', 'w') as f:
+labels = {int(uid): ("good" if uid in good_unit_ids else "other") for uid in metrics.index}
+with open("curation_labels.json", "w") as f:
json.dump(labels, f, indent=2)
-# Generate summary report
-npa.plot_quality_metrics(analyzer, metrics, output='quality_summary.png')
+si.export_report(analyzer_clean, "report/", format="png")
```
## Full Pipeline Example
```python
-import neuropixels_analysis as npa
+import spikeinterface.full as si
+
+si.set_global_job_kwargs(n_jobs=-1, chunk_duration="1s", progress_bar=True)
# Load
-recording = npa.load_recording('/data/experiment/', format='spikeglx')
+recording = si.read_spikeglx("/data/experiment/", stream_name="imec0.ap", load_sync_channel=False)
# Preprocess
-rec = npa.preprocess(recording)
+rec = si.highpass_filter(recording, freq_min=400.0)
+bad_channel_ids, _ = si.detect_bad_channels(rec)
+rec = rec.remove_channels(bad_channel_ids)
+rec = si.phase_shift(rec)
+rec = si.common_reference(rec, operator="median", reference="global")
# Motion correction
-rec = npa.correct_motion(rec)
+rec = si.correct_motion(rec, preset="nonrigid_fast_and_accurate", folder="motion/")
# Sort
-sorting = npa.run_sorting(rec, sorter='kilosort4')
+sorting = si.run_sorter("kilosort4", rec, folder="ks4/")
-# Postprocess
-analyzer, metrics = npa.postprocess(sorting, rec)
+# Postprocess + metrics
+analyzer = si.create_sorting_analyzer(sorting, rec, sparse=True, format="binary_folder", folder="analyzer/")
+analyzer.compute(["random_spikes", "waveforms", "templates", "noise_levels",
+ "spike_amplitudes", "correlograms", "unit_locations"])
+analyzer.compute("quality_metrics",
+ metric_names=["snr", "isi_violation", "presence_ratio", "amplitude_cutoff", "firing_rate"])
+metrics = analyzer.get_extension("quality_metrics").get_data()
# Curate
-labels = npa.curate(metrics, method='allen')
+query = "(amplitude_cutoff < 0.1) & (isi_violations_ratio < 0.5) & (presence_ratio > 0.9)"
+good_unit_ids = metrics.query(query).index.values
+print(f"Good units: {len(good_unit_ids)}/{len(metrics)}")
+```
+
+Or run it as a script:
-# Export good units
-good_units = [uid for uid, label in labels.items() if label == 'good']
-print(f"Good units: {len(good_units)}/{len(labels)}")
+```bash
+python scripts/neuropixels_pipeline.py /data/experiment/ output/ --sorter kilosort4 --curation allen
```
## Tips for Success
-1. **Always visualize drift** before deciding on motion correction
-2. **Save preprocessed data** to avoid recomputing
-3. **Compare multiple sorters** for critical experiments
-4. **Review uncertain units manually** - don't trust automated curation blindly
-5. **Document your parameters** for reproducibility
-6. **Use GPU** for Kilosort4 (10-50x faster than CPU alternatives)
+1. **Always visualize drift** before deciding on motion correction.
+2. **Save preprocessed data** to avoid recomputing (and Kilosort needs a binary file).
+3. **Compare multiple sorters** for critical experiments.
+4. **Review uncertain units manually** — don't trust automated curation blindly.
+5. **Document parameters and model repo IDs** for reproducibility.
+6. **Use a GPU** for Kilosort4.
diff --git a/skills/neuropixels-analysis/scripts/explore_recording.py b/skills/neuropixels-analysis/scripts/explore_recording.py
index 873fdbd6..8d1a4b8b 100644
--- a/skills/neuropixels-analysis/scripts/explore_recording.py
+++ b/skills/neuropixels-analysis/scripts/explore_recording.py
@@ -12,11 +12,11 @@ import matplotlib.pyplot as plt
import numpy as np
-def explore_recording(data_path: str, stream_id: str = 'imec0.ap'):
+def explore_recording(data_path: str, stream_name: str = 'imec0.ap'):
"""Explore a Neuropixels recording."""
print(f"Loading: {data_path}")
- recording = si.read_spikeglx(data_path, stream_id=stream_id)
+ recording = si.read_spikeglx(data_path, stream_name=stream_name)
# Basic info
print("\n" + "="*50)
@@ -147,7 +147,7 @@ def plot_power_spectrum(recording, output_path=None):
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Explore Neuropixels recording')
parser.add_argument('data_path', help='Path to SpikeGLX recording')
- parser.add_argument('--stream', default='imec0.ap', help='Stream ID')
+ parser.add_argument('--stream', default='imec0.ap', help='Stream name (e.g. imec0.ap)')
parser.add_argument('--plot', action='store_true', help='Generate plots')
parser.add_argument('--output', default=None, help='Output directory for plots')
diff --git a/skills/neuropixels-analysis/scripts/neuropixels_pipeline.py b/skills/neuropixels-analysis/scripts/neuropixels_pipeline.py
index 2b2a580b..20fa2b5a 100644
--- a/skills/neuropixels-analysis/scripts/neuropixels_pipeline.py
+++ b/skills/neuropixels-analysis/scripts/neuropixels_pipeline.py
@@ -19,7 +19,7 @@ import spikeinterface.full as si
import numpy as np
-def load_recording(data_path: str, stream_id: str = 'imec0.ap') -> si.BaseRecording:
+def load_recording(data_path: str, stream_name: str = 'imec0.ap') -> si.BaseRecording:
"""Load a SpikeGLX or Open Ephys recording."""
data_path = Path(data_path)
@@ -29,7 +29,7 @@ def load_recording(data_path: str, stream_id: str = 'imec0.ap') -> si.BaseRecord
# SpikeGLX format
streams, _ = si.get_neo_streams('spikeglx', data_path)
print(f"Available streams: {streams}")
- recording = si.read_spikeglx(data_path, stream_id=stream_id)
+ recording = si.read_spikeglx(data_path, stream_name=stream_name)
elif any(data_path.rglob('*.oebin')):
# Open Ephys format
recording = si.read_openephys(data_path)
@@ -157,11 +157,13 @@ def correct_motion(
"""Apply motion correction if needed."""
print(f"Applying motion correction (preset: {preset})...")
+ # correct_motion returns just the corrected recording by default. Pass
+ # output_motion_info=True only if you also want the motion info dict (a tuple is
+ # returned in that case).
rec_corrected = si.correct_motion(
recording,
preset=preset,
folder=f'{output_folder}/motion',
- output_motion_info=True,
n_jobs=8,
chunk_duration='1s',
progress_bar=True
diff --git a/skills/neuropixels-analysis/scripts/preprocess_recording.py b/skills/neuropixels-analysis/scripts/preprocess_recording.py
index 5ef8e663..be5be9df 100644
--- a/skills/neuropixels-analysis/scripts/preprocess_recording.py
+++ b/skills/neuropixels-analysis/scripts/preprocess_recording.py
@@ -16,7 +16,7 @@ def preprocess_recording(
input_path: str,
output_dir: str,
format: str = 'auto',
- stream_id: str = None,
+ stream_name: str = None,
freq_min: float = 300,
freq_max: float = 6000,
phase_shift: bool = True,
@@ -30,7 +30,7 @@ def preprocess_recording(
# Load recording
if format == 'spikeglx' or (format == 'auto' and 'imec' in str(input_path).lower()):
- recording = si.read_spikeglx(input_path, stream_id=stream_id or 'imec0.ap')
+ recording = si.read_spikeglx(input_path, stream_name=stream_name or 'imec0.ap')
elif format == 'openephys':
recording = si.read_openephys(input_path)
elif format == 'nwb':
@@ -38,8 +38,8 @@ def preprocess_recording(
else:
# Try auto-detection
try:
- recording = si.read_spikeglx(input_path, stream_id=stream_id or 'imec0.ap')
- except:
+ recording = si.read_spikeglx(input_path, stream_name=stream_name or 'imec0.ap')
+ except Exception:
recording = si.load_extractor(input_path)
print(f"Recording: {recording.get_num_channels()} channels, {recording.get_total_duration():.1f}s")
@@ -94,7 +94,7 @@ def main():
parser.add_argument('input', help='Path to input recording')
parser.add_argument('--output', '-o', default='preprocessed/', help='Output directory')
parser.add_argument('--format', '-f', default='auto', choices=['auto', 'spikeglx', 'openephys', 'nwb'])
- parser.add_argument('--stream-id', default=None, help='Stream ID for multi-probe recordings')
+ parser.add_argument('--stream-name', default=None, help='Stream name for multi-probe recordings (e.g. imec0.ap)')
parser.add_argument('--freq-min', type=float, default=300, help='Highpass cutoff (Hz)')
parser.add_argument('--freq-max', type=float, default=6000, help='Lowpass cutoff (Hz)')
parser.add_argument('--no-phase-shift', action='store_true', help='Skip phase shift correction')
@@ -108,7 +108,7 @@ def main():
args.input,
args.output,
format=args.format,
- stream_id=args.stream_id,
+ stream_name=args.stream_name,
freq_min=args.freq_min,
freq_max=args.freq_max,
phase_shift=not args.no_phase_shift,
diff --git a/skills/pennylane/SKILL.md b/skills/pennylane/SKILL.md
index 3d23eb39..194fc160 100644
--- a/skills/pennylane/SKILL.md
+++ b/skills/pennylane/SKILL.md
@@ -1,9 +1,13 @@
---
name: pennylane
-description: Hardware-agnostic quantum ML framework with automatic differentiation. Use when training quantum circuits via gradients, building hybrid quantum-classical models, or needing device portability across IBM/Google/Rigetti/IonQ. Best for variational algorithms (VQE, QAOA), quantum neural networks, and integration with PyTorch/JAX/TensorFlow. For hardware-specific optimizations use qiskit (IBM) or cirq (Google); for open quantum systems use qutip.
+description: Hardware-agnostic quantum ML framework with automatic differentiation. Use when training quantum circuits via gradients, building hybrid quantum-classical models, or needing device portability across IBM/Google/Rigetti/IonQ. Best for variational algorithms (VQE, QAOA), quantum neural networks, and integration with PyTorch or JAX. For hardware-specific optimizations use qiskit (IBM) or cirq (Google); for open quantum systems use qutip.
license: Apache-2.0 license
+allowed-tools:
+ - Read
+ - Bash
+ - Python
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -15,29 +19,35 @@ PennyLane is a quantum computing library that enables training quantum computers
## Installation
-Install using uv:
+PennyLane 0.45.0 requires Python 3.11 or newer. Install using uv with pinned versions for reproducible environments:
```bash
-uv pip install pennylane
+uv pip install "pennylane==0.45.0"
```
-For quantum hardware access, install device plugins:
+For quantum hardware access, install the plugin matching the target provider. Start from a clean environment when adding or upgrading Qiskit because its dependency graph is strict.
```bash
# IBM Quantum
-uv pip install pennylane-qiskit
+uv pip install "pennylane-qiskit==0.45.0"
# Amazon Braket
-uv pip install amazon-braket-pennylane-plugin
+uv pip install "amazon-braket-pennylane-plugin==1.34.1"
# Google Cirq
-uv pip install pennylane-cirq
+uv pip install "pennylane-cirq==0.44.0"
# Rigetti Forest
-uv pip install pennylane-rigetti
+uv pip install "pennylane-rigetti==0.40.0"
# IonQ
-uv pip install pennylane-ionq
+uv pip install "pennylane-ionq==0.45.0"
+
+# High-performance local simulators
+uv pip install "pennylane-lightning==0.45.0"
+
+# Catalyst JIT compilation
+uv pip install "pennylane-catalyst==0.15.0"
```
## Quick Start
@@ -81,7 +91,7 @@ Build circuits with gates, measurements, and state preparation. See `references/
### 2. Quantum Machine Learning
Create hybrid quantum-classical models. See `references/quantum_ml.md` for:
-- Integration with PyTorch, JAX, TensorFlow
+- Integration with PyTorch and JAX
- Quantum neural networks and variational classifiers
- Data encoding strategies (angle, amplitude, basis, IQP)
- Training hybrid models with backpropagation
@@ -156,19 +166,23 @@ from pennylane import qchem
# 1. Build Hamiltonian
symbols = ['H', 'H']
-coords = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.74])
-H, n_qubits = qchem.molecular_hamiltonian(symbols, coords)
+geometry = np.array([[0.0, 0.0, -0.66140414], [0.0, 0.0, 0.66140414]])
+molecule = qchem.Molecule(symbols, geometry)
+H, n_qubits = qchem.molecular_hamiltonian(molecule)
+hf_state = qchem.hf_state(electrons=2, orbitals=n_qubits)
+singles, doubles = qchem.excitations(electrons=2, orbitals=n_qubits)
+s_wires, d_wires = qchem.excitations_to_wires(singles, doubles)
# 2. Define ansatz
@qml.qnode(dev)
def vqe_circuit(params):
- qml.BasisState(qchem.hf_state(2, n_qubits), wires=range(n_qubits))
- qml.UCCSD(params, wires=range(n_qubits))
+ qml.BasisState(hf_state, wires=range(n_qubits))
+ qml.UCCSD(params, wires=range(n_qubits), s_wires=s_wires, d_wires=d_wires)
return qml.expval(H)
# 3. Optimize
opt = qml.AdamOptimizer(stepsize=0.1)
-params = np.zeros(10, requires_grad=True)
+params = np.zeros(len(singles) + len(doubles), requires_grad=True)
for i in range(100):
params, energy = opt.step_and_cost(vqe_circuit, params)
@@ -186,7 +200,11 @@ dev_sim = qml.device('default.qubit', wires=4)
result_sim = circuit_def(dev_sim)(params)
# Run on quantum hardware
-dev_hw = qml.device('qiskit.ibmq', wires=4, backend='ibmq_manila')
+from qiskit_ibm_runtime import QiskitRuntimeService
+
+service = QiskitRuntimeService()
+backend = service.least_busy(operational=True, simulator=False, min_num_qubits=4)
+dev_hw = qml.device('qiskit.remote', wires=backend.num_qubits, backend=backend)
result_hw = circuit_def(dev_hw)(params)
```
diff --git a/skills/pennylane/references/advanced_features.md b/skills/pennylane/references/advanced_features.md
index 731ae978..7d327e62 100644
--- a/skills/pennylane/references/advanced_features.md
+++ b/skills/pennylane/references/advanced_features.md
@@ -216,7 +216,7 @@ print("Operations:", tape.operations)
print("Observables:", tape.observables)
# Transform tape
-expanded_tape = transforms.expand_tape(tape)
+expanded_tape = transforms.decompose(tape, gate_set={qml.RX, qml.RY, qml.RZ, qml.CNOT})
optimized_tape = transforms.cancel_inverses(tape)
```
diff --git a/skills/pennylane/references/devices_backends.md b/skills/pennylane/references/devices_backends.md
index 2ff19634..86152f15 100644
--- a/skills/pennylane/references/devices_backends.md
+++ b/skills/pennylane/references/devices_backends.md
@@ -20,8 +20,8 @@ import pennylane as qml
# Basic initialization
dev = qml.device('default.qubit', wires=4)
-# With shots (sampling mode)
-dev = qml.device('default.qubit', wires=4, shots=1000)
+# For sampling mode, set shots on the QNode with qml.set_shots
+dev = qml.device('default.qubit', wires=4)
# Specify wire labels
dev = qml.device('default.qubit', wires=['a', 'b', 'c', 'd'])
@@ -50,19 +50,18 @@ def noisy_circuit():
return qml.expval(qml.PauliZ(0))
```
-### default.qubit.torch, default.qubit.tf, default.qubit.jax
+### Machine Learning Interfaces
-Framework-specific simulators with better integration:
+Use `default.qubit` with the QNode interface for PyTorch or JAX. The old interface-specific device names are not needed in current PennyLane examples, and TensorFlow support is no longer maintained as of PennyLane v0.44.
```python
# PyTorch
-dev = qml.device('default.qubit.torch', wires=4)
-
-# TensorFlow
-dev = qml.device('default.qubit.tf', wires=4)
+dev = qml.device('default.qubit', wires=4)
-# JAX
-dev = qml.device('default.qubit.jax', wires=4)
[email protected](dev, interface="torch")
+def torch_circuit(weights):
+ qml.RX(weights[0], wires=0)
+ return qml.expval(qml.Z(0))
```
### lightning.qubit
@@ -109,7 +108,7 @@ def clifford_circuit():
```bash
# Install plugin
-uv pip install pennylane-qiskit
+uv pip install "pennylane-qiskit==0.45.0"
```
```python
@@ -119,19 +118,14 @@ import pennylane as qml
dev = qml.device('qiskit.aer', wires=2)
# Use IBM quantum hardware
-dev = qml.device(
- 'qiskit.ibmq',
- wires=2,
- backend='ibmq_manila', # Specify backend
- shots=1024
-)
+from qiskit_ibm_runtime import QiskitRuntimeService
-# With API token
+service = QiskitRuntimeService()
+backend = service.least_busy(operational=True, simulator=False, min_num_qubits=2)
dev = qml.device(
- 'qiskit.ibmq',
- wires=2,
- backend='ibmq_manila',
- ibmqx_token='YOUR_API_TOKEN'
+ 'qiskit.remote',
+ wires=backend.num_qubits,
+ backend=backend,
)
@qml.qnode(dev)
@@ -139,13 +133,15 @@ def circuit():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0))
+
+sampled_circuit = qml.set_shots(circuit, shots=1024)
```
### Amazon Braket
```bash
# Install plugin
-uv pip install amazon-braket-pennylane-plugin
+uv pip install "amazon-braket-pennylane-plugin==1.34.1"
```
```python
@@ -168,7 +164,6 @@ dev = qml.device(
'braket.aws.qubit',
device_arn='arn:aws:braket:us-east-1::device/qpu/ionq/Harmony',
wires=11,
- shots=1000,
s3_destination_folder=('amazon-braket-outputs', 'outputs')
)
```
@@ -177,7 +172,7 @@ dev = qml.device(
```bash
# Install plugin
-uv pip install pennylane-cirq
+uv pip install "pennylane-cirq==0.44.0"
```
```python
@@ -192,7 +187,6 @@ dev = qml.device(
'cirq.pasqal',
wires=2,
device='rainbow',
- shots=1000
)
```
@@ -200,50 +194,22 @@ dev = qml.device(
```bash
# Install plugin
-uv pip install pennylane-rigetti
+uv pip install "pennylane-rigetti==0.40.0"
```
```python
# Use QVM (Quantum Virtual Machine)
-dev = qml.device('rigetti.qvm', device='4q-qvm', shots=1000)
+dev = qml.device('rigetti.qvm', device='4q-qvm')
# Use Rigetti QPU
-dev = qml.device('rigetti.qpu', device='Aspen-M-3', shots=1000)
-```
-
-### Microsoft Azure Quantum
-
-```bash
-# Install plugin
-uv pip install pennylane-azure
-```
-
-```python
-# Use Azure simulators
-dev = qml.device(
- 'azure.simulator',
- wires=4,
- workspace='your-workspace',
- resource_group='your-resource-group',
- subscription_id='your-subscription-id'
-)
-
-# Use IonQ on Azure
-dev = qml.device(
- 'azure.ionq',
- wires=11,
- workspace='your-workspace',
- resource_group='your-resource-group',
- subscription_id='your-subscription-id',
- shots=500
-)
+dev = qml.device('rigetti.qpu', device='Aspen-M-3')
```
### IonQ
```bash
# Install plugin
-uv pip install pennylane-ionq
+uv pip install "pennylane-ionq==0.45.0"
```
```python
@@ -251,7 +217,6 @@ uv pip install pennylane-ionq
dev = qml.device(
'ionq.simulator', # or 'ionq.qpu'
wires=11,
- shots=1024,
api_key='your_api_key'
)
```
@@ -263,7 +228,6 @@ dev = qml.device(
dev = qml.device(
'strawberryfields.remote',
backend='borealis',
- shots=10000
)
```
@@ -278,9 +242,9 @@ def select_device(n_qubits, use_hardware=False, noise_model=None):
if use_hardware:
# Use real quantum hardware
if n_qubits <= 11:
- return qml.device('ionq.qpu', wires=n_qubits, shots=1000)
+ return qml.device('ionq.qpu', wires=n_qubits)
elif n_qubits <= 127:
- return qml.device('qiskit.ibmq', wires=n_qubits, shots=1024)
+ raise ValueError("Pass a qiskit.remote backend object for IBM hardware")
else:
raise ValueError(f"No hardware available for {n_qubits} qubits")
@@ -332,8 +296,9 @@ def exact_circuit():
result = exact_circuit() # Returns exact expectation
# Sampling mode (with shots)
-dev_sampled = qml.device('default.qubit', wires=2, shots=1000)
+dev_sampled = qml.device('default.qubit', wires=2)
[email protected]_shots(1000)
@qml.qnode(dev_sampled)
def sampled_circuit():
qml.Hadamard(wires=0)
@@ -354,9 +319,9 @@ def circuit():
return qml.expval(qml.PauliZ(0))
# Different shot numbers
-result_100 = circuit(shots=100)
-result_1000 = circuit(shots=1000)
-result_exact = circuit(shots=None) # Exact
+result_100 = qml.set_shots(circuit, shots=100)()
+result_1000 = qml.set_shots(circuit, shots=1000)()
+result_exact = qml.set_shots(circuit, shots=None)() # Exact
```
### Analytic Mode vs Finite Shots
@@ -364,7 +329,7 @@ result_exact = circuit(shots=None) # Exact
```python
# Compare analytic vs sampled
dev_analytic = qml.device('default.qubit', wires=2)
-dev_sampled = qml.device('default.qubit', wires=2, shots=1000)
+dev_sampled = qml.device('default.qubit', wires=2)
@qml.qnode(dev_analytic)
def circuit_analytic(x):
@@ -380,7 +345,7 @@ import numpy as np
x = np.pi / 4
print(f"Analytic: {circuit_analytic(x)}")
-print(f"Sampled: {circuit_sampled(x)}")
+print(f"Sampled: {qml.set_shots(circuit_sampled, shots=1000)(x)}")
print(f"Exact value: {np.cos(x)}")
```
@@ -388,8 +353,9 @@ print(f"Exact value: {np.cos(x)}")
```python
# Set random seed
-dev = qml.device('default.qubit', wires=2, shots=1000, seed=42)
+dev = qml.device('default.qubit', wires=2, seed=42)
[email protected]_shots(1000)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires=0)
@@ -506,7 +472,7 @@ dev2 = get_device(4) # Returns same device
```python
# Install Catalyst
-# uv pip install pennylane-catalyst
+# uv pip install "pennylane-catalyst==0.15.0"
import pennylane as qml
from catalyst import qjit
@@ -554,7 +520,7 @@ with Pool(processes=4) as pool:
# Use GPU-accelerated devices if available
try:
dev = qml.device('lightning.gpu', wires=20)
-except:
+except Exception:
dev = qml.device('lightning.qubit', wires=20)
@qml.qnode(dev)
diff --git a/skills/pennylane/references/getting_started.md b/skills/pennylane/references/getting_started.md
index f4877156..52cf4e67 100644
--- a/skills/pennylane/references/getting_started.md
+++ b/skills/pennylane/references/getting_started.md
@@ -6,26 +6,26 @@ PennyLane is a cross-platform Python library for quantum computing, quantum mach
## Installation
-Install PennyLane using uv:
+Install PennyLane using uv. PennyLane 0.45.0 requires Python 3.11 or newer:
```bash
-uv pip install pennylane
+uv pip install "pennylane==0.45.0"
```
For specific device plugins (IBM, Amazon Braket, Google, Rigetti, etc.):
```bash
# IBM Qiskit
-uv pip install pennylane-qiskit
+uv pip install "pennylane-qiskit==0.45.0"
# Amazon Braket
-uv pip install amazon-braket-pennylane-plugin
+uv pip install "amazon-braket-pennylane-plugin==1.34.1"
# Google Cirq
-uv pip install pennylane-cirq
+uv pip install "pennylane-cirq==0.44.0"
# Rigetti
-uv pip install pennylane-rigetti
+uv pip install "pennylane-rigetti==0.40.0"
```
## Core Concepts
@@ -145,8 +145,13 @@ def circuit_simulator(x):
qml.RX(x, wires=0)
return qml.expval(qml.PauliZ(0))
-# Switch to hardware (if available)
[email protected](qml.device('qiskit.ibmq', wires=2))
+# Switch to IBM hardware after configuring qiskit-ibm-runtime credentials
+from qiskit_ibm_runtime import QiskitRuntimeService
+
+service = QiskitRuntimeService()
+backend = service.least_busy(operational=True, simulator=False, min_num_qubits=2)
+
[email protected](qml.device('qiskit.remote', wires=backend.num_qubits, backend=backend))
def circuit_hardware(x):
qml.RX(x, wires=0)
return qml.expval(qml.PauliZ(0))
diff --git a/skills/pennylane/references/optimization.md b/skills/pennylane/references/optimization.md
index 939f94a5..eeb9088d 100644
--- a/skills/pennylane/references/optimization.md
+++ b/skills/pennylane/references/optimization.md
@@ -230,8 +230,9 @@ def vqe(hamiltonian, ansatz, n_qubits):
from pennylane import qchem
symbols = ['H', 'H']
-coords = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.74])
-H, n_qubits = qchem.molecular_hamiltonian(symbols, coords)
+geometry = np.array([[0.0, 0.0, -0.66140414], [0.0, 0.0, 0.66140414]])
+molecule = qchem.Molecule(symbols, geometry)
+H, n_qubits = qchem.molecular_hamiltonian(molecule)
def simple_ansatz(params, wires):
qml.BasisState(qchem.hf_state(2, n_qubits), wires=wires)
@@ -297,16 +298,14 @@ for i in range(100):
```python
from pennylane import qaoa
+import networkx as nx
# Define problem: MaxCut on a graph
edges = [(0, 1), (1, 2), (2, 0)]
-graph = [(edge[0], edge[1], 1.0) for edge in edges]
-
-# Cost Hamiltonian
-cost_h = qaoa.maxcut(graph)
+graph = nx.Graph(edges)
-# Mixer Hamiltonian
-mixer_h = qaoa.x_mixer(range(3))
+# Cost and mixer Hamiltonians
+cost_h, mixer_h = qaoa.maxcut(graph)
# QAOA circuit
def qaoa_layer(gamma, alpha):
diff --git a/skills/pennylane/references/quantum_chemistry.md b/skills/pennylane/references/quantum_chemistry.md
index 062e0d49..bacd9192 100644
--- a/skills/pennylane/references/quantum_chemistry.md
+++ b/skills/pennylane/references/quantum_chemistry.md
@@ -19,16 +19,19 @@ import numpy as np
# Define molecule
symbols = ['H', 'H']
-coordinates = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.74]) # Angstroms
+geometry = np.array([[0.0, 0.0, -0.66140414], [0.0, 0.0, 0.66140414]])
+molecule = qchem.Molecule(
+ symbols,
+ geometry,
+ charge=0,
+ mult=1,
+ basis_name='sto-3g',
+)
# Generate Hamiltonian
hamiltonian, n_qubits = qchem.molecular_hamiltonian(
- symbols,
- coordinates,
- charge=0,
- mult=1, # Spin multiplicity
- basis='sto-3g',
- method='dhf' # Dirac-Hartree-Fock
+ molecule,
+ mapping='jordan_wigner',
)
print(f"Hamiltonian: {hamiltonian}")
@@ -47,7 +50,7 @@ a_0 = fermi.FermiC(0) # Creation operator
a_1 = fermi.FermiA(1) # Annihilation operator
# Convert to qubits
-qubit_op = qml.qchem.jordan_wigner(a_0 * a_1)
+qubit_op = qml.jordan_wigner(a_0 * a_1)
```
### Bravyi-Kitaev Transformation
@@ -58,8 +61,7 @@ from pennylane.qchem import bravyi_kitaev
# Build Hamiltonian with Bravyi-Kitaev
hamiltonian, n_qubits = qchem.molecular_hamiltonian(
- symbols,
- coordinates,
+ molecule,
mapping='bravyi_kitaev'
)
```
@@ -125,10 +127,9 @@ print(f"Final ground state energy: {energy:.8f} Ha")
### UCCSD Ansatz
```python
-from pennylane.qchem import UCCSD
-
# Singles and doubles excitations
singles, doubles = qchem.excitations(electrons=2, orbitals=n_qubits)
+s_wires, d_wires = qchem.excitations_to_wires(singles, doubles)
@qml.qnode(dev)
def uccsd_circuit(params):
@@ -136,7 +137,7 @@ def uccsd_circuit(params):
qml.BasisState(hf_state, wires=range(n_qubits))
# UCCSD ansatz
- UCCSD(params, wires=range(n_qubits), s_wires=singles, d_wires=doubles)
+ qml.UCCSD(params, wires=range(n_qubits), s_wires=s_wires, d_wires=d_wires)
return qml.expval(hamiltonian)
@@ -210,19 +211,19 @@ def adaptive_vqe(hamiltonian, n_qubits, max_gates=10):
```python
# Simple diatomic
h2_symbols = ['H', 'H']
-h2_coords = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.74])
+h2_coords = np.array([[0.0, 0.0, -0.66140414], [0.0, 0.0, 0.66140414]])
# Water molecule
h2o_symbols = ['O', 'H', 'H']
h2o_coords = np.array([
- 0.0, 0.0, 0.0, # O
- 0.757, 0.586, 0.0, # H
- -0.757, 0.586, 0.0 # H
+ [0.0, 0.0, 0.0], # O
+ [0.757, 0.586, 0.0], # H
+ [-0.757, 0.586, 0.0], # H
])
# From XYZ format
-molecule = qchem.read_structure('molecule.xyz')
-symbols, coords = molecule
+symbols, geometry = qchem.read_structure('molecule.xyz')
+molecule = qchem.Molecule(symbols, geometry)
```
### Geometry Optimization
@@ -232,8 +233,9 @@ def optimize_geometry(symbols, initial_coords, basis='sto-3g'):
"""Optimize molecular geometry."""
def energy_surface(coords):
+ molecule = qchem.Molecule(symbols, coords, basis_name=basis)
H, n_qubits = qchem.molecular_hamiltonian(
- symbols, coords, basis=basis
+ molecule
)
# Run VQE to get energy
@@ -269,11 +271,11 @@ def dissociation_curve(symbols, axis=2, distances=None):
energies = []
for d in distances:
- coords = np.zeros(6)
- coords[axis] = d # Set bond length
+ coords = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, d]])
+ molecule = qchem.Molecule(symbols, coords, basis_name='sto-3g')
H, n_qubits = qchem.molecular_hamiltonian(
- symbols, coords, basis='sto-3g'
+ molecule
)
energy = run_vqe(H, n_qubits)
@@ -300,18 +302,21 @@ plt.show()
```python
# Minimal basis (fastest, least accurate)
+molecule = qchem.Molecule(symbols, coords, basis_name='sto-3g')
H_sto3g, n_qubits = qchem.molecular_hamiltonian(
- symbols, coords, basis='sto-3g'
+ molecule
)
# Double-zeta basis
+molecule = qchem.Molecule(symbols, coords, basis_name='6-31g')
H_631g, n_qubits = qchem.molecular_hamiltonian(
- symbols, coords, basis='6-31g'
+ molecule
)
# Large basis (slower, more accurate)
+molecule = qchem.Molecule(symbols, coords, basis_name='cc-pvdz')
H_ccpvdz, n_qubits = qchem.molecular_hamiltonian(
- symbols, coords, basis='cc-pvdz'
+ molecule
)
```
@@ -322,11 +327,11 @@ H_ccpvdz, n_qubits = qchem.molecular_hamiltonian(
active_electrons = 2
active_orbitals = 2
+molecule = qchem.Molecule(symbols, coords, basis_name='sto-3g')
H_active, n_qubits = qchem.molecular_hamiltonian(
- symbols,
- coords,
+ molecule,
active_electrons=active_electrons,
- active_orbitals=active_orbitals
+ active_orbitals=active_orbitals,
)
print(f"Full system: {len(symbols)} electrons")
@@ -339,17 +344,17 @@ print(f"Qubits needed: {n_qubits}")
```python
# Jordan-Wigner (default)
H_jw, n_q_jw = qchem.molecular_hamiltonian(
- symbols, coords, mapping='jordan_wigner'
+ molecule, mapping='jordan_wigner'
)
# Bravyi-Kitaev
H_bk, n_q_bk = qchem.molecular_hamiltonian(
- symbols, coords, mapping='bravyi_kitaev'
+ molecule, mapping='bravyi_kitaev'
)
# Parity
H_parity, n_q_parity = qchem.molecular_hamiltonian(
- symbols, coords, mapping='parity'
+ molecule, mapping='parity'
)
print(f"Jordan-Wigner terms: {len(H_jw.ops)}")
@@ -448,8 +453,9 @@ def full_chemistry_workflow(symbols, coords, basis='sto-3g'):
"""Complete quantum chemistry calculation."""
print("1. Building molecular Hamiltonian...")
+ molecule = qchem.Molecule(symbols, coords, basis_name=basis)
H, n_qubits = qchem.molecular_hamiltonian(
- symbols, coords, basis=basis
+ molecule
)
print(f" Molecule: {' '.join(symbols)}")
@@ -486,11 +492,12 @@ def compute_molecular_properties(symbols, coords, vqe_params):
"""Calculate molecular properties from VQE solution."""
# Energy
- H, n_qubits = qchem.molecular_hamiltonian(symbols, coords)
+ molecule = qchem.Molecule(symbols, coords)
+ H, n_qubits = qchem.molecular_hamiltonian(molecule)
energy = vqe_circuit(vqe_params)
# Dipole moment
- dipole_obs = qchem.dipole_moment(symbols, coords)
+ dipole_obs = qchem.dipole_moment(molecule)
@qml.qnode(dev)
def dipole_circuit(axis):
@@ -527,14 +534,16 @@ def reaction_energy(reactants, products):
E_reactants = 0
for molecule in reactants:
symbols, coords = molecule
- H, n_qubits = qchem.molecular_hamiltonian(symbols, coords)
+ mol = qchem.Molecule(symbols, coords)
+ H, n_qubits = qchem.molecular_hamiltonian(mol)
E_reactants += run_vqe(H, n_qubits)
# Calculate energies of products
E_products = 0
for molecule in products:
symbols, coords = molecule
- H, n_qubits = qchem.molecular_hamiltonian(symbols, coords)
+ mol = qchem.Molecule(symbols, coords)
+ H, n_qubits = qchem.molecular_hamiltonian(mol)
E_products += run_vqe(H, n_qubits)
# Reaction energy
diff --git a/skills/pennylane/references/quantum_circuits.md b/skills/pennylane/references/quantum_circuits.md
index ef84720b..ff65448f 100644
--- a/skills/pennylane/references/quantum_circuits.md
+++ b/skills/pennylane/references/quantum_circuits.md
@@ -157,15 +157,17 @@ def measure_probabilities():
### Samples and Counts
```python
[email protected]_shots(1000)
@qml.qnode(dev)
-def measure_samples(shots=1000):
+def measure_samples():
qml.Hadamard(wires=0)
# Raw samples
return qml.sample(qml.PauliZ(0))
[email protected]_shots(1000)
@qml.qnode(dev)
-def measure_counts(shots=1000):
+def measure_counts():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
@@ -288,8 +290,12 @@ def dynamic_for_loop(n_iterations):
### While Loops (with Catalyst)
```python
[email protected] # Just-in-time compilation
+from catalyst import qjit
+
+compiled_dev = qml.device("lightning.qubit", wires=1)
+
+@qjit # Just-in-time compilation with Catalyst
[email protected](compiled_dev)
def dynamic_while_loop():
qml.Hadamard(wires=0)
@@ -347,8 +353,8 @@ print(f"Depth: {specs['depth']}")
print(f"Parameters: {specs['num_trainable_params']}")
# Resource estimation
-resources = qml.resource.resource_estimation(circuit)(params)
-print(f"Total gates: {resources['num_gates']}")
+resources = qml.specs(circuit)(params)["resources"]
+print(f"Total gates: {resources.num_gates}")
```
### Tape Inspection
@@ -369,8 +375,8 @@ print("Wires used:", tape.wires)
### Circuit Transformations
```python
-# Expand composite operations
-expanded = qml.transforms.expand_tape(tape)
+# Expand composite operations to a target gate set
+expanded = qml.transforms.decompose(tape, gate_set={qml.RX, qml.RY, qml.RZ, qml.CNOT})
# Cancel adjacent operations
optimized = qml.transforms.cancel_inverses(tape)
diff --git a/skills/pennylane/references/quantum_ml.md b/skills/pennylane/references/quantum_ml.md
index 0a5bac44..60ab8fb1 100644
--- a/skills/pennylane/references/quantum_ml.md
+++ b/skills/pennylane/references/quantum_ml.md
@@ -113,6 +113,33 @@ for epoch in range(100):
optimizer.step()
```
+### PyTorch `TorchLayer` Integration
+
+Use `qml.qnn.TorchLayer` when the quantum circuit should behave like a `torch.nn.Module`. The QNode must have an `inputs` argument for data, and every other argument is treated as a trainable weight with a shape declared in `weight_shapes`.
+
+```python
+import torch
+import pennylane as qml
+
+n_qubits = 2
+dev = qml.device("default.qubit", wires=n_qubits)
+
+def qnode(inputs, weights):
+ qml.AngleEmbedding(inputs, wires=range(n_qubits))
+ qml.StronglyEntanglingLayers(weights, wires=range(n_qubits))
+ return [qml.expval(qml.Z(i)) for i in range(n_qubits)]
+
+weight_shapes = {"weights": (3, n_qubits, 3)}
+qlayer = qml.qnn.TorchLayer(qnode, weight_shapes)
+
+model = torch.nn.Sequential(
+ torch.nn.Linear(4, n_qubits),
+ qlayer,
+ torch.nn.Linear(n_qubits, 2),
+)
+```
+
### JAX Integration
```python
@@ -147,52 +174,9 @@ for i in range(100):
weights = weights - 0.01 * grads
```
-### TensorFlow Integration
-
-```python
-import tensorflow as tf
-import pennylane as qml
-
-dev = qml.device('default.qubit', wires=2)
-
[email protected](dev, interface='tf')
-def quantum_circuit(inputs, weights):
- qml.RY(inputs[0], wires=0)
- qml.RY(inputs[1], wires=1)
- qml.RX(weights[0], wires=0)
- qml.RX(weights[1], wires=1)
- qml.CNOT(wires=[0, 1])
- return qml.expval(qml.PauliZ(0))
+### TensorFlow Status
-# Keras layer
-class QuantumLayer(tf.keras.layers.Layer):
- def __init__(self, n_qubits):
- super().__init__()
- self.n_qubits = n_qubits
- weight_init = tf.random_uniform_initializer()
- self.weights = tf.Variable(
- initial_value=weight_init(shape=(n_qubits,), dtype=tf.float32),
- trainable=True
- )
-
- def call(self, inputs):
- return tf.stack([quantum_circuit(x, self.weights) for x in inputs])
-
-# Keras model
-model = tf.keras.Sequential([
- tf.keras.layers.Dense(2, activation='relu'),
- QuantumLayer(2),
- tf.keras.layers.Dense(2, activation='softmax')
-])
-
-model.compile(
- optimizer=tf.keras.optimizers.Adam(0.01),
- loss='sparse_categorical_crossentropy',
- metrics=['accuracy']
-)
-
-model.fit(x_train, y_train, epochs=100, batch_size=32)
-```
+TensorFlow support is no longer maintained as of PennyLane v0.44, and `qml.qnn.keras.KerasLayer` has been removed. Prefer PyTorch (`qml.qnn.TorchLayer`) or JAX/Optax for new quantum machine learning code.
## Quantum Neural Networks
@@ -563,7 +547,7 @@ def hybrid_transfer_model(image, classical_weights, quantum_weights):
1. **Start simple** - Begin with small circuits and scale up
2. **Choose encoding wisely** - Match encoding to data structure
-3. **Use appropriate interfaces** - Select interface matching your ML framework
+3. **Use maintained interfaces** - Prefer PyTorch or JAX for new quantum ML projects
4. **Monitor gradients** - Check for vanishing/exploding gradients (barren plateaus)
5. **Regularize** - Add L2 regularization to prevent overfitting
6. **Validate hardware compatibility** - Test on simulators before hardware