Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sorrel

Sorrel is a native, high-performance GUI for manual curation of spike-sorted electrophysiology data. It targets the same workflow as phy — cluster-by-cluster inspection, relabelling, merging, and splitting — but is built around a zero-cost, monomorphised Rust core and a wgpu-backed renderer.

Highlights

  • Multiple backends. Reads phy/Kilosort directories, SpikeInterface SortingAnalyzer (binary folder), legacy MATLAB rez.mat, and NWB files. Recording-only formats (SpikeGLX, Open Ephys, Mountainsort MDA) are supported as raw trace sources.
  • Native egui + wgpu UI. Trace, raster, ISI, CCG, waveform, template, feature, drift, probe, similarity, quality, and suggestion views.
  • GPU compute path. Optional wgpu kernels for common-median referencing, high-pass filtering, and mean-snippet extraction along the trace window; transparent CPU fallback.
  • Static dispatch core. Session<P> is generic over a DataProvider trait — every hot path (downsampling, vertex generation, journaling, metrics) is monomorphised per backend.
  • Durable curation. Every label change, merge, split, and undo/redo is written to an append-only journal before the in-memory session moves. The journal is replayable and idempotent.
  • Headless QC export. sorrel qc runs the full metrics pipeline and writes cluster_qc.tsv + cluster_qc.json without spawning a window.
  • Python bridge. The sorrel-py crate exposes sorrel.open(recording, sorting) for SpikeInterface users.

Visit the Sorrel website or download the native build for your OS. Source code is hosted at github.com/caniko/sorrel.

Installation

Desktop users should download the native build for their OS. The stable 0.4.0 release ships these builds:

OSCPUDownload
Linuxx86_64AppImage or .tar.gz
LinuxARM64.tar.gz
macOSApple silicon.tar.gz
Windowsx64.zip or standalone .exe files

Release binaries follow the code signing policy. The 0.4.0 binaries include phy export but not HDF5, so they cannot read NWB or legacy MATLAB rez.mat. For those readers, build from trunk with Cargo or with Nix.

Python

Use this route for the GUI + Python API. Wheels for Linux x86_64 / aarch64 (glibc 2.34+), Windows x86_64 and macOS arm64 (Python 3.8+) hold the Python API and the GUI binary. They are on PyPI as sorrel-ephys, since PyPI’s sorrel is an unrelated project. The import is still import sorrel:

pip install sorrel-ephys

Each GitHub release attaches the same wheels (sorrel_ephys-<VERSION>-cp38-abi3-<PLATFORM>.whl). There is no Windows ARM64 wheel.

nix build .#release-bundle.wheels.x86_64-linux builds one locally (aarch64-linux, windows, darwin-aarch64 likewise). See Integrations for the API.

Windows

Windows package managers

Chocolatey puts sorrel and sorrelw on your PATH:

choco install sorrel

Alternatively, download the Windows x64 ZIP. The 0.4.0 release has no native Windows ARM64 build. Winget is not yet available; track the pending submission.

Windows launchers and shortcuts

sorrel.exe is a console program. sorrelw.exe is the same program without a console window: it starts sorrel.exe with the same arguments (bare, it opens the launcher) and exits. Use it from shortcuts, Win+R and Explorer.

Start menu. The Chocolatey package adds a Sorrel entry that runs sorrelw.exe. If you unpacked the ZIP by hand, run this once:

sorrel install-shortcut            # creates the Start-menu entry
sorrel install-shortcut --remove   # deletes it

It writes %APPDATA%\Microsoft\Windows\Start Menu\Programs\Sorrel.lnk, pointing at the sorrelw.exe next to sorrel.exe. Run --remove before deleting a manually unpacked copy.

Chocolatey also installs uv, which sorrel auto uses to run its SpikeInterface pipeline. sorrel mcp works from the same PATH, so an agent can launch it by name (see Agents).

Chocolatey moderation can delay new versions after the GitHub release.

Completions. Add this line to your $PROFILE (notepad $PROFILE) to get PowerShell completion in every session:

sorrel completions powershell | Out-String | Invoke-Expression

Standalone files. The release also lists x64 executables for use without a package manager: sorrel-<VERSION>-x86_64-windows.exe and sorrel-<VERSION>-x86_64-windows-gui.exe. sorrelw.exe looks for sorrel.exe next to itself, so rename the downloads back to sorrel.exe and sorrelw.exe and keep them in one folder.

SmartScreen. The executables are not code-signed yet, so Windows SmartScreen may warn about an unknown publisher when you run a download (click More info, then Run anyway). Signing is planned through SignPath Foundation (see the Code signing policy). Until then, check a download before you run it. Every release lists SHA256SUMS.txt, signed with minisign (SHA256SUMS.txt.minisig; the public key is keys/minisign.pub), and each file has Sigstore bundles (<file>.cosign.bundle, plus an SLSA provenance <file>.intoto.bundle):

(Get-FileHash .\sorrel-<VERSION>-x86_64-windows.zip).Hash   # compare with SHA256SUMS.txt
minisign -V -p minisign.pub -m SHA256SUMS.txt
cosign verify-blob --bundle sorrel-<VERSION>-x86_64-windows.zip.cosign.bundle `
  --certificate-identity-regexp 'https://github.com/caniko/sorrel/' `
  --certificate-oidc-issuer https://token.actions.githubusercontent.com `
  sorrel-<VERSION>-x86_64-windows.zip

Uninstall. choco uninstall sorrel removes the Chocolatey package. Sorrel’s per-user state (the GUI instance file, host registry, gui.log, sorrelw.log) stays in %LOCALAPPDATA%\sorrel. The derived-data cache and your curation journals stay next to your data. Delete the folder when you no longer need it:

Remove-Item -Recurse -Force $env:LOCALAPPDATA\sorrel

The window opens on the first backend wgpu likes (Vulkan or DX12). If it crashes at startup with a shader error, or stays blank, pick the other one:

$env:WGPU_BACKEND = "vulkan"   # or "dx12", or "gl"
sorrel open <DATA_DIR>

sorrel gpu-check shows what each backend can do. Trace filtering falls back to the CPU on its own when a backend rejects the compute kernels.

With Cargo

cargo install sorrel at version 0.4.0 enables phy-export by default, not hdf5, just like the 0.4.0 release binaries.

A source build from trunk enables both phy-export and hdf5 by default. It reads NWB and MATLAB v7.3 rez.mat and bundles HDF5 at build time. Use a C compiler and CMake 3.26 or newer; no system HDF5 library is needed.

cargo build --release -p sorrel

The binary is written to target/release/sorrel. A second binary, sorrelw, is the console-free launcher for Windows (see Windows). Shell completions come from sorrel completions <shell>; see the CLI reference.

Full phy export (sorrel export-phy, the export_phy MCP tool, the Export phy button and Session.export_phy in sorrel-py) is the phy-export feature, on by default. To build the CLI without both HDF5 and phy export, use:

cargo build --release -p sorrel --no-default-features

With Nix

nix build .#sorrel        # includes HDF5

From trunk, nix build builds the default sorrel package with HDF5 bundled. The flake also exposes:

  • .#website — the Plinth landing and download pages.
  • .#docs — this mdBook documentation.
  • .#site — combined static site, with the docs mounted under /docs/.

The Nix packages ship a sorrel.desktop menu entry with the app icon. They also install sorrelw, which on Linux and macOS only runs the sibling sorrel; the release archives, AppImage and cargo install users can ignore it.

Home Manager

Add the flake as an input and enable the module:

{
  inputs.sorrel.url = "github:caniko/sorrel";
  # in your Home Manager configuration:
  imports = [inputs.sorrel.homeManagerModules.default];
  programs.sorrel.enable = true;
}

GPU drivers

Sorrel draws through wgpu, so it runs on Intel, AMD and NVIDIA GPUs alike. It uses Vulkan (Linux, Windows), DX12 (Windows) or Metal (macOS), and falls back to OpenGL. Trace CMR and high-pass filtering run on the GPU when the adapter supports compute shaders, and on the CPU otherwise.

  • Linux, AMD and Intel: Mesa (radv / anv Vulkan drivers; distro packages mesa-vulkan-drivers and libvulkan1 on Debian/Ubuntu).
  • Linux, NVIDIA: the proprietary driver with its Vulkan ICD. On nouveau, use Mesa’s NVK.
  • NixOS: hardware.graphics.enable = true;, plus services.xserver.videoDrivers = [ "nvidia" ]; for NVIDIA. A Nix-built sorrel on another distribution needs nixGL to find the host driver.
  • Release tarballs and AppImage: need glibc 2.31 or newer (Ubuntu 20.04, Debian 11, Fedora 32, RHEL 9 and later) and use the distribution’s own Vulkan/GL loader and drivers.
  • Windows and macOS: no extra setup.

Run sorrel gpu-check to see every adapter, which one the GUI prefers, and whether the compute kernels match the CPU on each. The usual wgpu variables override the choice, for example on hybrid laptops:

WGPU_POWER_PREF=low sorrel ...   # integrated instead of discrete GPU
WGPU_BACKEND=gl sorrel ...       # OpenGL if Vulkan misbehaves

Development Shell

nix develop

The shell pulls in the Rust toolchain, native GUI dependencies (wgpu / egui), mdbook for the docs, and plinth-project for the website.

To run the docs and site locally:

mdbook serve docs
plinth-project dev --config website/plinth-project.toml

Quick Start

Point Sorrel at a sorting output and it will auto-detect the backend:

sorrel open <DATA_DIR>

The detector looks for, in order:

  1. spike_times.npy + spike_clusters.npy → phy / Kilosort.
  2. recording.json (or binary.json) + sorting/ → SpikeInterface SortingAnalyzer.
  3. A .nwb file path → NWB.
  4. A rez.mat / rez2.mat file path → legacy MATLAB v7.3 (HDF5).

You can force the choice with --backend kilosort | sorting-analyzer | nwb | rez. The older ks4-rez name is still accepted as an alias for rez.

Phy / Kilosort

For Kilosort 4, open the results directory containing its native .npy arrays.

sorrel open my_run/phy

Sample rate, channel count, dtype, header offset, and dat path are read from params.py when present. CLI flags override on a per-field basis:

sorrel open my_run/phy \
  --dat recording.dat \
  --sample-rate 30000 \
  --channels 384 \
  --dtype int16

When the trace metadata isn’t in params.py, point Sorrel at a SpikeGLX or Open Ephys metadata file:

sorrel open my_run/phy --spikeglx-meta run.imec0.ap.meta
sorrel open my_run/phy --oebin Record\ Node\ 101/structure.oebin

SpikeInterface SortingAnalyzer

sorrel open my_run/sorting_analyzer

The analyzer must be saved with format='binary_folder' and have a flattened sorting under <root>/sorting/. A Zarr analyzer converts with analyzer.save_as(format="binary_folder", folder=...).

NWB and legacy MATLAB rez.mat

Both readers are enabled by default on trunk, but not in the stable 0.4.0 binaries. See Installation. The rez.mat reader is for MATLAB v7.3 (HDF5) files from Kilosort 2, 2.5, and 3.

sorrel open my_session.nwb
sorrel open rez.mat --dat path/to/recording.bin

Curation journal

--journal PATH overrides the on-disk curation journal. The default is <root>/sorrel.journal. The journal is replayed on every open, so reopening the same directory restores all prior edits.

CLI Reference

sorrel
sorrel open <DATA_DIR> [OPTIONS]
sorrel run [<DATA_DIR>] [OPTIONS]
sorrel <SUBCOMMAND> ...

Use sorrel for the detached GUI launcher, sorrel open for a dataset tab, or sorrel run for the foreground GUI (add --headless for agents). Subcommands can process the same datasets without a window.

<DATA_DIR> is a phy / Kilosort or SortingAnalyzer directory. Builds with HDF5 support also accept *.nwb and rez.mat.

Subcommands

SubcommandWhat it does
open <DATA_DIR> [OPTIONS]Open the dataset as a new tab in the running GUI, or start the GUI detached if none is running. If the dataset is already open, its tab is focused. See Opening a window.
run [<DATA_DIR>] [OPTIONS]The GUI in the foreground, with logs and Ctrl-C. Hands the dataset to a running window as a tab. --standalone always starts a separate window; --headless runs the session host with no window.
status [<DATA_DIR>] [--json]The running GUI (pid, tabs), every session host (dataset, kind, pid, port, alive) and the log file of a detached GUI. See Status.
call <DATA_DIR> [OPTIONS] <TOOL> [ARGS_JSON]Run one MCP tool from a shell. See Call.
agent-guidePrint a primer for LLM agents, with the live command list, MCP tools and running hosts. See Agent guide.
completions <SHELL>Print a completion script for bash, zsh, fish, elvish or powershell. See Completions.
install-shortcut [--remove]Windows only: create (or delete) the Start-menu shortcut Sorrel.lnk, which runs sorrelw.exe with the app icon. See Windows.
qc <DATA_DIR> --out DIR [OPTIONS]Run every metric on the current curation and write cluster_qc.tsv + cluster_qc.json into DIR.
suggest <DATA_DIR> [--json] [OPTIONS]Rank merge and split suggestions; a table by default, {"merges": [...], "splits": [...]} with --json.
apply <DATA_DIR> (--rules FILE | --curation FILE) [--dry-run] [--save]Label clusters from QC-metric threshold rules, or import a SpikeInterface curation.json (labels, tags, merges), as one undoable batch; see docs/src/usage/rules-example.toml.
auto <DATA_DIR> [--llm] [--llm-model MODEL] [--gain-to-uv UV] [--no-merge] [--no-unitrefine] [--reuse] [--dry-run] [--save]Automatic curation with SpikeInterface (merge presets, Bombcell + UnitRefine, optional Claude tiebreak), applied as one undoable batch with provenance and review:* tags; see Automatic curation.
rescue <DATA_DIR> [--apply] [--save] [OPTIONS]Matched-filter rescue of spikes the sorter missed from existing units (FDR-controlled); a dry run unless --apply. See Spike rescue.
describe <DATA_DIR> [--json]Print a dataset summary like phy’s template-describe: data file, dtype, sample rate, duration, channels, spikes, clusters per group, templates, PC features, custom labels and the undo history. --json prints it as JSON.
report <DATA_DIR> [--out FILE] [--clusters IDS] [--label L] [--tag PREFIX]Self-contained HTML: an overview table, then one card per cluster with headline metrics, tags, template on its strongest channels, ISI (linear and log), ACG, amplitude over time and every metric; prints cleanly to PDF. --tag review: renders the review queue.
share <DATA_DIR> [--port N | --relay ADDR]Host this dataset for a remote curator (see Remote curation).
join <CODE> [--direct ADDR | --relay ADDR] [--into DIR]Join a shared session as the remote curator.
mcp [<DATA_DIR>] [OPTIONS]MCP over stdio for agents and notebooks: metrics, suggestions, SVG plots, journaled relabel / merge / split / undo / save, proposals. Without <DATA_DIR> it attaches to the GUI’s active tab or the only running host; see Agents.
mcp tools [--json]List the MCP tools, offline.
mcp config [--client claude | codex | json] [<DATA_DIR>]Print how to register sorrel with an agent. See MCP tools and config.
diff <A.tsv> <B.tsv> [--json]Compare two cluster_group.tsv files: confusion table, Cohen’s kappa, per-cluster disagreements. With two directories and --root, a spike-level score (Blind bench).
blind <DATA_DIR> --input <IN> --truth <TRUTH>Write a double-blind bench pair from a curated session (Blind bench).
journal dump <JOURNAL> [--json]Print every committed journal record, oldest first.
journal replay <DATA_DIR> --out DIRReplay the journal and write spike_clusters.npy, cluster_group.tsv, curation.json into DIR.
export-phy <DATA_DIR> --out DIR [--copy-raw]Write the curated data as a complete phy directory into DIR, from any backend; see Exporting a phy directory.
clear-cache <DATA_DIR>Remove <DATA_DIR>/.sorrel/cache/.
gpu-checkList every GPU adapter and check the compute kernels against the CPU on each; see GPU drivers.

Every subcommand that takes <DATA_DIR> accepts the open options below, opens the data through the same backend detection, and replays the same curation journal as the GUI, so headless output always reflects the current curation.

The old spellings are removed: sorrel <DATA_DIR> is sorrel open, --headless is sorrel run --headless, --export-qc DIR is sorrel qc <DATA_DIR> --out DIR, --clear-cache is sorrel clear-cache, and serve is mcp.

Opening a window

Bare sorrel starts the GUI detached from the terminal, showing a launcher (Open dataset…, drag-and-drop, recent datasets). If a window is already running, it is focused. The desktop entry runs this.

sorrel open adds a dataset as a tab to the running window, or starts one if none is running. Each dataset is a tab; Ctrl-O opens another and Ctrl-W closes the current one.

sorrel run is the same GUI in the foreground: the terminal stays attached, logs go to it, and Ctrl-C stops it. If a window is already running, run hands the dataset over as a tab and returns. --standalone always starts a separate window. sorrel run --headless <DATA_DIR> runs the session host and MCP listener with no window, until Ctrl-C.

Status

sorrel status lists the running GUI (pid, tabs with dataset, dirty and active), every session host (dataset, kind gui or headless, pid, port, alive), and the log file of a detached GUI. --json prints the same as JSON.

Call

sorrel call <DATA_DIR> [OPTIONS] <TOOL> [ARGS_JSON] runs one MCP tool through the running host, or in-process when none is running. It prints the result and exits non-zero on error. --raw prints the JSON-RPC response instead.

sorrel call ks4/ metrics '{"cluster": 12}'

MCP tools and config

sorrel mcp tools [--json] lists the MCP tools without starting a host.

sorrel mcp config [--client claude|codex|json] [<DATA_DIR>] prints how to register sorrel with an agent: a claude mcp add sorrel -- sorrel mcp line, a Codex [mcp_servers.sorrel] TOML block, or an mcpServers JSON block.

Agent guide

sorrel agent-guide prints a primer for LLM agents, including the live command list, the MCP tools and the running hosts. sorrel agent-guide --prompt review prints only the review prompt exactly as the MCP review prompt serves it. Setting SORREL_RUBRIC or SORREL_REVIEW (a file path, or the text itself) overrides the rubric or the review instructions for sorrel mcp, sorrel auto --llm and this command.

Blind bench

sorrel blind <DATA_DIR> --input <IN> --truth <TRUTH> splits a curated session into a double-blind pair. IN is the sorter’s own output, an allowlist of the root files (spike_*, templates, channel_*, pc_features and the like, and params.py) with the raw recording and its .ch/.meta inside it as regular files under their own names (params.py is pointed at them), so nothing in IN leads back to DATA_DIR. Files under 64 MiB are copied, larger ones hard-linked (a copy where that fails). The sorter’s cluster_KSLabel/ContamPct/Amplitude.tsv are rewritten to the root cluster ids. There is no journal, other cluster_* file, curation.json, phy.log, sorrel_auto/, .phy/, mcp/, .sorrel/ or sorrel_original/, and spike_clusters.npy is checked against the journal’s baseline hash. TRUTH holds the journal head (spike_clusters.npy, cluster_group.tsv, curation.json) and provenance.json (edits by actor and method, pure_manual, anchored, journal hash, seal state). Both directories must be empty or absent.

With --phy-curated the session is a Kilosort sort curated in phy instead: spike_templates.npy (which phy never rewrites) becomes IN’s spike_clusters.npy, and TRUTH takes the top-level spike_clusters.npy and cluster_group.tsv. phy.log, which lists the human’s merges, is never copied. phy keeps no actor history, so provenance.json assumes the curation is manual unless DATA_DIR holds a sorrel journal, sorrel_original/ or sorrel_auto/ (then pure_manual is false and anchored true). curated is false, with a warning, when spike_clusters.npy equals spike_templates.npy and the labels are the sorter’s. DATA_DIR is only read. If params.py names a dat_path that doesn’t exist, the copy points at the recording of the same name next to it.

sorrel diff <TRUTH> <TEST> --root <IN> [--json] [--match 0.8] [--min-spikes 10] [--split-share 0.1] [--binary | --no-binary] [--disputed FILE] scores a curation of IN against the truth spike by spike: unit recovery (Jaccard at least --match and the same label), root-cluster label agreement, merge pairs, splits, noise exclusion and ARI. Misses are keyed by root cluster id; --disputed lists root ids (one per line) to leave out. When the truth only uses good and noise, mua and unsorted count as noise (--binary; --no-binary keeps them apart) so a vocabulary gap is not scored as a miss.

Dev mode (--features dev)

The double-blind bench keeps its results in one SQLite file, bench/results.sqlite (git-lfs, derived data only: opaque ids and numbers, no paths or dataset names). It is a cargo feature that is off by default, so release, nix and CI builds carry no SQLite: cargo build --release -p sorrel --features dev.

The DB is --db FILE, else $SORREL_DEV_DB, else bench/results.sqlite found by walking up from the cwd. Every text value is refused if it holds / or \, or a string of the --deny FILE (else $SORREL_DEV_DENY) list of sealed ids and source basenames. Prompt text in variants.rubric / variants.review is the one exception to the separator rule. scripts/bench_curation.py --db FILE calls these for you.

  • sorrel dev db init|status|query SQL: query is read-only and prints TSV.
  • sorrel dev record-session --sid S --split dev --input DIR --truth DIR: the input’s fingerprint (journal baseline_hash of spike_clusters.npy), its root cards (level-2 brief) and the human verdict per root (truth_roots: noise, kept, cores, cleanup or other, with the good share). --split holdout records an id and nothing else.
  • sorrel dev record-run --run-dir DIR [--variant-dir DIR]: run.json, evidence.json, the claude usage and the actions of the run’s journal. Dev runs only.
  • sorrel diff TRUTH TEST --root INPUT --record RID [--db FILE]: also writes the score’s numeric fields (dotted names such as good_units.recall) and misses. TEST must be the run’s own output (record-run hashes it), TRUTH the session’s recorded truth and --root its recorded input; the scoring options are stored with the score.
  • sorrel dev ledger --json FILE: holdout aggregates (no sid, no run id), each row with a query id; the same id re-records in place, a new one appends.
  • sorrel dev distill --out DIR: exemplars.tsv, priors.toml, thresholds.toml and lineage.md (one row per variant, arm, revisions and scoring options) from the dev sessions, each headed with the DB sha, the dev sids and a learned_rev hash of the content.

Completions

sorrel completions <bash|zsh|fish|elvish|powershell> prints a completion script for the shell. For bash:

sorrel completions bash > ~/.local/share/bash-completion/completions/sorrel

For PowerShell, put sorrel completions powershell | Out-String | Invoke-Expression in $PROFILE.

Install shortcut

sorrel install-shortcut creates %APPDATA%\Microsoft\Windows\Start Menu\Programs\Sorrel.lnk for the current user. It targets sorrelw.exe in the folder of the running sorrel.exe and uses its icon, through PowerShell’s WScript.Shell. --remove deletes the shortcut. It is useful for manual ZIP installs; the Chocolatey package creates its own entry. On other systems the command fails with “Windows only”. sorrelw is sorrel without a console window; see Windows.

Open options

FlagDescription
--backend NAMEkilosort | sorting-analyzer | nwb | rez. Auto-detected when omitted. ks4-rez is an alias for the legacy MATLAB rez backend, not for Kilosort 4 output.
--dat PATHRaw recording. Overrides params.py:dat_path.
--sample-rate HzOverrides params.py:sample_rate.
--channels NOverrides params.py:n_channels_dat.
--dtype DTYPEint16 | uint16 | int32 | float32. Overrides params.py:dtype.
--offset BYTESHeader bytes to skip in the .dat.
--journal PATHCuration journal. Default: <root>/sorrel.journal.
--discard-journalSet the existing journal aside before opening: renamed to <journal>.<unix seconds>, not deleted. On a phy directory, sorrel_original/ is set aside too (see Saving).
--spikeglx-meta PPopulate sample-rate / channels / dtype from a SpikeGLX .meta.
--oebin PATHPopulate sample-rate / channels / dat path from an Open Ephys structure.oebin.
--events FILEPSTH events: events.csv, events.npy, or an .nwb trials table (GUI only).
-h, --helpPrint usage.

When params.py is present, sample-rate, channels, dtype, offset, and dat-path all default from it. CLI flags override per-field.

Examples

# Auto-detect, defaults from params.py
sorrel open my_run/phy

# Force a backend
sorrel open my_run --backend sorting-analyzer

# Override sample rate but inherit everything else from params.py
sorrel open my_run/phy --sample-rate 25000

# SpikeGLX run without a params.py
sorrel open my_run/phy --spikeglx-meta run.imec0.ap.meta

# Run all metrics headlessly and write QC artefacts
sorrel qc my_run/phy --out out/qc/

# Feed suggestions to a script
sorrel suggest my_run/phy --json | jq '.merges[] | select(.score > 0.7)'

# See what a colleague's journal would do before opening it
sorrel journal dump my_run/phy/sorrel.journal

Backends & Inputs

Sorrel reads several sorting and recording formats. The general rule:

  • Sorting backends carry both a sorting and (optionally) the raw trace.
  • Recording-only formats plug into a sorting via --dat / --spikeglx-meta / --oebin.
KindFormatNotes
Sortingphy / Kilosort directoryReads Phy arrays as-is, including Kilosort 4’s native .npy output.
SortingSpikeInterface SortingAnalyzer (binary folder)Reads recording.json (binary, or a channel- and sample-preserving preprocessing chain over binary), the flat sorting under sorting/, optional probe.json, and extensions/quality_metrics/metrics.csv.
SortingNWB (local HDF5)HDF5 is bundled by default. Reads /units, with or without a trace. --nwb-series selects an acquisition or processed series; --dat pairs a separate raw NWB. See NWB.
SortingNWB-Zarr (local Zarr v2 directory)Default zarr feature. Same units and lazy trace reader as HDF5 NWB; --dat can mix storage formats. See NWB.
SortingDANDI NWB / NWB-Zarr (remote)On by default. Read-only range streaming with local journals. See DANDI streaming.
SortingLegacy MATLAB rez.mat / rez2.matMATLAB v7.3 (HDF5) files from Kilosort 2, 2.5, and 3. See Legacy MATLAB rez.mat.
RecordingSpikeGLX (*.bin + *.meta)Use as --dat; pass --spikeglx-meta for sample rate / channels / dtype.
RecordingOpen Ephys binary (continuous.dat + structure.oebin)Use as --dat; pass --oebin to inherit metadata.
RecordingMountainsort MDA (*.mda)Use as --dat. Reads the MDA header.

Backend detection

When --backend is not specified, the detector is run on the input path:

  1. File path *.nwb → NWB (HDF5).
  2. File path rez.mat / rez2.mat → legacy MATLAB reader (HDF5).
  3. Directory containing spike_times.npy + spike_clusters.npy → phy / Kilosort.
  4. Directory ending in .nwb.zarr or with nwb_version in root .zattrs → NWB (Zarr).
  5. Directory containing recording.json (or binary.json) and a sorting/ folder → SortingAnalyzer.

If none match, Sorrel exits with a message listing what it looked for.

Probe geometry

If a probe.json or probegroup.json (probeinterface) is present in the directory, Sorrel uses it to lay out the WaveformView and ProbeView. Phy’s channel_positions.npy wins when both are present (it’s authoritative for the row order in the raw .dat).

Quality metrics sidecars

Sorrel auto-loads cluster-level metrics at startup from any of:

  • quality_metrics.csv (one row per cluster, header columns become metric names — SI’s format).
  • cluster_<metric>.tsv files (one file per metric — phy’s format).
  • /units columns marked as Sorrel QC metrics by the Python NWB export.

NaNs mean the upstream tool didn’t report a value for that cluster.

Kilosort / phy2

Sorrel reads everything phy reads. The minimum is two arrays plus a trace; the rest of the phy artefacts are picked up opportunistically and unlock additional views.

Required

FilePurpose
spike_times.npySpike sample indices.
spike_clusters.npyCluster ID for each spike.

Plus a raw trace — typically recording.dat. The path can come from params.py:dat_path, --dat, --oebin, or default to recording.dat inside the directory.

Optional, used when present

FilePowers
params.pySample rate, n channels, dtype, offset, dat path.
cluster_group.tsvInitial good / mua / noise / unsorted labels.
channel_positions.npyProbe geometry — authoritative row order.
templates.npyTemplate view, similarity matrix.
template_features.npy, template_feature_ind.npyTemplate-feature scatter.
pc_features.npy, pc_feature_ind.npyFeature view (PC space).
amplitudes.npyAmplitude-vs-time scatter, drift map.
similar_templates.npySimilarity view shortcut.
cluster_<metric>.tsvQuality-metric columns in the cluster table.
quality_metrics.csvSI-style quality metrics.
probe.json / probegroup.jsonProbe geometry fallback (probeinterface).

Loading model

Spike arrays and the raw .dat are memory-mapped. On open, Sorrel buckets spike times and amplitudes once per cluster; subsequent hot-path lookups are slice borrows into the bucket. The .npy parser supports the dtypes Kilosort actually emits for these arrays.

Integrations

Sorrel speaks the phy2 directory format natively. Most spike-sorting pipelines either emit phy directly or have a one-line export step that does. This page lists the integration paths.

SpikeInterface

SpikeInterface (SI) is the dominant Python framework for spike-sorting workflows. Two ways to bring an SI run into Sorrel:

1. Phy export (works today, no extra deps)

import spikeinterface.exporters as siex
siex.export_to_phy(
    sorting_analyzer,        # SortingAnalyzer with templates + waveforms
    output_folder="my_run/phy",
    copy_binary=True,        # so sorrel can mmap recording.dat in place
    compute_pc_features=True # enables the FeatureView
)

Then:

sorrel open my_run/phy

Sorrel reads spike_times.npy, spike_clusters.npy, params.py, channel_positions.npy, templates.npy, pc_features.npy, similar_templates.npy, and cluster_group.tsv exactly as phy does.

2. Native SortingAnalyzer (binary folder)

If the analyzer was saved with format='binary_folder' and the sorting was flattened to spike_times.npy + unit_indices.npy under <root>/sorting/, point Sorrel directly at the analyzer root:

sorrel open my_run/sorting_analyzer

The current implementation reads recording.json (sample rate, channel count, dtype, bin path), the flat sorting arrays, the unit ids (sorting/numpysorting_info.json, or sorting/unit_ids.npy from older layouts), the optional probe.json for geometry, and extensions/quality_metrics/metrics.csv into the cluster table. recording.json may describe a raw binary file (a recording from spikeinterface.read_binary) or a SpikeInterface binary folder (rec.save(folder=..., format='binary'), a BinaryFolderRecording): for the latter Sorrel follows its folder_path to that folder’s binary.json. Either may sit under a preprocessing chain that keeps every channel and sample (bandpass, highpass or notch filters, common reference, whitening, phase shift, scaling, centering, z-scoring, highpass spatial filter). Sorrel reads the binary source beneath it and does not re-apply the chain: traces show the source samples through Sorrel’s own highpass. A chain that slices channels or frames, resamples or aggregates fails with an error naming the class. Zarr is not read: a Zarr analyzer converts with analyzer.save_as(format="binary_folder", folder=...), and a Zarr recording needs recording.save(format="binary", folder=...) and a new analyzer on it (save_as keeps the Zarr recording).

Round-tripping curation back into SI

Sorrel writes the same two files SI’s read_phy() reads:

  • spike_clusters.npy — updated per-spike cluster assignment after merges/splits.
  • cluster_group.tsv — good/mua/noise/unsorted labels.
import spikeinterface.extractors as se
sorting = se.read_phy("my_run/phy")  # picks up sorrel's edits

It also writes curation.json for SI’s apply_curation. A session with merges or splits is SI’s list form (SequentialCuration): structural steps, then one labels-only step. That expresses histories a single pass cannot — a unit both merged and split, a repeated split, edits of units Sorrel created — and the round trip is one call:

import sorrel
import spikeinterface.curation as sc
curated = sc.apply_curation(analyzer, sorrel.read_curation(result_dir))

read_curation returns the list as-is; a labels-only session, and a phy directory saved onto itself, stay one Curation dict. Ids are SI’s own: a merge keeps its target’s id, a split’s child keeps the id Sorrel gave it and the spikes left behind get a fresh one. A merge into a unit an earlier merge emptied brings back the target’s id; when it has a single source there is nothing for SI to merge, so that unit keeps the source’s SI id. A rescue (AddSpikes) has no SI curation slot, so its document lists the edits under sorrel_unrepresentable and read_curation raises instead of silently dropping spikes.

Quality metrics

Sorrel auto-loads sidecar metrics at startup:

  • SI’s quality_metrics.csv (one row per cluster, header columns become metric names).
  • Phy’s cluster_<metric>.tsv files (one file per metric).

Metrics surface as columns in the cluster table. NaN means the upstream tool didn’t report a value for that cluster.

Probe geometry

If the directory contains a probe.json or probegroup.json in probeinterface format, Sorrel will use it for the WaveformView layout. Phy’s channel_positions.npy still wins when both are present (it’s authoritative for the row order in the raw bin).

Recording-only formats

These are recording formats — they don’t carry a sorting on their own, but Sorrel can use them as the raw .dat for an existing phy directory:

FormatWhat we readUse as --dat
SpikeGLX<run>.<stream>.bin + <run>.<stream>.metayes
Open Ephys binarycontinuous.dat + structure.oebinyes
Mountainsort MDA*.mda (header-prefixed flat array)yes
mtscomp (IBL)<run>.cbin + <run>.ch (zlib chunks)yes

For SpikeGLX or Open Ephys, point --dat at the bin file and pass --sample-rate/--channels from the .meta/.oebin (or let Sorrel auto-detect — see Backend detection).

NWB

sorrel open my_session.nwb
sorrel open my_session.nwb --nwb-series ElectricalSeriesRaw
sorrel open my_session.nwb --nwb-series /processing/ecephys/FilteredEphys/Processed
sorrel describe my_session.nwb --nwb-series none --json
sorrel open sorted_units.nwb --dat recording.nwb
sorrel open sorted_units.nwb --sample-rate 30000  # if no resolution is recorded

What Sorrel reads:

  • Units. /units/spike_times and spike_times_index, one unit per row. Units with no spikes are kept. /units/id supplies the numeric unit ID; a unique unit_name string column preserves the upstream names in curation.json. Sorrel reads good, mua, noise and unsorted from label, quality or KSLabel, in that order. Sorrel’s Python-exported origin, tags and parent IDs are restored. Parents without a table row are displayed as unit:<id> instead of local cluster IDs. Columns marked Sorrel QC metric. populate the cluster table, just like sidecar metrics. Unrecognized columns are ignored.
  • Trace. Sorrel reads single windows on demand and caches recent blocks instead of loading the entire trace. It looks for ElectricalSeries (or an extension subtype declared in /specifications) under /acquisition and /processing, with 2-D data (time × channels) or 1-D data (one channel). Conflicting cached type definitions that affect series selection are refused. By default it selects only from /acquisition, preferring 2-D series and breaking ties by path, and logs the available paths when there is more than one. On an automatic single-file open, if the selected series and /units/electrodes reference the same table but the series omits any of the Units’ electrodes, Sorrel opens without a trace. Pass --nwb-series PATH to force that series. A /processing series supplies a trace and clock only when explicitly selected with --nwb-series. The reader follows same-file HDF5 soft links, with a bounded hop count and cycle checks; literal .. path components are not supported. Discovery can recognize a soft-linked child as a series but does not recurse into it. HDF5 external links, links that reach through them, external raw storage, virtual datasets, and Zarr zarr_link nodes are refused; open the file or store that holds the data directly. --nwb-series takes an acquisition name or an absolute path in the NWB file, not a filesystem path. Use a separate --journal when curating against another series or a different paired recording. To reuse an open tab or attach call or mcp to its host, pass the same open options; conflicting options are refused rather than silently ignored.
  • Time base. Spike times on the NWB session clock become sample indices as round((t - starting_time) × rate). Sorrel uses the series rate by default. If 1 / spike_times.resolution is within one part per million of that rate, it also declares a Units clock. If the two clocks place any spike on different samples, pass --sample-rate <Hz> to choose one. The value must equal a declared clock exactly, including the full value of a stored float32 rate widened to float64. Copy one of the rates printed in the error; approximate values are refused. In a single file, an unspecified or more distant resolution is not a clock. With per-sample timestamps, the first timestamp gives the start and the end-to-end mean interval gives the series rate. Timestamps must strictly increase and stay within 0.001 samples of the inferred grid, plus four floating-point steps at the largest absolute timestamp (converted to samples) to allow for rounding at large clock origins. Irregular timestamps are refused; when Sorrel detects a large gap, it reports the adjacent sample indices and the size of the jump. NWB trials used as events are shifted by the same start time; CSV/NPY event times are already relative to the recording.
  • Sample types. int8, uint8, int16, uint16, int32, uint32, int64, float32 and float64 are read in their stored type. Sorrel converts to float32 microvolts as (data × conversion × channel_conversion[ch] + offset) × 10⁶. Other dtypes are refused.
  • Channels. The series’ electrodes region maps each data column to an electrodes-table row. That row’s id becomes the channel id and its rel_x/rel_y the probe position. x/y/z are brain coordinates and are not used as probe geometry; without rel_x/rel_y the session has no channel positions.

Units without a trace. Without a selected ElectricalSeries, Sorrel takes the rate from 1 / spike_times.resolution. If that resolution is unspecified and no raw NWB is paired, you must supply --sample-rate HZ as an analysis grid. Spike times are relative to zero (timestamps_reference_time). The electrodes table supplies channels if present, but there is no raw trace or waveform extraction. Session span comes from unit observation intervals, epochs, or trials (in that order), or is estimated from the spike extent; it is never a trace duration.

Sorrel refuses a selected series with an invalid time base, including gaps or backward steps in its timestamps. Pass --nwb-series none to open the units without that trace. The same option works with open, describe, qc, report, call, and mcp. Do not combine it with --dat; select a series literally named none with --nwb-series /acquisition/none. Use a separate --journal when switching between units-only and trace-backed opens of the same recording.

describe shows why the series was skipped. Its JSON output and cluster_qc.provenance.json include provenance.mode: "units-only" and provenance.skipped_series for explicit skips. The latter records the default acquisition series path (series), status, and message. Sorrel checks shape and type and probes timestamps without scanning them end to end. It does not read trace samples or the skipped series’ electrodes region. regular (probe) only means the sampled timestamps fit; an unprobed gap can still be present. not fully checked means the probe hit the eight-chunk I/O budget, was otherwise inconclusive, or had no per-sample timestamps. A refused result names the failing check; when the probe locates a jump it also reports sample, next_sample, jump_s (signed seconds), and t_s (the two timestamps in seconds). If there is no acquisition series, the status says so. For trace-backed QC exports, the mode is "trace".

Without the opt-in, --dat recording.nwb lets the raw file supply the trace, channels and time base; use --nwb-series if that file has only processed series. If a Units rate is declared, it must be within one part per million of the raw series rate. The same exact clock choice and spike-index check apply. Spike indices must fit inside the raw series. The files must have the same timestamps_reference_time; Sorrel does not infer an offset between files.

The reader needs an NWB with /units. Default builds and release binaries bundle HDF5, including gzip/deflate and LZF, so no system HDF5 installation is needed. One series is read per session; multi-segment stitching is not supported.

  • Timestamps with float64 spacing greater than 0.01 samples are refused; if sampling was regular, rewrite the series with starting_time and rate.
  • With per-sample timestamps, each spike must map to a sample inside the series whose recorded timestamp is nearest to the spike time (ties are allowed). Sorrel refuses the file if the inferred grid disagrees.
  • The selected clock (starting_time with its rate, or timestamps) and /units/id, /units/spike_times, and /units/spike_times_index must be stored in their respective opened files or stores. For HDF5, every path component must be a hard link; virtual datasets and external raw storage are refused. Open the file holding the data directly, or pass the recording file via --dat.

Zarr. sorrel open session.nwb.zarr reads local NWB-Zarr v2 directories written by NWBZarrIO. Arrays must use C order and a defined fill value. Supported compressors are Blosc (default LZ4), zlib and gzip; uncompressed chunks are also supported. Sorrel refuses filters other than variable-length string encodings and the JSON encoding used for cached NWB specifications. If .zmetadata is present, it must match the individual metadata files. The zarr feature is on by default in sorrel. --dat can pair an HDF5 file with a Zarr store in either direction when both features are built. The same exact clock rules apply: Zarr clock attributes are finite JSON numbers read as float64, and clock arrays must use little-endian <f4 or <f8. External links and references are not followed; even same-store zarr_link aliases are refused for the clock and spike-mapping columns, like HDF5 soft links. Pickled columns are not decoded. Journals live next to the store. Its seal hashes metadata contents and the paths, sizes and modification times of chunk files, without reading trace chunks at open. An edit that deliberately preserves chunk size and mtime is not detected.

The test fixtures in release/fixtures/nwb/ are written by PyNWB and hdmf-zarr (generate.py pins both versions).

DANDI streaming

# This units-only example needs an explicit sample grid; it has no recording clock.
sorrel open --sample-rate 1000 'dandi://dandi/000006@0.220126.1855/sub-anm369962/sub-anm369962_ses-20170316.nwb'
sorrel describe --sample-rate 1000 'https://api.dandiarchive.org/api/assets/d97954f2-6d80-4dda-9ecf-89c7c10fed0b/download/'

Use dandi://dandi/<dandiset>[@<version>]/<exact asset path>. If you omit the version, Sorrel selects the latest published version, or draft if there is none. Prefer an explicit version for reproducibility. For embargoed data, set DANDI_API_KEY in the Sorrel process that opens the session (including an already-running GUI if it receives sorrel open). The key is used only for requests to the DANDI API, not to storage. Library consumers should cap ureq, ureq_proto, and rustls logging at warn or turn it off to keep signed URLs out of logs.

Streaming is read-only. Sorrel loads metadata and sorting data, then fetches trace windows on demand. Direct HTTPS HDF5 URLs must support range GETs and provide a strong ETag. For Zarr, use a DANDI locator or DANDI API asset download URL: a bare storage prefix doesn’t provide the required object list. The same NWBs and series that local readers refuse are refused remotely. Default builds and release binaries include DANDI streaming.

Sessions with DANDI inputs always open fresh without reusing a tab or session host. A session can’t combine two distinct draft assets; this also applies to DANDI asset-ID download URLs without a version. If a running session owns the journal, stop it or pass a different --journal.

The default journal and save directory is local, under the Sorrel user data directory ($XDG_DATA_HOME/sorrel or ~/.local/share/sorrel on Linux), in dandi/<dandiset>/<version>/<path hash>/. Direct HTTPS URLs are stored under dandi/https/<URL hash>/, without the signed query. Use --journal or the command’s --out to choose a different location. export-phy, qc, and report default to this directory for remote sessions. An asset whose ETags or sizes have changed does not match the old journal seal.

Limits: As in any local session, local files are fingerprinted by name, size, and modification time; a replacement with the same name, size, and modification time is not detected.

Writing curated units to NWB

sorrel.nwb.add_units_to_nwbfile writes a curated session (phy directory or SortingAnalyzer folder) into an NWBFile as its Units table. It needs PyNWB: pip install "sorrel-ephys[nwb]".

from datetime import datetime, timezone
from pynwb import NWBFile, NWBHDF5IO
from sorrel.nwb import add_units_to_nwbfile

nwbfile = NWBFile("session", "id-1", datetime(2026, 1, 1, tzinfo=timezone.utc))
add_units_to_nwbfile("my_run/phy", nwbfile, starting_time=0.0)
with NWBHDF5IO("session.nwb", "w") as io:
    io.write(nwbfile)

Each cluster that still has spikes gets one row. The row id is the backend’s integer unit id, the one curation.json uses, with one exception: SpikeInterface gives the spikes a split leaves behind a fresh id, while Sorrel and this table keep the parent’s id (likewise a single-source merge into an emptied unit keeps the source’s id in SpikeInterface). When a SortingAnalyzer’s ids are strings that are not distinct integers ("unit_a", "007" beside "7"), rows are numbered densely and a unit_name column holds SpikeInterface’s ids. The columns are:

columncontent
spike_timesseconds, see the timing contract below
qualitygood, mua, noise or unsorted
originAuto[<sorter>], or Sorrel[<method>] for a unit a split created
parent_unit_idsragged: the unit a split came from, or the units merged into this one
tagsragged: Sorrel’s tags (src:*, review:*, split, tuned)
QC metricsevery cluster_qc.tsv column that is not NaN for all units, with its units

A parent id can be missing from the table when that unit has no spikes left, e.g. a unit merged into another. That is why the column holds plain ids and not a DynamicTableRegion.

Timing contract. spike_times = sample_index / sample_rate + starting_time. sample_index counts from the first sample of the recording the sort ran on. sample_rate is the exact rate from params.py or recording.json, not Sorrel’s single-precision copy. Units.resolution is 1 / sample_rate. Pass starting_time (seconds) when that recording does not start at the NWB session start. The recording’s ElectricalSeries needs the same offset. Multi-segment SortingAnalyzers are rejected: their sample indices restart per segment.

Provenance. The table’s description records the Sorrel version, the sorter, the journal’s xxh3 hash, whether the saved state is sealed, and the edits on the applied path counted by actor (human, agent, algo, remote) and by method (manual, algo, llm). NWBFile.was_generated_by gets ("sorrel-ephys", <version>). NWB has no core slot for curation provenance. The other options were each worse:

  • a one-row DynamicTable trips NWB Inspector’s check_single_row;
  • JSON in a column trips check_table_values_for_dict;
  • LabMetaData needs an NDX extension;
  • the schema says scratch data “is not intended for sharing”.

The function refuses an NWBFile that already has a units table. It does not write traces, the electrodes table or waveforms. Use the recording’s own NeuroConv interface for those.

Native export

Sorrel exports the same Units table to local HDF5 NWB without Python. The command is built by default on trunk and requires the hdf5 feature:

sorrel export-nwb my_run/phy --out curated.nwb \
  --identifier my-run --session-description 'Curated spike sorting' \
  --session-start-time '2026-01-01T10:00:00+00:00'

New files use NWB 2.11.0 and never overwrite an existing file. The three metadata flags are required for non-NWB inputs. For HDF5 NWB and NWB-Zarr inputs, local or streamed, Sorrel copies them and the timestamps reference time from the source. The output contains the Units table and, when available, probe-relative electrode geometry, but no traces, waveforms or subject metadata. For DANDI, add real subject metadata or export into an NWB recording that already has it.

Pass --starting-time SECONDS to set the first sample’s time on the file’s NWB time axis. By default, export uses the rate and offset Sorrel used to open the session: from the selected ElectricalSeries (including regular timestamps or a paired raw file via --dat), or from the Units resolution or --sample-rate when there is no series. Reopening a Units-only export uses a zero offset for its relative sample indices; pair the raw NWB with --dat to recover the raw series’ time base or to reopen a file with negative spike times. If the series and Units clocks map spikes to different samples, reopen with --sample-rate set to the exact Units clock listed in the error. The Units clock is recovered from the written resolution and may differ by one ULP from the export rate. Export checks that both rates map each written spike back to its original sample. Unlike export-phy, export-nwb does not need channels: if no electrode geometry is available, the new file contains Units but no electrodes table.

sorrel export-nwb my_run/phy --into recording.nwb --starting-time 0.5

--into adds root /units to an existing local HDF5 NWB file and refuses to replace an existing /units table. When the NWB source and destination have different timestamps_reference_time values, pass --starting-time explicitly on the destination’s time axis; Sorrel does not rebase the times automatically. If the destination’s default ElectricalSeries has a rate more than one part per million from the exported Units clock, append refuses rather than writing a clock Sorrel would ignore on reopen. Use --out for a separate Units file instead. Append needs space for a sibling copy of the entire destination and replaces the original only after a successful write. Do not edit the destination concurrently.

NeuroConv

sorrel.neuroconv.SorrelSortingInterface wraps the same function as a NeuroConv data interface (pip install "sorrel-ephys[neuroconv]"), so a -to-nwb converter can put Sorrel’s curated units next to its recording interfaces:

from neuroconv import ConverterPipe
from neuroconv.datainterfaces import SpikeGLXRecordingInterface
from sorrel.neuroconv import SorrelSortingInterface

sorting = SorrelSortingInterface(folder_path="my_run/phy")
sorting.set_aligned_starting_time(0.0)  # offset of the sorted recording
converter = ConverterPipe(data_interfaces={
    "recording": SpikeGLXRecordingInterface(file_path="run_g0_t0.imec0.ap.bin"),
    "sorting": sorting,
})

add_to_nwbfile takes units_description, which goes in front of the provenance summary. Opening the folder takes the curation journal’s writer lock, so close the Sorrel window on it first.

The interface does not go through NeuroConv’s add_sorting_to_nwbfile, for three reasons:

  • that writer concatenates the segments of a multi-segment sorting into one spike train, where Sorrel refuses to guess;
  • it renumbers rows 0..N-1 and moves the sorter’s ids into unit_name, where parent_unit_ids and curation.json need the ids themselves;
  • it would make SpikeInterface a dependency of the NWB path.

The interface does not link units to electrodes.

Legacy MATLAB rez.mat

sorrel open rez.mat --dat path/to/recording.bin

This reader supports MATLAB v7.3 (HDF5) rez.mat and rez2.mat files from Kilosort 2, 2.5, and 3. It reads sample and template IDs from the first two columns of rez/st3 and groups spikes by template, not by any later cluster assignments. It reads rez/ops/fs and rez/ops/Nchan for recording parameters, rez/xc and rez/yc for channel positions, and rez/ops/fbinary or rez/ops/fproc for the binary path (--dat overrides it).

The reader is included by default. To select it explicitly, use --backend rez; --backend ks4-rez is an older spelling for the same reader. If the MAT file is not v7.3 or you built without HDF5, use a Phy export of the legacy run instead.

Kilosort 4 writes Phy-format .npy arrays directly. Open the results directory with Sorrel’s Phy reader (--backend kilosort), not the MAT file reader.

Python (Jupyter)

Install the sorrel Python package from the wheel attached to each GitHub release (see Installation); it bundles the GUI binary. maturin develop from crates/sorrel-py/ builds it from source. The package has two layers.

In-process, no window — the notebook and pipeline API. It opens the same journal the GUI uses, so edits made here show up in the GUI and vice versa:

import sorrel
s = sorrel.Session.open("my_run/phy")        # or a SortingAnalyzer binary_folder
s.qc()                                       # list of dicts, cluster_qc.tsv columns
s.suggest()                                  # {"merges": [...], "splits": [...]}
s.set_label(3, "good"); s.merge([4, 5], 6)   # journaled, undoable
new = s.split(0, [1, 7, 9])                  # local spike indices → new cluster id
s.save()                                     # phy files + curation.json

GUI launcher — subprocesses the sorrel binary (egui needs the main thread, which a Jupyter kernel cannot give it):

sorrel.open(recording, sorting)         # builds a SortingAnalyzer, saves it as binary_folder
result_dir = sorrel.open_analyzer(sorting_analyzer)

The directory it returns keeps the curation journal and, once you save in the GUI, curation.json; round-trip into SpikeInterface with sc.apply_curation(analyzer, sorrel.read_curation(result_dir)). The temporary directory is kept by default so that file survives; pass keep_temp=False to discard it.

Backend detection

sorrel open <DIR> walks a small detector list:

  1. If spike_times.npy + spike_clusters.npy are present → phy/Kilosort.
  2. Else if recording.json + sorting/ are present → SortingAnalyzer.
  3. Else fail with a helpful message.

Override with --backend kilosort|sorting-analyzer.

Views

Every view is a dockable tile. The default layout puts three tab groups side by side — shape (Waveforms, Templates, Probe, Summary), comparison (CCG, Features, Amplitudes, ISI, Rate, Similar) and assessment (Quality, Suggest, Stats, Raster, Drift, Contam·time); PSTH sits in the comparison group — above a full-width Trace, so a waveform overlay, a correlogram grid and a feature scatter of the same selection are visible at once, as in phy.

  • Drag a tab title to move it into another group, or to the edge of a tile to split it. Drag the borders to resize.
  • × on a tab closes the view; the + at the right of a tab bar or the View menu in the top bar reopens it. View → Reset layout restores the default.
  • Every view can be maximized or popped out: the two buttons at the right of a tab bar act on its active tab. Maximize fills the view area with that one view (header Restore button, Esc or Ctrl+Shift+M brings the layout back); pop-out moves the view to its own native window, leaving “In its own window” and a Bring back button in its tile, and closing that window brings the view back. F11 toggles full screen in either window. The :max and :pop snippets do the same for the view under the pointer. A popped-out window handles the same keyboard shortcuts while it has focus (K splits, Esc clears a lasso and never closes it).
  • The layout, table sort/filter, trace settings and last selected cluster are saved per dataset in <dataset>/.sorrel/ui.json and restored on the next open.

The cluster table stays in the left panel. Clusters in the selection are coloured by their position in it (first = blue, second = orange, …), and every view uses the same colour for the same cluster.

Spike counts. The table’s n is the total current spike membership of that cluster, not the number of points or waveforms drawn. A merge adds the selected clusters’ counts; a split redistributes them. Waveforms separately reports loading and valid-snippet counts, because spikes at recording edges or with missing raw data may not have a complete waveform.

ViewWhat it shows
TraceRaw recording for a configurable window, one row per channel, with channel numbers, a time axis and a tick on each selected cluster’s peak channel for every spike in view. LTTB downsampling with optional CMR + high-pass. Drag or wheel to pan, Ctrl-wheel to zoom.
Trace imagephy v2.1’s TraceImageView: the trace window as an image (blue negative, red positive), following the Trace window, filters and origin.
Spike dataphy’s Spike*Views: any spike_<name>.npy against time (1-D) or as x vs y (2-D), Ctrl-click lasso and K to split. A closed lasso is the app-wide spike brush (brushed spikes draw in ink in every spike view); hovering a point (within 6 px) highlights it everywhere; Shift-drag along a 1-D attribute sets the time range.
SummarySelection summary: cluster ids, spike counts and labels.
WaveformsEvery valid spike’s waveform plus the full-set mean per selected cluster on four shared channels by default. Hover and press M to toggle mean-only versus all-spike overlays; each press switches back, without clicking the pane. Loading runs in cancellable background batches and shows progress and valid/total spike counts, never labeling a 100-spike sample as “all.” All selected clusters use the same channel boxes; selecting comparison clusters never adds channels. A four-channel tetrode shows all four channels. Larger recordings use the primary cluster’s peak and nearest channels in its channel group; ⚙ → channels explicitly allows more. Uses probe positions when available, otherwise a simple channel grid—not a peak-only fallback. Spikes, mean and template modes share the same channels. Snippets follow Trace HP/CMR. Shift+click a box toggles it in the Features channel set; Ctrl+click / Ctrl+right-click makes it A / B. Features’ lassoed spikes and optional PC shapes remain linked.
Templatesphy’s TemplateView: every cluster’s template on its peak channel, in table order, the selection outlined; click selects, Ctrl/Shift-click adds.
Amplitudesphy’s AmplitudeView: template, feature or raw amplitude over time (A cycles), grey background spikes on the peak channel, a per-cluster histogram, Ctrl-click lasso and Alt-right-drag threshold, K splits; Alt-click seeks the trace. The lasso or threshold is the spike brush (ink points everywhere); hovering a point (within 6 px) rings it and draws its time line in Raster, Rate, Drift and Trace; Shift-drag sets a time range (spikes outside fade, or hide with only in range), Shift-click clears it.
ISIInter-spike interval histogram per cluster. Click the shaded refractory band or a cluster’s violation chip to brush every spike that is part of a violating pair; hovering shows “N spikes in M violating pairs”. With a Features/k-means lasso brush on one selected cluster, the pane overlays that cluster’s split what-if (inside dashed, outside dotted, with each part’s refractory share), Quality adds green/red “if split · inside / outside” rows with composite deltas, and Waveforms draws the two means dashed and dotted. Hovering a Similar/Suggest row adds a grey dashed ghost mean in Waveforms and a grey “cN (ghost)” row and column in CCG.
CCGAuto- and cross-correlogram grid across the selected clusters (memoised per selection).
FeaturesPhy’s full 4×4 grid of PC1/PC2 on channels A and B, with time on the diagonal and grey background spikes. All 16 projections are visible together at narrow, normal and maximized sizes; the grid fits the pane’s width and height. There is no projection navigator or replacement single-cell view. The channel set (default the selection’s best four) is edited from Waveforms or Probe: Shift+click toggles a channel, Ctrl+click / Ctrl+right-click sets A / B; C fixes A/B. Uses sorter PC features when present, otherwise PCs fitted on raw snippets. Ctrl+click or Ctrl+drag a lasso; K splits and Esc cancels. K-means can lasso a part and show collision evidence directly on the projections. Secondary controls and alternatives do not interrupt the projection matrix. The 2D|3D toggle explicitly switches to the inspection-only 3D scene. A lasso or k-means part becomes the linked spike brush, Alt+click seeks Trace, and Shift+drag a time cell sets the time range.
RasterEvery spike of every cluster, time on x, cluster row on y. Selected rows are highlighted and the current trace window is outlined; click to seek. Brushed spikes are full-height ink ticks; Shift-drag sets the time range, drawn as a band.
RateFiring rate over the recording, in Hz, one line per selected cluster; bin count (:frn, :frb) and time unit (s, min, h) in the header. Shift-drag sets the time range, Shift-click clears it; the hovered spike’s time is a vertical line.
ProbeChannel layout from probe geometry with a ring on each selected cluster’s peak channel. It is also the Features channel picker: set members get a selection ring (A and B a badge), the focused plot’s channels a strong ring; Shift+click a site toggles it in the set, Ctrl+click makes it A, Ctrl+right-click B.
SimilarClusters whose template is most similar to the first selected one. Click a row to compare, Cmd/Ctrl-click to add it to the selection. Hovering a row ghosts that cluster in the other views (as a merge into the first selected cluster) and shows the merge preview delta (composite, contamination) in a tooltip; Suggest merge rows do the same. Hovering a History row ghosts the clusters before that edit in Features 3D.
StatsHistograms of spike count, mean amplitude and ISI violations across all clusters.
QualityComposite quality breakdown (refractory, presence, coverage, SNR, completeness, stability, isolation). Computed on a background thread; a spinner shows while it runs.
SuggestRanked merge and split suggestions with predicted outcomes. Ranked on a background thread; curation stays responsive while it runs.
DriftSpike depth (µm, Kilosort 4 spike_positions.npy y, else PC-weighted centre of mass, else template peak) over time with a regression line per cluster; amplitude over time when the backend has no depth estimate. Brushed spikes draw in ink, the hovered one is ringed; Shift-drag sets the time range (outside points fade).
Contam·timeSliding refractory contamination over the recording.
Tmpl featuresphy’s TemplateFeatureView: with two clusters selected, each spike projected on both clusters’ templates (template_features.npy), Ctrl-click lasso, K splits; a closed lasso is the spike brush.
Scatterphy v2.1’s ClusterScatterView: one point per cluster, x / y / size from amp, depth, fr, n_spikes or ch; click selects, Shift-click adds, Ctrl-click lasso selects.
PSTHEvent-aligned firing rate per selected cluster plus a per-trial raster of the first one. Needs events.csv (time,label, seconds) or events.npy next to the dataset, an NWB file’s /intervals/trials table, or --events FILE; pick the label, pre/post window and bins in the toolbar.

Feature navigation. Plain drag pans the whole 4×4 projection grid, and the wheel zooms it like a single image around the pointer: the projection squares, the gaps between them and their captions scale together. A modest zoom enlarges the visible projections so they can be inspected, and panning brings an enlarged square fully into view. Double-click resets the zoom and pan so all sixteen projections fit the pane again. Ctrl-wheel still scales PC features and Alt-wheel changes marker size. Plain-wheel zoom and drag do not change axis ranges, the lasso polygon, spike brush or cluster data, or relayout the pane, reset the channel set or change the default grid; the toolbar and alternatives strip stay fixed. Esc abandons the lasso and a pending cut, clearing its linked spike highlights without changing the clusters; Undo reverses a completed split.

Lasso tracking. With live tracking unchecked (the default), a Ctrl-click polygon stays a draft between clicks: only its outline changes, not the spike selection or linked previews. Release Ctrl to finish it, then press K to cut; K also finishes the current valid polygon directly. Node drags settle on mouse-up. Large hit-tests and highlight-buffer builds run off the UI thread, and a cut does not wait for a preview to finish. Esc cancels without editing.

Refractory-period settings

Set the windows in Settings → Refractory-period settings, or pass these flags when opening a recording. GUI settings are saved as defaults for new sessions, and each launch flag overrides its saved value for that session. Saving Settings applies only the fields you changed to open sessions, so a flag or MCP value for any other field stays in force.

ParameterCLI flagDefaultSource
Fixed (fixed_ms)--refractory-ms1.5 msSpikeInterface compute_isi_violations
Sweep minimum (sweep_min_ms, exclusive)--rp-min-ms0.5 msSpikeInterface exclude_ref_period_below_ms; IBL slidingRP rp_reject
Sweep maximum (sweep_max_ms, inclusive)--rp-max-ms10 msSpikeInterface max_ref_period_ms; IBL slidingRP upper limit
Sweep step (sweep_step_ms)--rp-step-ms0.25 msSpikeInterface bin_size_ms

The first tested window is minimum + step: the default grid runs from 0.75 to 10 ms in 38 windows. For Bombcell’s 1 ms first window, set the exclusive minimum to 0.75 ms and keep the default step. The legacy rp_contamination and rp_estimate_ms columns still report the minimum of a linearised Hill estimate and its window. That estimate can be biased low when short windows have no violations.

The MCP tool refractory returns the current and default parameters without arguments. Supply any of the four fields to update the live session, including its attached GUI, without changing the saved GUI defaults. metrics includes the settings it used under refractory.

Refractory evidence in QC

sorrel qc, MCP metrics, and rules expose these columns. In the GUI, hover over a cluster’s coloured badge in the ISI view to see both results.

ColumnMeaning
srp_contaminationNominal upper limit: the smallest contamination fraction the sliding-RP test confirms at confidence strictly above 90%, under the model below.
srp_rp_msWindow (ms) of highest confidence at the reported fraction, IBL’s estimate of the unit’s refractory period.
rpv_post_meanPosterior mean contamination fraction at the session’s fixed window (not the SRP window), conditional on the model below.
rpv_post_lo95Lower bound of the shortest 95% credible interval.
rpv_post_hi95Upper bound of the shortest 95% credible interval.

Both metrics count all spike pairs with a positive lag strictly inside the window, not just consecutive ISIs. Exact duplicates (zero lag) are not counted, so they need their own check. Windows are rounded to sample edges, and a window of e samples is charged e − 1 samples of exposure, which is what integer lags 1 to e − 1 can observe. IBL charges the full window; the difference is small at 30 kHz but matters on coarse timestamps, where IBL’s charge would understate contamination. Windows shorter than two samples or at least half the recording long are skipped. The sliding-RP test (Roth et al., 2026) uses a fixed 0.5–35% contamination grid in 0.5 percentage-point steps, with no correction for testing multiple windows. Sorrel uses the configured sweep above, rather than IBL’s every sample bin above 0.5 ms. The SRP columns are unavailable if no tested fraction reaches confidence; this does not distinguish contamination above 35% from too few spikes to tell.

The posterior uses a uniform Beta(1,1) prior on the contamination fraction and a Poisson likelihood with the same expected-violation model as the sliding test (Llobet et al., 2022). Both results assume stationary spike rates, a window no longer than the neuron’s true refractory period, and diffuse contamination: contaminating spikes arrive as a Poisson process, so they also violate each other. A unit whose contamination comes from one other refractory neuron produces fewer violations than this model expects, so both results understate it. If the posterior sits near 100% while the sliding test passes at a shorter window, the fixed window is probably longer than this unit’s refractory period. The interval is the shortest 95% credible interval, so with no violations it starts at 0. An interval from near 0 to high values means too little data to tell; one bounded well above 0 can still be wide, because the expected violations flatten as contamination nears 100%. The flat prior pulls the mean of a sparse unit towards 50%, so read the interval, not the mean alone. A unit firing in bursts, or drifting, can show more violations than any contamination explains, which pins the posterior near 100%. With fewer than two spikes or invalid recording duration or sample rate, both results are unavailable (NaN in Rust, null in JSON and blank in TSV).

For example, this rules.toml policy labels a unit mua only when the evidence says contamination exceeds 10%, that is when the posterior’s lower bound does. To find units that are merely uncertain (a wide interval, as with very few spikes), run rules_eval with rpv_post_lo95 <= 0.1 and rpv_post_hi95 > 0.1 together (all = [...]) and review them instead of relabelling.

Two traps when writing such rules:

  • A rule never matches a missing (NaN) value. With default = "good", a rule srp_contamination > 0.1 labels every unit with a missing srp_contamination good, including heavily contaminated ones. Write it the other way round: default = "mua" with srp_contamination <= 0.1 labelling good.
  • The posterior uses the fixed window. If it is longer than a unit’s refractory period, as 1.5 ms can be for fast-spiking interneurons, a clean unit shows high contamination there while srp_contamination passes at a shorter window. Lower Fixed for such recordings, or check srp_contamination before acting on the posterior.
[[rule]]
name = "refractory contamination"
metric = "rpv_post_lo95"
op = ">"
value = 0.1
label = "mua"

Stable epochs

Thin lines in the Amplitudes view mark fitted changes for the selected units, using their stored sorter amplitudes regardless of the displayed amplitude type. The lines are hidden when Ctrl+R reorders spike times. probe epochs C lists each interval in seconds with its spike count, firing rate (Hz), and signed mean amplitude. QC exports, MCP metrics, and rules expose these summaries:

ColumnMeaning
n_epochsNumber of fitted segments, including 1 if no change was found.
epoch_amp_ratioSmallest divided by largest magnitude of the segment mean amplitudes.
epoch_rate_ratioLowest divided by highest segment firing rate; 1 for a single segment.

The fit divides the recording into 100 equal bins and finds the exact best piecewise-constant fit, with segments at least 5 bins long. Each bin gives two series: its spike count and the mean stored amplitude of its spikes. The count costs its Poisson deviance from the segment’s rate, divided by a dispersion measured from differences between neighbouring bins (never below the Poisson value). The amplitude costs its squared distance from the segment’s level, weighted by spike count and scaled by a noise level from robust differences between neighbouring bins; it widens when neighbouring bins are correlated, as when amplitudes drift on a timescale close to the bin width. Taking the noise from the data covers bursty firing and rounded amplitudes. Each series’s cost in a bin is capped at 9 (3 noise units squared; up to 18 when both rate and amplitude are fitted), after the biweight loss of Fearnhead & Rigaill (2019), JASA 114:169–183, so a burst or a stray bin cannot buy a boundary alone. Each fitted level costs ln 100 (a rate per segment, plus an amplitude per nonempty segment when fitted) and each boundary 2 ln 91 for the search over its position.

Missing or invalid amplitudes, or fewer than 21 nonempty bins, give a rate-only fit, and silent segments fit no amplitude. probe epochs marks each interval fit=rate or fit=rate+amp, and still shows descriptive means when amplitudes are valid but not fitted. Because a boundary in a fit=rate+amp unit also pays for an amplitude level, such units need a larger rate change to split; compare n_epochs and epoch_rate_ratio between units with the same fit. The amplitude ratio is unavailable if amplitudes were not fitted, any segment is silent, or the largest mean magnitude is zero. A single segment with a fitted nonzero mean has ratio 1. All three summaries are unavailable with fewer than 10 spikes, recordings shorter than 20 s (200 ms bins), or invalid recording timing (NaN in Rust, null in JSON, blank in TSV).

Boundaries are change points of a step model, not transition times. A gradual drift becomes a staircase whose edges fall wherever the fit is cheapest, and the ratios compare segment means, so they understate the end-to-end change. In simulations, a linear 100 → 55 amplitude ramp over the recording (5 Hz, SD 10) gave 4 to 5 segments and a median epoch_amp_ratio of 0.63. Slow firing-rate modulation splits too: a ±40% rate oscillation with a 50 s period split 70% of 100 s recordings. Some steady units also split: bursts whose spike amplitudes shrink within the burst (23% of simulated units), and amplitude fluctuations that last several bins, which are likelier at low firing rates or in short recordings (a spike-to-spike amplitude correlation of 0.75 split 14–19% of units at 1–2 Hz over 100 s, or at 5 Hz over 20 s).

A rate-only change is not by itself evidence of dropout: behaviour can change firing rates. For example, try epoch_amp_ratio < 0.6 as a review rule in rules_eval, then inspect where the change occurred. To split at a boundary, copy the reported time into split C by=time at=T in probe; probe epochs suggests this only when some boundary has spikes on both sides. The handle moves spikes at or after the boundary, matching the fit’s half-open intervals. Applying it is journaled and undoable; the fit itself makes no edits.

Cross-talk (Sorrel extra). The views share four kinds of state, so a pick in one shows in all the others:

  • Spike brush. One set of spikes at a time, and the last writer wins. It comes from a Features lasso or k-means part, an Amplitudes lasso or threshold, a Spike data or Tmpl features lasso, or the ISI refractory band. Every spike view draws the brushed spikes in brush ink: white in dark, near-black in light. With a lasso or k-means brush, ISI, Waveforms and Quality also preview the split: the inside part dashed, the outside part dotted, and “if split” rows with the change in composite score.
  • Time range. Shift-drag along a time axis (Amplitudes, Rate, Drift, Raster, Features’ time cells). Spikes outside it fade, or hide with only in range.
  • Hovered spike. The spike under the pointer in Features, Amplitudes or Spike data, or the one clicked in Trace. It is ringed in the point views, marked with a line in the time views, and drawn bold in Waveforms. Alt-click seeks Trace to it.
  • Ghosts. Hovering a Similar or Suggest row shows that cluster as a grey ghost (points, dashed mean, CCG row, 3D hull) with the merge’s quality change. Hovering a History row shows the clusters as they were before that edit, as dashed hulls in Features 3D.

The brush and the time range appear as chips in the top bar. Click a chip’s × or press Esc to clear them. A curation edit drops the brush, because its spike indices no longer mean the same spikes.

Features 3D (Sorrel extra; the 3D toggle in the Features header) shows the same points in three dimensions of the channel set (time, then PC1 and PC2 on every channel: 17 dimensions and 680 triples for eight channels) behind an orbit camera. It is for inspection only: lasso, k-means and split stay in the 2D grid. Every triple of the set is ranked by how well it separates the selected clusters (mean simplified silhouette on at most 5000 points, every axis scaled to 0–1); with one cluster selected the k-means parts are the labels, and with no parts the total variance. A wide pane lists the top 20 in a sidebar with a score bar and a show all N toggle that expands the list into a scroll area; a narrow one offers the top 20 in a combo box. Your pick is remembered as its three axes, so it survives re-ranking, and gives way to the best triple when the channel set changes and one of its axes is gone. The focused 2D plot is pinned when you enter 3D (a “pinned · x × y ×” chip under the toolbar, following the focused cell): only the triples holding both its axes are listed, as “+ third axis” rows, and the best of them is the default. × on the chip lists every triple; the “pin x × y” button pins again. The channels of the triple on show are highlighted in Waveforms. Each selected cluster gets a convex hull of the 95% of its points nearest the median: translucent and filled for sorter-made (Auto) units, wireframe for Sorrel-made ones. A cluster made by a split also shows its parent before the split as a dashed grey hull (the union of the siblings the split produced; merged units show only their current hull). A closed lasso is extruded along the third axis as a prism when its two dimensions are both in the triple, otherwise a note says which triple shows it. The k-means part on show gets a dotted hull in the link colour, and its points turn white (dark theme) or black (light). The legend names every cluster with its origin (Auto[kilosort4], Sorrel[Manual], …) and each overlay. Drag orbits, Shift-drag (or middle-drag) pans, the wheel zooms and double-click resets the camera.

Cross-talk in 3D: the app-wide spike brush (a Features lasso, k-means part, ISI violators, …) draws its spikes in brush ink (white in dark, near-black in light), a little bigger and on top; the time brush fades the spikes outside its range, or hides them with “only in range”. The pointer picks the nearest spike within 6 px, which rings it in the accent colour here and in every other spike view (and the ring follows a spike hovered elsewhere). Hovering a Similar or Suggest row draws that cluster as a grey dashed hull (“ghost cN”); hovering a History row draws each cluster the edit changed as it was before it (dashed, “before #n”, restricted to the spikes shown). The Features colour mode (time, depth) colours the points the same way as the 2D grid. With spike depths available (the Drift map’s source) the space family joins the axes: depth takes part in the ranked triples like any PC, and so does x when the Kilosort 4 directory has spike_positions.npy (which also becomes the Drift map’s depth, y being the depth).

The Trace toolbar offers per shank CMR when the probe has more than one shank (channel_shanks.npy), referencing each shank by its own median.

Plots follow the egui theme, so light mode renders light plot backgrounds.

Keyboard & Mouse

Sorrel uses phy’s TemplateGUI shortcuts, so phy muscle memory carries over. Press h (or ?, F1, or the ? button in the top bar) for this list as an overlay. The overlay is generated from the same keymap table the app dispatches from. The tables below describe the defaults; Help shows your active bindings. phy parity tracks what is still missing.

Letter keys below are unshifted unless Shift is explicitly shown. On macOS, use Cmd for the primary Ctrl shortcuts, except the physical Ctrl+Tab dataset-tab navigation noted below.

Configure shortcuts and settings

Open Settings from the launcher, dataset tab bar or top bar. Under Keyboard shortcuts, search an action, remove a binding with its × button, or choose Add shortcut and press the new chord. Multiple alternatives are supported. Reset restores one action; Restore all shortcut defaults restores every action. Conflicting shortcuts in overlapping scopes prevent saving. Waveforms and CCG shortcuts apply only while their pane is hovered.

Save settings applies changes immediately to every tab and pop-out and writes ~/.sorrel/settings.toml (%USERPROFILE%\.sorrel\settings.toml on Windows). This file also stores the theme and recent datasets. Set SORREL_CONFIG_DIR to use another settings directory. It is separate from the host registry/runtime directory (SORREL_USER_DIR). Recording-specific layout, selection and view state remain in <dataset>/.sorrel/ui.json.

You can also edit the TOML while Sorrel is closed:

version = 1

[appearance]
theme = "system" # system, dark or light

[keybindings]
"curation.split" = ["F8"]
"curation.merge" = ["G"]
"app.open_dataset" = ["Primary+O"]
"waveforms.mean" = [] # explicitly unbound

Missing action entries inherit their defaults; arrays replace all bindings for that action. Primary means Ctrl on Windows/Linux and Cmd on macOS; Ctrl means the physical Control key. Use named keys such as Plus, ArrowDown and PageUp. Settings lists the stable action IDs on hover. Invalid settings cause a visible warning and are never silently overwritten. Mouse/wheel gestures and native text-editing shortcuts are unchanged.

“Best” clusters are the ones picked in the cluster table; “similar” clusters are picked in the Similar pane or stepped through with Space. Views show the best clusters first, then the similar ones.

Curation

KeyAction
GMerge the selection into the first-selected cluster.
KSplit off the spikes inside the Features lasso.
LOpen the snippet bar with :l typed (set a label).
Alt+G / Alt+M / Alt+N / Alt+UMark the cluster-table selection good / MUA / noise / unsorted.
Ctrl+G / M / N / UMove the similar clusters.
Ctrl+Alt+G / M / N / UMove all selected clusters.
Ctrl+ZUndo.
Ctrl+Shift+Z / Ctrl+YRedo.
Ctrl+SSave curated state to disk (see Saving).
Shift+Ctrl+KSplit the selection back into its original templates.
VMerge mode: stage the selection, add similar candidates (Space, clicks), G merges all, V cancels.

A move is journaled as a single entry, so one undo reverts it. Afterwards the wizard advances as phy’s does. Moving the best clusters selects the next table row. Moving a similar cluster steps to the next similar one. G requires at least two selected clusters and combines their actual spike memberships into the first-selected cluster; it is not just a visual group. One Undo restores all of the merged memberships.

KeyAction
↓ / ↑Next / previous best cluster in table order (sort + filter respected).
Home / EndFirst / last best cluster.
Space / Shift+SpaceNext / previous similar cluster; noise and MUA are skipped.
Ctrl+SpaceSelect the first 15 similar clusters.
BackspaceUnselect the similar clusters.
Ctrl+Alt+SpaceReset the wizard to the first cluster.
Alt+← / Alt+→Pan the trace window back / forward by one window.
Alt+Home / Alt+EndJump the trace to the start / end of the recording.
Alt++ / Alt+-Narrow / widen the trace window.
Alt+PgDn / Alt+PgUpCentre the trace on the selection’s next / previous spike.
Alt+TGo to a time (opens :tg).
Alt+O / Alt+S / Alt+LTrace: channel 0 at the bottom / mark every cluster’s spikes / channel labels.
Ctrl+Alt+↑ / Ctrl+Alt+↓Trace gain up / down.

Views and snippets

KeyAction
CFeatures: fix the current channels, or follow the selection again.
A / Shift+AAmplitudes: next / previous type (template, feature, raw, template feature).
Ctrl+RTime axes use spike_reorder.npy (when present).
:Snippet bar. Enter runs the snippet, Esc closes it.
H / ? / F1Toggle the help overlay.
Ctrl+QQuit (asks first when there is unsaved curation).
Ctrl+O / Ctrl+WOpen a dataset / close the active dataset tab.
Ctrl+Tab / Ctrl+Shift+TabNext / previous dataset tab (physical Ctrl on macOS too).
Ctrl+CommaOpen Settings (Cmd+Comma on macOS).
Ctrl+Shift+MMaximize the pane under the pointer over the whole view area, or restore.
F11Full screen for the window the key is pressed in (main or a popped-out one).
EscClose a dialog, the snippet bar or the help, or cancel the lasso and any pending cut without changing the cluster; with nothing else to cancel, restore a maximized pane.

Snippets: :g merge, :k split, :c 3 7 10-12 select, :l name value custom label (:l group good moves the selection), :note text unit note (:note alone clears it), :tg 12.5 trace to 12.5 s, :ts 0.2 200 ms trace window, :max maximize or restore the pane under the pointer (Features if none yet), :pop move that pane to its own window.

Plain-key shortcuts never fire while a text field has focus. Ctrl chords, Esc and F1 always do.

Pane-local defaults

These shortcuts apply only while the pointer is over the pane and no text field has focus. They are configurable in Settings too.

PaneKeyAction
WaveformsW / Shift+WNext / previous waveform mode.
WaveformsM / O / Ctrl+LMean toggle / overlap / channel labels.
WaveformsCtrl+↑ / Ctrl+↓Increase / decrease amplitude scale.
WaveformsCtrl+→ / Ctrl+←Widen / narrow waveform boxes.
WaveformsShift+↑ / Shift+↓Spread / shrink the probe vertically.
WaveformsShift+→ / Shift+←Spread / shrink the probe horizontally.
WaveformsR / Shift+RReset scales.
CCGNToggle uniform normalization.

While hovering Waveforms, each M press switches between the mean alone and individual waveforms from every valid spike, with the same full-set mean overlaid. No click in the pane is needed. Loading counts distinguish available waveforms from the total cluster spike count; text fields and dialogs keep their keyboard input. An explicitly selected sample preview is separate; M always restores the all-spike source, even with older preferences that stored a 100-spike cap.

Undo moves to the previous edit and redo to the branch you visited last. An edit after an undo starts a new branch, and the old one stays in the History pane. The top bar’s Undo/Redo buttons name the command they will revert or re-apply.

After a merge the target cluster is selected; after a split both halves are. Closing the window with unsaved curation asks whether to save first.

Cluster table mouse

GestureAction
Click a rowReplace selection with this cluster.
Cmd/Ctrl-clickToggle this cluster in the selection.
Shift-clickSelect the range of visible rows from the anchor to here.
Click column headerSort by that column; click again to flip.

Selected rows carry a colour swatch; the same colour marks that cluster in every view (first selected = blue, second = orange, …).

Views mouse

WhereGestureAction
Tracedrag / wheelPan in time.
TraceCtrl-wheel / pinchZoom the window around the pointer (1 ms – 5 s).
RasterclickSeek the trace window to that time.
Rasterdrag / wheel / double-clickPan / zoom time and rows around the pointer / reset.
Amplitudes, Rate, Drift, RasterShift-drag along timeSet the time range (a band; spikes outside fade). Shift-click clears it (not in Raster, where it adds a cluster: use Esc or the chip).
Amplitudes, Spike datahover a point (6 px)Highlight that spike in every view: ring in the spike views, a time line in Raster, Rate, Drift and Trace.
Traceclick a spike tickPick that spike (4 px): Features rings it and the pick stays until the next click.
Ratedrag / wheel / double-clickPan / zoom in time (re-binned over what is visible) / reset; :frmin 10, :frmax 600 set the x range in seconds.
TemplatesCtrl-wheel / pinch / double-clickZoom every template box / reset; the wheel scrolls.
WaveformsShift-click a channel boxToggle that channel in the Features channel set.
ProbeShift-click a site; Ctrl-click / Ctrl-right-clickToggle that channel in the Features set; make it A / B.
ISIClick the shaded refractory band / a violation chipBrush both spikes in every pair closer than the fixed refractory window, for all shown clusters / that cluster. Esc clears.
WaveformsCtrl-click / Ctrl-right-click a channel boxMake that channel Features channel A / B (phy select_channel).
FeaturesCtrl-click / Ctrl-dragCtrl-click adds a lasso node in that subplot; Ctrl-drag draws one freehand (simplified to at most 64 nodes on release, replacing the old lasso); Ctrl-right-click or Esc clears; K splits the spikes inside.
FeaturesDrag / double-click / right-click on a lassoOn a closed lasso: drag a node to move it, double-click an edge to insert a node, right-click a node to delete it (never below three). A plain drag elsewhere pans the whole projection grid — squares, gaps and captions together — not the dots within one square.
Featuresk-means button / :kmLasso the smallest k-means part of the first selected cluster (exact members highlighted, a chip per part to switch); auto-run refits as the selection changes. K splits.
FeaturesAlt+click a spike / Shift+drag a time cellAlt+click on a spike (6 px) seeks the Trace to it; elsewhere it picks the amplitude feature. Shift+drag along a time cell sets the time range, Shift+click clears it.
Featureswheel / Ctrl-wheel / Alt-wheel / drag / double-clickZoom the whole 4×4 projection grid like one image around the pointer, scaling squares, gaps and captions together / scale PC features / marker size / pan that canvas / reset the zoom and pan so all 16 projections fit again. Plain wheel and drag do not change data ranges, the lasso, the spike brush or cluster data; the toolbar and alternatives strip stay fixed.
Features 3Ddrag / Shift-drag (or middle-drag) / wheel / double-clickOrbit / pan / zoom / reset the camera; click a triple in the AXES list (or the combo box) to change the axes; the pinned chip holds the focused 2D plot’s pair so only its third axis is chosen, × on it lists every triple. Inspection only: no lasso here, and drags with Ctrl or Alt held are ignored.
Similarclick a rowSelect the primary cluster together with that candidate.
SimilarCmd/Ctrl-click a rowAdd that candidate to the current selection.
Any tabdrag the tab titleMove the view to another group or split; × closes it.
Tab bar+Reopen a closed view in that group.

Journaling guarantee

Every label change, merge, split, undo/redo and History jump is written to the journal before the in-memory session changes. If Sorrel crashes between the journal write and the next event, the replay on next open recovers the exact same state.

Tab menu

Right-click any tab for Freeze on this selection (phy’s auto-update toggle: the pane keeps showing the clusters it had, marked 🔒) and Save screenshot (a PNG of the pane in <dataset>/.sorrel/screenshots/). Shift+wheel over Raster, Scatter or Templates cycles the colour scheme for unselected clusters (also :cf none|cluster|group|depth|fr). Drag pans, the wheel zooms and double-click resets the Amplitudes, Scatter, Tmpl features and Spike data plots.

Saving & QC Export

Sorrel separates two persistence concerns:

  1. The journal — every action goes here, automatically and synchronously, before the in-memory session moves. This is the source of truth for “what edits has the user made.”
  2. Phy artefacts — the canonical files other tools read (spike_clusters.npy, cluster_group.tsv). These are written on demand.

Saving phy artefacts

Cmd/Ctrl-S

Writes the current curated state into the directory the binary was opened with (save_dir):

  • spike_clusters.npy — updated per-spike cluster assignment after any merges and splits.

  • cluster_group.tsv — good / mua / noise / unsorted labels.

  • curation.json — SpikeInterface’s manual-curation document (format_version 2), see below.

The first two are exactly the files spikeinterface.extractors.read_phy() reads back, so a round trip into SpikeInterface or phy works without intermediate steps.

The journal and sorrel_original/

The journal replays onto the sort as it was loaded, never onto the files the last save wrote. Saving keeps the whole history.

For phy / Kilosort directories, the first save that replaces a file copies the original into sorrel_original/. The arrays a rescue rewrites are hard-linked instead. sorrel_original/ROOT lists every file captured this way, including the files that did not exist yet. Sorrel reads those copies on open, so a reopen rebuilds every node of the history. Leave the directory in place.

Each save adds a seal to the journal: the hash of the spike_clusters.npy and cluster_group.tsv it is about to write. The seal is recorded before the files are renamed into place, so a crash at any point leaves files that match the sort as loaded or one of the seals.

Opening checks two things and fails closed when either fails:

  • The original spike_clusters.npy must match the journal. It does not when the sorter was re-run or the file was copied from elsewhere.
  • The current spike_clusters.npy and cluster_group.tsv must be the original or one of sorrel’s saves. Otherwise someone edited them outside sorrel, for example by curating in phy after a sorrel save, and the next sorrel save would overwrite that work.

To curate from the files as they are now, reopen with --discard-journal. It renames the journal to <journal>.<seconds> and sorrel_original/ to sorrel_original.<seconds>. Nothing is deleted. The current files become the new starting point. To keep the journal instead, restore the files it was recorded against.

SortingAnalyzer, NWB and rez.mat sessions reload the original sort on every open, so they need no copies or checks.

Saving an NWB session does not change the input NWB file. To write a Units table from a curated phy or SortingAnalyzer session, use the Python NWB export. The HDF5 reader can reopen those Units tables, alone or paired with a raw NWB file.

curation.json

Every save also writes SpikeInterface’s manual-curation document next to the phy files. It carries the good / mua / noise labels, tags and the origin of every unit. A session that merged or split units also carries the edit history in SpikeInterface’s list form (SequentialCuration), so a SortingAnalyzer round trip is one call:

import sorrel
import spikeinterface.curation as sc
curated = sc.apply_curation(analyzer, sorrel.read_curation("my_run/sorting_analyzer"))

crates/sorrel-py/python/tests/test_si_curation.py runs this against SpikeInterface in CI and checks every unit’s ids, spikes and labels.

The list form is one structural step per run of edits that touch disjoint units, followed by a single labels-only step keyed by the final unit ids. That expresses histories one pass cannot: a unit both merged and split, a second split of a unit, and labels or merges on units Sorrel created. Unit ids keep their SpikeInterface type ("7" stays a string), and strings that are not integers ("unit_a", "007") are written back verbatim. A merge keeps its target’s id and the merged unit’s own label; the sources’ labels leave with them. SpikeInterface never reuses a split unit’s id, so a split’s child gets the id Sorrel allocated for it and the spikes that stay behind get the next free id, not the original one. A merge into a unit that an earlier merge emptied re-creates the target’s id (SpikeInterface appends it, or keeps it in place when a source already holds it); with one source there is nothing to merge, so that unit keeps the source’s SpikeInterface id.

A rescue (AddSpikes, phy directories only) has no SpikeInterface curation slot. Its document still saves; it lists the edits under sorrel_unrepresentable, and sorrel.read_curation raises naming them instead of silently dropping spikes.

For phy directories the saved spike_clusters.npy already contains the merges and splits, so there curation.json is labels only and must not be applied on top of the npy a second time. Sorrel reads the file back on open when no cluster_group.tsv is present (phy dirs) and always for SortingAnalyzer folders, so labels made in SpikeInterface show up too. A SortingAnalyzer session keeps the label source it started from beside its journal (sorrel.journal.labels.json): its own saves rewrite curation.json with the head’s labels, and replaying the journal onto those would make undo restore the edit instead of the pre-session value. The copy goes away with the journal (--discard-journal sets both aside). A journal created before Sorrel 0.5 has no copy, and the labels it started from were overwritten by its saves; Sorrel warns on open, and undoing a relabel past the start restores the last saved label.

Exporting a phy directory

Saving updates the curation files in place. Exporting writes a complete phy template-gui directory somewhere else, from any backend, so phy, spikeinterface.extractors.read_phy() or a colleague without Sorrel can open the curated result:

sorrel export-phy <DATA_DIR> --out curated_phy/ [--copy-raw]
phy template-gui curated_phy/params.py

The same export is available as the export_phy tool of sorrel mcp, the Export phy button (it writes <dataset>_phy next to the dataset), and Session.export_phy(out_dir, copy_raw=False) in sorrel-py. It is the phy-export Cargo feature, on by default.

What goes into the directory depends on the source:

  • phy / Kilosort: every *.npy, *.tsv and *.csv file is copied byte for byte (templates, amplitudes, PC features, whitening, …), with spike_clusters.npy and cluster_group.tsv rewritten from the curation. Large non-phy files such as temp_wh.dat or rez.mat stay behind.
  • SortingAnalyzer, NWB, rez.mat: spike_times.npy, spike_clusters.npy, spike_templates.npy (one template per cluster), templates.npy, channel_map.npy, channel_positions.npy (and channel_shanks.npy when known) and cluster_group.tsv. Templates are mean waveforms of up to 500 spikes per cluster, 1 ms before to 2 ms after each spike, from the raw trace with the per-channel mean removed (no high-pass filter). Units-only NWB has no raw waveforms to average; if it also has no channels, export requires pairing a raw NWB with --dat. There are no amplitudes, PC features or similarity matrix, so phy falls back to its defaults for those views.

params.py points at the original raw recording by absolute path. With --copy-raw, the trace is streamed into recording.dat in its native dtype, which also decompresses an mtscomp .cbin. NWB traces are always streamed to recording.dat as float32 microvolts; units-only NWB has no recording to copy. params.py is written last, so an interrupted export never looks complete to phy. The export refuses to write into the source directory. The exported directory has no journal: opening it in Sorrel starts a fresh curation on top of the exported state.

Headless QC export

sorrel qc <DATA_DIR> --out out/qc/

Loads the data, runs the full metrics pipeline (firing rate, presence, refractory contamination, amplitude stats, ISI violations, isolation distance where PC features are available, composite quality), and writes:

  • out/qc/cluster_qc.tsv — one row per cluster, header columns are metric names.
  • out/qc/cluster_qc.json — the v1 top-level array, with the same row fields as the TSV.
  • out/qc/cluster_qc.provenance.json — a separate object with schema_version: 1, session_span, trace provenance, and composite_terms by cluster ID.

The sidecar and sorrel describe --json share the same session_span object, which describes the session-wide union of recorded intervals. kind is measured, declared, derived, or unavailable; source describes the origin, and interval_source is the declared NWB path or null. start_s and end_s are the outer bounds on the spike sample grid (end exclusive); extent_s is the time between them. recorded_s and its alias duration_s exclude gaps; gap_s is the difference and n_intervals counts the merged intervals. Times are null when unavailable. sorrel describe keeps duration as a string in seconds and also shows the extent when there are gaps.

A trace gives the span [0, trace length). Without a trace, NWB uses valid Units observation intervals (their union for the session), then epochs, then trials. If none covers the spikes, Sorrel estimates the span from the first spike through one sample past the last spike.

Firing rate, presence, and coverage use each unit’s recorded intervals, or the session span when no separate unit intervals are declared. Without a usable span, these metrics are null in JSON and blank in TSV. If any unit’s span differs from the session union, the sidecar lists every cluster’s denominator in seconds under unit_recorded_s (null when unavailable). For units-only data, refractory contamination estimates also require observable positive lags within the tested window. isi_violation_ratio counts violations per second of that unit’s own first-to-last spike span, not a fraction of spikes or a rate over the session. It is missing when that unit has no positive spike span.

Amplitude metrics require per-spike amplitudes, even if raw traces or waveform templates are available. Unmeasured metrics are null in JSON and blank in TSV, not zero. composite_quality is the equal-weight geometric mean of the measured subscores, with a floor of 0.001 per measured term. Missing terms are excluded from both the numerator (the sum of log scores) and the term count; with no measured terms the score is missing. The sidecar’s composite_terms map lists the terms used for each cluster ID: isi (refractory contamination), presence, coverage, snr, completeness, stability, and isolation.

…and exits without spawning a window. The journal is replayed first, so the export reflects current curation.

Automatic Curation

sorrel auto handles the repetitive part of curating a Kilosort sort, using the classifiers the SpikeInterface project recommends:

sorrel auto /data/session1 --gain-to-uv 2.34375          # label + merge, journaled
sorrel auto /data/session1 --reuse --save                # re-import, write phy files
sorrel auto /data/session1 --llm                         # an LLM settles the uncertain cases

All of its edits go into one batch in the curation journal, so one Undo in the GUI reverts the whole run. Every cluster gets tags that record who decided what. Clusters that still need a person get a review:* tag; the GUI’s review filter shows only those clusters.

Pipeline

sorrel auto runs crates/sorrel/src/sorrel_auto.py (embedded in the binary) using SpikeInterface ≥ 0.105. The script needs either uv on PATH, which installs the pinned dependencies on first use, or SORREL_PYTHON pointing to an interpreter that already has them. Without either, sorrel falls back to python3 on Linux and macOS and to python on Windows. The winget and Chocolatey packages install uv for you.

  1. Load. It loads the raw recording from params.py (or --dat, --spikeglx-meta), applies a 300 Hz high-pass and median CMR, and builds the sorting from spike_times.npy and spike_clusters.npy, so the unit ids are the same cluster ids sorrel uses.
  2. Analyzer. It computes waveforms, templates, PCs, spike locations, correlograms, template similarity, quality metrics and template metrics. The analyzer is cached in <DATA_DIR>/sorrel_auto/analyzer and rebuilt only when spike_clusters.npy or the recording options change.
  3. Redundant units. Near-duplicate spike trains found by remove_redundant_units are labelled noise and tagged redundant. They are not deleted.
  4. Merges. The similarity_correlograms and slay presets of compute_merge_unit_groups run separately. Their groups are combined, then merged in the analyzer so the merged units are measured again.
  5. Labels. Bombcell rules and the two UnitRefine random forests label each merged unit. SUA counts as good. Bombcell’s non-somatic call becomes the tag non-somatic.
  6. LLM (--llm, optional). An LLM decides the units where the two classifiers disagree or UnitRefine is unsure, and the merges that only one preset found (see below).
  7. Output. The script writes sorrel_auto/curation.json (SpikeInterface curation format v2, keyed by original cluster ids, validated before writing) and sorrel_auto/evidence.json. Every member of a merge group gets the merged unit’s label and tags.

Sorrel then imports curation.json, the same as running sorrel apply --curation. It also adds review:split to clusters where its own split ranking found a concrete two-way split; SpikeInterface has no standard automatic split. Importing the same document again changes nothing.

Bombcell’s amplitude threshold is in µV. Pass --gain-to-uv (e.g. 2.34375 for Neuropixels 1.0 at AP gain 500) or --spikeglx-meta. Without one of them, amplitudes stay in ADC units and that one Bombcell rule is meaningless.

Bombcell and UnitRefine were built on silicon probes with real geometry, mostly Neuropixels. If any two channels in channel_positions.npy are less than 5 µm apart, as with tetrode sorts that store channel indices instead of µm, the spatial metrics are meaningless. In that case every unit gets review:geometry and the run is only a starting point. On two such CINPLA tetrode recordings, sorrel auto called 58 of 65 human-kept units noise, while never keeping a unit the human had marked noise.

Tags

TagMeaning
src:bombcell, src:unitrefineThat classifier contributed to the label.
src:llmClaude decided the label or the merge.
src:spikeinterfaceSet by SpikeInterface cleanup (redundant).
src:sorrelSet by sorrel’s own ranking (review:split).
src:humanSomeone edited the cluster in the GUI after the run.
agree / disagreeWhether Bombcell and UnitRefine gave the same label.
conf:high / conf:mid / conf:lowUnitRefine probability ≥ 0.85, in between, or < 0.6.
bc:<metric>A Bombcell threshold the unit failed, e.g. bc:snr, bc:sliding_rp_violation.
non-somatic, redundantBombcell’s non-somatic waveform call; a near-duplicate spike train.
merged:similarity_correlograms, merged:slayThe merge preset(s) that proposed the merge.
merged:consensusBoth presets agreed on the merge.
review:disagree, review:low-conf, review:llm-unsureThe label needs a person.
review:mergeThe merge (applied or vetoed) needs a person.
review:splitSorrel’s split ranking has a split proposal for this cluster.
review:geometryChannel positions look like indices, not µm; every label needs checking.
tunedAn Auto unit that absorbed a merge or gained rescued spikes. Set by sorrel.
splitAn Auto unit that lost spikes to a split. Set by sorrel; a split child does not inherit it.
externalMerged, split or created outside sorrel (phy). Set on first open; origin stays Auto.

Tags are saved in cluster_sorrel_tags.tsv, which phy shows as an ordinary column, and in the tags category of curation.json. Any GUI edit to a tagged cluster (relabel, merge, split) removes its review:* tags and adds src:human in the same undoable step.

Unit origin, lineage and notes

Every unit has exactly one origin:

  • Auto[<sorter>]: the unit came straight out of the sorter. The sorter name is --sorter NAME when given, else the one pinned in the saved annotations, else detected from the directory (see below).
  • Sorrel[Manual], Sorrel[Algo:<name>] or Sorrel[LLM:<client>]: the unit was created inside sorrel.

Only a split creates a unit, so only a split gives a Sorrel[...] origin. A merge keeps the target’s id and origin, and the sources disappear. A split child’s origin is the method that made the split:

Made byOrigin
Lasso split in the GUISorrel[Manual]
split_initSorrel[Algo:split_init]
Suggest, GMM splitSorrel[Algo:gmm]
Accepted proposal, agentSorrel[LLM:<MCP client name>]
Accepted proposal, other sourceSorrel[Algo:<source>], e.g. Algo:kmeans
sorrel mcp splitSorrel[LLM:<MCP client name>]
sorrel-py split(..., by=...)the given method; default Sorrel[Algo:python]
Tests and fixturesSorrel[Manual]

Lineage is stored as direct parents only. A split child’s parent is the unit it was cut from. A merge target’s parents are the units merged into it. To see the full history, follow the parents recursively.

A note is free text on a unit, set with the snippet :note <text> on the selected clusters. :note with no text clears it. Notes are journaled and undo like other edits.

Origins, parents and notes are saved in cluster_sorrel_annotations.tsv with the columns cluster_id, sorrel_origin, sorrel_parents and sorrel_note. It has a row for every non-empty unit, and phy shows the columns. Notes are escaped so each fits one cell.

In curation.json, the exclusive origin label holds each unit’s origin, for example Auto[kilosort4]. Notes are not exported.

The sorter name is detected in this order; the first match wins:

  1. sorter_name in spikeinterface_log.json, in the directory or its parent.
  2. ops.npy: kilosort4.
  3. rez.mat or cluster_KSLabel.tsv: kilosort.
  4. A SortingAnalyzer folder: the sorter_name in sorting/annotations.json, else spikeinterface.
  5. A .nwb file: nwb.
  6. Nothing matches: unknown.

Override the detected name with --sorter NAME, which is a calibration knob. Precedence: --sorter, then the name pinned by a saved Auto[<sorter>] row, then detection. Re-detection never changes a saved name; --sorter does, and the next save pins the new name. A saved Auto[unknown] pins nothing.

The journal format is described in History.

origin is not the same as the src:* tags. The origin says where a unit came from. The src:* tags say who labelled or reviewed it, for example src:llm or src:human. The two are independent, and the src:* tags are unchanged.

Reviewing

  • GUI: check review above the cluster table. Sort by tags to list the clusters with the most review tags first. The filter box matches tags as well as ids, e.g. merged, src:llm or bc:snr.
  • HTML: sorrel report DIR --tag review: --out review.html.
  • Agents: sorrel mcp adds list_clusters {"tag": "review:"}, evidence {"cluster": N} (the classifier outputs and Claude verdicts) and tag, so an MCP client can go through the queue with the same evidence.

Claude

With --llm, the uncertain cases go to an LLM. Bare --llm uses the claude CLI; --llm=BACKEND picks one (the = keeps --llm DIR unambiguous):

BackendNeeds--llm-model default
claude (bare)Claude Code on PATH, signed in (/login)the CLI’s own
codexcodex on PATH, codex loginthe CLI’s own
opencodeopencode on PATH, opencode auth loginthe CLI’s own (provider/model)
apiANTHROPIC_API_KEY or ant auth loginclaude-opus-5

A missing CLI fails the run before any analysis. The CLI backends run one process per case (8 in parallel) with tools disabled, no session and an empty working directory: claude with no MCP servers, project-only settings and --json-schema; codex exec read-only with --output-schema; opencode run with every permission denied. opencode and codex get the system prompt prepended to the message, and opencode has no schema enforcement, so every reply is validated (label or merge flag, confidence clamped to [0, 1], at most three reasons). A failed, timed-out (10 minutes) or invalid reply leaves that case in review.

The LLM is sent text, not plots: the same token-lean brief an MCP agent reads (see Agents). sorrel auto hands the sidecar its own binary and open arguments (SORREL_BIN, SORREL_OPEN_ARGS), so the sidecar runs sorrel call DIR brief and sorrel call DIR eval on the dataset exactly as sorrel auto opens it. They run before sorrel auto opens the session, so the journal is not locked; with a host running, sorrel call goes through it. If a call fails, the --llm stage fails with its stderr and nothing is applied. A single case that cannot be judged (a missing card or eval line, a failed or malformed backend reply) is only logged: it gets no verdict and keeps its review:* tags. A merged unit with any member card missing is not asked about at all. --llm cannot be combined with --reuse, and with --discard-journal set the journal aside first (sorrel open --discard-journal). --llm=api needs ANTHROPIC_API_KEY or an active ant auth login profile (its stored credentials, not just the ant binary) and fails before the analysis otherwise. Each run sets an existing evidence.json aside as evidence.json.<unix seconds> first, so a rerun cannot overwrite paid verdicts.

  • System prompt (cached once for all cases with --llm=api; the CLI backends re-send it with every case, about 3 KB per case, until a persistent-session backend replaces the process per case): the rubric plus the brief header, which has the recording, the population quantiles of every metric, the flag thresholds and the legend for the cards.
  • One message per unit: the unit’s card row (every metric, the flags it trips as a delta against the population, SAX strings for the ACG and for amplitude over time) under the card’s column line, plus both classifiers’ outputs. A merged unit gets its members’ cards and the merge counterfactual.
  • One message per merge: the counterfactual line from the eval tool ({"merge": [a, b, ...]}: per-part and merged contamination, presence, cutoff, CCG dip and synchrony, amplitude KS) and which presets proposed it.

Amplitudes are in the brief’s own units, which its header states (template units for Kilosort; --gain-to-uv scales only the SpikeInterface side). A unit message is a few hundred bytes where the raw arrays it replaces (25-point template, 30-bin ACG, 8-channel footprint, deciles; JSON) took 1-2 KB; the header is paid once with api and per case with the CLI backends.

The reply is a JSON verdict (label or merge/no-merge, a confidence and up to three reasons). Its model names the backend: claude-cli:<model>, codex:<model>, opencode:<model>, or the bare model id for api. It is stored in evidence.json next to the exact user message that produced it (llm_input, per unit and per merge); the system prompt’s brief header is stored once, as the top-level llm_header. A verdict below 0.7 confidence keeps the case in review as review:llm-unsure. A confident “do not merge” vetoes a merge that only one preset found.

Checking it on your data

Compare sorrel auto with your own curation of the same dataset:

cp DIR/cluster_group.tsv human.tsv                       # a curated copy
sorrel auto DIR --discard-journal --save                 # on a fresh copy of the sort
sorrel diff human.tsv DIR/cluster_group.tsv              # kappa + disagreements

Repeat with --no-unitrefine, without --llm and with --llm to see which stage helps on your recordings. A synthetic self-check lives in scripts/test_sorrel_auto.py (uv run --script scripts/test_sorrel_auto.py [--unitrefine]).

Double-blind bench

To find out what sorrel auto --llm and the MCP review agent miss compared with a person, replay human curations through them and score the difference.

The target is the quality of the human’s manual post-sort curation in phy: those curations are the training data. Sorrel will need new features and ideas to reach that quality, not only better prompts. On the first dev session both arms recovered 1 of 17 good units, because nothing in sorrel could propose the cores the human carved out of under-split templates. Each round of the loop therefore looks first for the missing capability (a proposer, probe, brief feature, metric, rule or tool) and only then at the prompt around it. scripts/bench_curation.py (a stdlib uv script) runs the bench; its data lives in a private BENCH directory outside the repo.

Data. Sessions curated in sorrel and saved, ideally from scratch: a session whose history holds a sorrel auto or agent batch anchors the human on the machine’s answer, so it is kept in dev and never enters the holdout. About 30% of the purely manual sessions go to the holdout, chosen by a salted hash. Many sessions beat many repeats; Neuropixels geometry helps the probe-based checks. Kilosort sorts curated in phy work too (add --phy-curated): the sorter’s clustering comes from spike_templates.npy. Data owners package a phy-curated Kilosort sort with the export-curated-sort skill (.claude/skills/export-curated-sort/), which keeps only what the bench needs and verifies the compressed raw recording before delivery.

The curation-bench-loop skill (.claude/skills/curation-bench-loop/) runs the improvement loop below and says which steps a cheap flash agent can do, which need a worker and which stay with the lead. Before collecting data, run the checks in its “Pitfalls (learned the hard way)” section. Each one cost a round or leaked an answer once. To set the bench up on a new machine, including how the sealed holdout survives the move, see bench/README.md. Results, prompt variants and lineage live in bench/ (the results DB through git-lfs).

Three blinds.

  1. Curator blind. sorrel blind writes the sorter’s own root output (no journal, labels, tags, notes, curation.json or .phy/), checks it against the journal’s baseline hash, and keeps the human’s final state apart as the truth. Sessions get opaque ids; the path map and the salt are sealed in BENCH/.sealed/. Every run works on a fresh hard-linked copy of the input.
  2. Improver blind. Per-unit misses are only reported on dev. The holdout reports aggregates, with a paired bootstrap over sessions, and every holdout query is logged.
  3. Blinded A/B adjudication. Each disagreement goes to a reviewer as two verdicts in random order, without saying which is the human’s. Units where the human loses are disputed and drop out of scoring.
b=~/sorrel-bench; v=variants/base       # a variant dir may hold rubric.md / review.md
bench_curation.py --bench $b add ~/sessions/*                    # blind, seal, split
bench_curation.py --bench $b run --arm mcp-review --variant $v --split dev --repeats 3
bench_curation.py --bench $b run --arm auto-llm   --variant $v --split dev --repeats 3
bench_curation.py --bench $b score                               # sorrel diff per run
bench_curation.py --bench $b report dev                          # misses + the card the arm saw
bench_curation.py --bench $b adjudicate --split dev [--judge claude]
# fill the `choice` column (A, B or both-wrong) of adjudication/dev/cases.tsv, then:
bench_curation.py --bench $b adjudicate --split dev --unmask     # writes disputed/<session>.tsv
bench_curation.py --bench $b report holdout --baseline base --candidate new

SORREL_BIN picks the sorrel binary. The variant’s rubric.md and review.md reach both arms as SORREL_RUBRIC / SORREL_REVIEW, and the prompt revision is recorded with every run, so a variant needs no rebuild. The mcp-review arm runs claude -p with the sidecar’s isolation (empty working directory, strict MCP config holding only sorrel mcp RUN, no built-in tools, no session persistence) and the prompt from sorrel agent-guide --prompt review; each run.json records the model, usage, cost and wall time. Reviewers open the cases’ input_dir (a copy is safer; stray files there never reach a run). The LLM judge is dev-only; holdout cases are for humans.

The improvement loop.

  1. Baseline both arms on every session, 3 repeats each, and score.
  2. Adjudicate the disagreements (a human for the holdout, an LLM judge is fine on dev), unmask, and score again.
  3. report dev; pick the largest miss category.
  4. The improver changes one thing. First it asks what sorrel lacks to make the human’s decision, and builds that: a new proposer, probe, brief feature, metric, rule default or tool. A prompt change (rubric or review instructions) on its own is only for gaps the existing capabilities already cover. It sees dev reports, the dev truth verdicts and the repo only.
  5. Rerun dev. The target category must improve and no other may regress beyond the spread across repeats.
  6. One holdout query decides: a paired improvement with no category regression. The change then lands as a PR: a sorrel feature with its tests, or a prompt edit in serve.rs. Each round reports the distance to the human curation (good-unit recall and precision, where 1.0 means matching the human), not just the delta to the previous round.
  7. When new sessions arrive, re-split, refresh the holdout and retire the ledger.

A smoke test with stub CLIs (scripts/test_bench_curation.py) needs neither data nor a model.

Spike rescue

sorrel rescue <DATA_DIR> finds spikes the sorter missed, for units you already have. It adds spikes to existing units. It does not discover new units. It works on Kilosort and phy directories only.

It is a dry run unless you pass --apply. --apply journals the additions as one batch, so one Undo reverts them. This is the same model as Automatic Curation.

Method

For each target unit:

  1. Templates. Build a raw-space template for each time block, 60 s by default. Each block gets its own template, so drift is absorbed.
  2. Filter. Compute a matched filter whitened by the noise covariance, Σ⁻¹·M, where M is the block template and Σ is the noise covariance.
  3. Scan. Run the filter on the GPU over the high-passed, CMR’d residual. The residual is the signal left after every accepted spike has been subtracted.
  4. Accept. Keep a detection only if it:
    • beats the best competing unit by --margin;
    • is outside the fixed refractory window of the unit’s existing spikes (1.5 ms by default; --refractory-ms overrides it);
    • clears the unit’s threshold. The threshold comes from a channel-shifted null, set to control the false discovery rate at --q.
  5. ISI check. If the unit’s ISI-violation fraction more than doubles, drop all of that unit’s additions.

Flags

FlagDefaultMeaning
--units good|all|<ids>goodUnits to rescue: the good units, all units, or a list of cluster ids.
--q0.05Target false discovery rate for each unit’s threshold.
--margin0.2Required margin over the best competing unit.
--replicates3Channel-shifted null replicates.
--block-seconds60Length of each template time block.
--chunk-seconds2Length of each GPU processing chunk.
--channels-per-unit16Channels used by each unit’s template and filter.
--hybrid-frac FoffInject hybrid spikes for a recall check. See Hybrid check.
--jsonoffPrint the report as JSON.
--applyoffJournal the additions as one undoable batch.
--saveoffWith --apply, save the directory. See Saving.
--seed1Random seed for the nulls and the hybrid injection.

The usual recording flags also apply, as for sorrel auto.

Dry run

A dry run is the default. It prints one row per target unit:

ColumnMeaning
existingSpikes the unit has now.
addedSpikes the rescue would add.
thetaThe unit’s detection threshold, from the null at --q.
est_fpFalse positives among the added spikes, estimated from the null.
isi_beforeISI-violation fraction before the rescue.
isi_afterISI-violation fraction after. Step 5 above applies to this column.
min_r2Lowest feature-calibration R² (see New spike features).

Hybrid check

--hybrid-frac F injects F × n_spikes copies of each unit’s template at random times into the in-memory signal. The .dat file is never written. The rescue then runs as usual, and the report gives recall per unit and per amplitude tercile.

A hybrid run is always a dry run. It never applies or saves.

Injected spikes are idealised, so recall on them is likely higher than on real spikes. It still shows which units the threshold cannot reach. Run it before you trust a rescue on real data.

Applying

--apply journals one undoable batch:

  • an AddSpikes record with the added spikes;
  • a review:rescue tag on each touched unit, shown with the other review:* tags.

Units that came straight from the sorter (Auto[...]) also get tuned. See the tag table in Automatic Curation.

Saving

--save saves the directory (see Saving). Because added spikes change the row count, the save rewrites every per-spike array in time order:

  • spike_times.npy, spike_clusters.npy, spike_templates.npy, amplitudes.npy, pc_features.npy, template_features.npy, every other spike_*.npy, and spike_reorder.npy.
  • spike_sorrel_rescued.npy is new. It holds 0 or 1 per spike, and marks the added rows. phy can show it as a spike attribute.

Safeguards:

  • Before the first rewrite, the originals are hard-linked into sorrel_original/. They are the sort as loaded, which the journal replays onto, so the rescue stays undoable after the save.
  • phy’s .phy/ cache is renamed to .phy.sorrel-stale, so phy does not use it with the rewritten arrays.
  • A manifest of pending renames is written first, which makes the save crash-safe.
  • The save refuses to run if the directory holds an unknown per-spike .npy, because it cannot reorder that file.
  • sorrel journal replay <DATA_DIR> --out DIR is refused while there are added spikes. It writes no per-spike arrays, so the files would no longer match. Save the directory itself instead (--apply --save).

Undoing the rescue and saving again writes the original arrays back.

New spike features

Added spikes do not get features computed from their waveforms the way Kilosort computes them. pc_features, amplitudes, template_features and the other per-spike attributes are predicted by a ridge regression. The regression is fitted on each unit’s own spikes. min_r2 in the dry run reports how well that fit works.

On real tetrode data, R² was low, about 0.1–0.2. Treat the PC features of rescued spikes as approximate.

GPU

Rescue runs on the GPU through wgpu. If no GPU is available, it falls back to a CPU reference and prints a warning. The CPU reference is about 100× slower.

On a 297 s, 32-channel Kilosort 2 tetrode recording from CINPLA with 62 clusters, 12 target units took 3.5 s on the GPU and 9.5 min on the CPU. That is about 160× on this recording.

Limitations

  • The channel-shift null is conservative for large, high-rate units. On the test recording, hybrid recall was 60–66% for 2 of 12 units and near 0% for most of the others.
  • A sign-flipped null recovered 65–90% for 7 units but failed on 2 others. Choosing the null is still open.
  • There is no joint refit of overlapping spikes.
  • Single-channel units cannot be rescued, because the channel-shift null cannot break them.
  • Rescue does not discover new units.

Example session

# 1. Hybrid check: measure recall. Never writes the .dat or the journal.
sorrel rescue /data/session1 --hybrid-frac 0.2 --seed 1

# 2. Dry run on the good units.
sorrel rescue /data/session1

# 3. Journal the additions and save.
sorrel rescue /data/session1 --apply --save

Reopen the directory after step 3. Then check the review:rescue clusters with the review filter.

Remote Work

Share a Kilosort/phy dataset with a collaborator on another machine. The host keeps the data; the guest curates in a normal Sorrel window and every edit lands in the host’s journal as it happens.

host:   sorrel share <DIR> [--port N]                 # or: --relay MULTIADDR
guest:  sorrel join "<six words>" --direct MULTIADDR  # or: --relay MULTIADDR

What moves over the wire

  • phy artefacts (spike_times.npy, spike_clusters.npy, templates, PC features, …) are copied once into the guest’s --into directory and verified with BLAKE3. Re-running join with the same directory skips files that already match.
  • The raw recording is never copied. The guest keeps a sparse mirror under .sorrel/remote/recording.dat and fetches the byte ranges the trace and waveform views ask for. Time windows render grey until they arrive; neighbouring windows are prefetched.
  • Curation commands stream back to the host as journal records. Each carries the (baseline, record count) cursor it was applied against; the host refuses a record that does not fast-forward its journal, and the guest’s own journal keeps everything so a later join catches up.
  • The derived cache (.sorrel/cache) is not shared; the guest rebuilds it.
  • A guest’s Export phy writes <into>_phy with params.py pointing at the sparse mirror, so traces only cover what has been fetched. Export on the host for a phy directory with the complete recording. --copy-raw on a guest has no separate guard: it reads the trace through the mirror, and the export fails (“came back incomplete”) at the first window not fetched yet, rather than writing the gaps.

Only one writer exists while a share is active: the host runs headless and only applies what the guest sends. Open the host directory normally after the share ends.

Current limits of protocol v3:

  • The guest’s edits reach the host as journal records, so they appear in the host’s History with the actor guest.
  • An undo, redo or save the guest made while disconnected cannot be pushed to the host; join refuses and asks for a fresh join directory.
  • sorrel_original/ travels with the other files, so the guest replays the same history the host has, saves included.

Pairing

share prints six words. Both machines derive their network identities from those words (argon2id, then ed25519), so the encrypted handshake itself proves each side knows the code and the host accepts exactly one guest identity. Treat the words like a password for that session and send them over a channel you trust.

Modes

Direct (the default): the host listens on QUIC and TCP (--port, default 7373) and prints sorrel join … --direct /ip4/… lines. On the same LAN the guest can omit --direct; mDNS finds the host. Across the internet you need a reachable address (port forward, VPN). Nothing sits between the two machines.

Relay (--relay MULTIADDR): for guests behind firewalls that only allow outbound HTTPS. Both sides dial a sorrel-relay server over WebSocket/TLS on port 443; the relay forwards encrypted bytes and sees neither the code nor the data. The relay address has the form /dns4/relay.example.org/tcp/443/wss/p2p/<RelayId>; the server prints its id on start.

Limitation: explicit HTTP CONNECT proxies (the HTTPS_PROXY kind) are not supported yet; the relay path works where outbound TLS on 443 is allowed.

Running a relay

sorrel-relay --listen /ip4/0.0.0.0/tcp/4001/ws --identity /var/lib/sorrel-relay/relay.key

Terminate TLS in front of it (caddy, nginx, or a Cloudflare-proxied hostname with WebSockets enabled) and publish /dns4/<hostname>/tcp/443/wss/p2p/<RelayId>. The identity file keeps the id stable across restarts. Circuit byte and duration limits are disabled; rate limits are off, so keep the relay for people you know.

The relay is a server meant for Linux or macOS. On Windows it still runs: the identity file is restricted to the current user with icacls (Unix gets mode 0600), and the relay warns if that fails. Do not host a shared relay there.

Agents & Headless Mode

A sorrel session has one owner, the session host. The GUI, MCP agents and a remote guest all edit through it. Every edit is journaled with who made it, so it can be undone and shows up in the History pane.

sorrel open <DATA_DIR>               # a tab in the running window, or a new window
sorrel run --headless <DATA_DIR>     # host only; stops on Ctrl-C
sorrel mcp [<DATA_DIR>]              # the command an agent launches

Connecting an agent

sorrel mcp speaks MCP (JSON-RPC 2.0, one object per line) on stdio. Without <DATA_DIR> it attaches to the GUI’s active tab, or else to the only running host; if there are several, it errors and lists them, even if they share a save directory. With a local <DATA_DIR> it connects to the matching host (the GUI or run --headless) when one is running. Otherwise, or when any input is remote, it opens the dataset itself and serves it until stdin closes. sorrel serve is gone; use sorrel mcp.

sorrel mcp config --client claude prints the registration line for Claude Code, --client codex a Codex TOML block, and --client json an mcpServers entry like this:

{
  "mcpServers": {
    "sorrel": { "command": "sorrel", "args": ["mcp", "/data/run42/ks4"] }
  }
}

On Windows, the winget and Chocolatey packages put sorrel on PATH, so the same entry works with a Windows path:

{
  "mcpServers": {
    "sorrel": { "command": "sorrel", "args": ["mcp", "C:\\data\\run42\\ks4"] }
  }
}

A running host listens on 127.0.0.1 on a random port. It writes the port and a token to $XDG_RUNTIME_DIR/sorrel/mcp/<hash>.json (fallback ~/.cache/sorrel/mcp/; %LOCALAPPDATA%\sorrel\mcp\ on Windows, which only your account can read), mode 0600 on Unix, and deletes the file when it exits. The file also records the dataset path and whether the host is a GUI or headless. SORREL_USER_DIR overrides the base directory. A client must send the token first. Only processes that can read that file can connect.

The client’s clientInfo.name from initialize names the agent. The agent indicator, the toasts and the History pane use that name, and a split it makes gets the origin Sorrel[LLM:<name>].

Tools

ToolWhat it does
briefRead the session as compact text. Level 1: header and flagged units. Level 2 (or clusters): one card per unit. Level 3: relations (merge components m<k>, split candidates s<cluster>.<k>).
evalCounterfactual of a merge (merge ids) or a handle (candidate), without applying it.
probeClosed-grammar computations for hypotheses the brief did not anticipate (acg, ccg, compare, window, split, eval). One compact answer per query; no arbitrary code.
rules_evalRun a threshold rule set (TOML) on every unit. Returns label counts, margin units and disagreements with the auto classifiers.
rules_applyApply the rule set as relabels in one undo step. Remembered in .sorrel/review_rules.toml.
decideMany decisions in one call: [target, action, confidence, reasons]. One undo step under Direct, one proposal per item under Propose.
list_clusters (TSV), metrics (one row, JSON), suggest, evidence, attention_queue, split_proposals, merge_candidatesRead the session. Each points at the brief for the compact form.
relabel, merge, splitEdit one thing. Journaled and undoable; queued as a proposal instead under Propose. split takes a handle.
tag, undo, save, export_phyRetag a cluster, undo the last edit, save, export a phy directory. Refused under Propose.
proposeQueue one relabel, merge, split or accept for a human, with a confidence and up to three reasons.
select, selectionMove the human’s selection in the GUI, or read it. These need the GUI.

render and features are gone. They returned SVG coordinates and raw PC samples, which a model cannot read. The brief carries the numbers instead: waveform landmarks, footprint, ACG and amplitude strings. sorrel report still writes the SVGs.

Handles

brief level 3 and suggest name every merge component m<k> and every split candidate s<cluster>.<k>. Pass the handle as candidate to split, propose and eval, or as the target in decide. A handle records the spikes of the clusters it names and is refused as stale once any of them changed. Tools never return spike indices.

decide

decisions is a list of [target, action, confidence, reasons], or of objects with the same keys plus an optional note.

  • target: a cluster id, a split handle ("s12.1"), a merge handle ("m3"), or a list of ids for a merge (the first is the target).
  • action: good, mua, noise or unsorted (relabel), merge, split (needs an s handle) or accept (drops review:* tags).
  • reasons: at most three codes (flag codes or rule names). Free text is allowed up to eight words.

Every item is checked first. If one is invalid, nothing is applied and the reply lists the errors by item. A cluster may appear in only one item. Under Direct the items are one batch, so one undo reverts all of them, and the batch is refused if the session changed since the check. Splits are in the batch.

probe

q is a query string or a list of them; each gets one answer block. Times in acg/ccg are milliseconds, in window/split seconds.

  • acg C [win=50] [bin=1]: refractory estimate and contamination, burst index, a SAX string over log lags and the first six bin rates in Hz.
  • ccg A B [win=50] [bin=1]: dip_z, sync_z (always on the standard 1 ms, ±50 ms CCG), the +/- lag asymmetry with its z, and a SAX string.
  • compare A B: template cosine over the union of active channels, peak-channel distance in µm, trough-to-peak and half-width deltas, amplitude ratio.
  • waveform C: current-membership raw waveform evidence from at most 128 jittered, time-stratified spikes on up to eight channels. Reports valid/sample counts, peak channel, baseline-MAD SNR, early/late waveform cosine and shape landmarks. Unlike primary sorter-template descriptors, this evidence follows split memberships. DC subtraction only; the response states whether the raw input was high-pass filtered. Do not apply filtered-template shape cutoffs to unfiltered or unknown raw. Missing/incomplete raw fails explicitly, never silently falling back to a parent template. No spike indices are returned.
  • window C T0 T1: n, rate, contamination, amplitude and presence of that slice against the whole unit.
  • split C by=amp|time|pc|kmeans|core|robust|axis [at=X]: registers a new split handle s<C>.<k> and prints its eval line. The minor part is the spikes above (amp, pc) or after (time) at. Defaults: the GMM boundary, the largest amplitude jump on a coarse 20-point scan, PC1 at 0 with the smaller side as minor; kmeans uses the same proposer as brief level 3; core isolates a small clean refractory core of a contaminated unit (diagonal GMM, BIC-chosen k <= 8; a contaminated component may offer a high-posterior dense interior with the same size, separation and refractory gates; run it again on the remainder for a second core), or, when a contaminated minority is dropped to leave a clean majority, the cleanup reading (minor part = the dropped minority; the handle line names core or cleanup, the better of the two is returned). robust fits one covariance-aware boundary and keeps the clean majority; axis lists up to 30 alternative PC/amplitude mixture handles instead of one. Act on the handle with split, decide or eval.
  • eval merge A B .., eval s12.1, eval m3: as the eval tool.
  • Experimental split C by=robust fits a correlated majority cloud plus broad tails, returning robust-cleanup (minor = dropped tail). No at= is allowed. It requires a BIC-supported broad component, at least 100 spikes per part, majority retained, retained rpc <= .1 and no refractory regression. A handle is a boundary hypothesis, not a good label. Inspect each part independently.

A parse error in one query lists the grammar and does not stop the others.

Experimental split C by=axis lists at most 30 alternative PC-coordinate and amplitude-mixture handles, with remaining/moved counts, rpc and BIC evidence. It accepts no at=. Listing is read-only and does not compute every CCG; use eval for a handle worth considering. Alternatives can overlap: applying one invalidates the others for that parent. rpc support is NOT a good label.

The review protocol

The review prompt (triage is an alias) walks an agent through this:

  1. brief level 1: read the mode, the population quantiles and the ledger.
  2. Write a rule set for the labels and call rules_eval. Refine it until few units are on the margin or disagree with the auto classifiers.
  3. Look only at margin, disagreement and flagged units: brief with clusters, level 3 for relations, eval for a counterfactual, probe for a hypothesis neither covers.
  4. rules_apply, then decide for the exceptions, the merges and the splits.
  5. brief level 1 again to confirm.

The cost depends on the number of borderline units, not on the number of units. The prompt ends with the curation rubric, which names the brief’s descriptors.

Token budget

  • Levels. Level 1 is the header and a ledger of flagged units. Level 2 adds cards. Level 3 adds relations. Ask for clusters to get cards for a few units, and budget (tokens) to cap the reply. What did not fit is listed with the handles to fetch it.
  • Mode-delta flags. The header gives the mode of each metric. A unit lists only the flags where it differs from the population, so a clean sort is a short reply.
  • Quantiser. Numbers are rounded to few significant digits and log-scaled where useful. Rounding never moves a value across a flag threshold (including those of your rule set), so a decision on the quantised number is the decision on the raw one.
  • Handles. A candidate costs a few characters, not a list of spikes.
  • Output. decide takes codes and a batch instead of one propose call with prose per decision.

Every agent edit adds src:agent to the clusters it touches, in the same undoable step. When someone else changes the session (you in the GUI, another agent), the agent gets a notifications/message after its next reply. The message names the actor, the change, the clusters and the new version.

Direct or Propose

While the GUI serves agents, the top bar shows an agent strip:

  • a dot, lit while an agent’s last edit is highlighted;
  • the names of the connected agents;
  • N to review, which opens the Proposals pane;
  • Direct | Propose.

Under Direct (the default), relabel, merge and split apply at once. Under Propose, they only queue a proposal. propose always queues.

What you see when an agent edits

  • A toast names the agent and the edit, e.g. codex: merge 1 cluster(s) into 2.
  • The clusters it touched are selected, the same as after your own edit.
  • Their rows in the cluster table are tinted for three seconds.
  • The edit is a node in the History pane with the agent’s name. Ctrl+Z undoes it like any other edit.

Proposals

The Proposals pane has one card per waiting proposal. A card shows who proposed it, what it does, the confidence and the reasons:

  • Click a cluster chip to select the clusters and look at the evidence in the other panes.
  • Accept applies the proposal as your decision. It adds src:human, drops review:*, and a split keeps the agent as its method (Sorrel[LLM:<name>]).
  • Reject applies nothing. A rejected merge tags the clusters notmerge:<other>, and a rejected split tags the cluster notsplit, so the suggestion rankers stop offering it.

Every proposal and every decision is appended to <DATA_DIR>/.sorrel/proposals.jsonl.

Headless mode

sorrel run --headless <DATA_DIR> opens the dataset, replays the journal and serves agents with no window. It prints the port and the command to connect, then runs until Ctrl-C. Edits land in the same journal the GUI uses, so opening the GUI afterwards shows them, branches included.

Without a GUI, select and selection return an error, and agents always edit directly.

From a shell

sorrel call <DATA_DIR> <TOOL> [ARGS_JSON] runs one MCP tool through the running host, or in-process when none is running. It prints the result and exits non-zero on error; --raw prints the JSON-RPC response instead:

sorrel call ks4/ metrics '{"cluster": 12}'

sorrel status --json lists the running GUI, its tabs and every session host, for scripts. sorrel agent-guide prints a primer for LLM agents, with the live command list, the MCP tools and the running hosts.

History

Sorrel keeps every edit. The journal is a tree: undo moves back to the parent, and an edit after an undo starts a new branch next to the old one, so nothing you undid is lost. The tree survives saving and reopening.

The History pane

History sits at the end of the Assess tab group. View → History reopens it after you close it. It lists the tree oldest first:

  • The first row is the sort as loaded, before any edit.
  • Each edit is a row with who made it (you, an agent’s name, an algorithm or a remote peer), what it did, and the time (UTC).
  • A straight run of edits stays in one column. Each later branch is indented one step under the edit it left from, and that edit says how many branches leave it.
  • The current edit is highlighted.
  • Saved edits are marked saved.

Click a row to go back to it. Sorrel undoes up to the point the two branches share, then reapplies the edits down to the row you clicked. The toast names where you went, e.g. back to: relabel cluster 12 as Good. Going back is journaled too, so it survives a reopen.

Undo and redo

KeyMoves to
Ctrl+Zthe parent of the current edit
Ctrl+Shift+Z / Ctrl+Ythe branch you visited last

An edit after an undo creates a new branch. Redo then follows the new branch, and the old one is a click away in the History pane.

Saving and reopening

Saving writes the current edit’s state to the phy files and marks it saved in the journal. It does not cut the history. The title-bar chip reads unsaved whenever the current edit is not the saved one, including after you go back past a save.

On reopen, sorrel replays the journal from the sort as loaded. For phy directories, the sort as loaded is kept in sorrel_original/ (see Saving), so the saved files never stand in for it.

Journal format

The journal is format version 3. Each record is one of:

  • an edit, with its parent, actor and time;
  • a move of the current edit;
  • a save.

Sorrel upgrades a version 1 or 2 journal the first time it opens it. Undone edits become branches, and the file is rewritten as version 3. Older sorrel builds refuse a version 3 journal (“not a sorrel journal (bad magic)”) instead of truncating it. Upgrade every sorrel build that opens the same sort.

Workspace Layout

Sorrel is a Cargo workspace with one role per crate:

CrateRole
sorrel-ioDataProvider trait and backends: Phy / Kilosort, SortingAnalyzer, NWB, MATLAB rez.mat, and recording-only readers (SpikeGLX, Open Ephys, MDA, probeinterface).
sorrel-cacheRebuildable derived-artifact cache. Owns content-addressed keys, rkyv archive I/O, atomic writes, and mmap-backed bytechecked reads; deleting it never loses user data.
sorrel-computeCPU kernels: LTTB downsampling, histograms, ISI / CCG, CMR + filter, mean snippet, GMM, drift, quality metrics, isolation distance.
sorrel-gpuwgpu compute pipelines (CMR median, biquad HP filter, mean snippet) sharing the device and queue with the renderer.
sorrel-dataGeneric Session<P>, CurationCommand, append-only Journal, save / replay, QC export, merge/split previews and suggestions.
sorrel-renderConcrete vertex types and monomorphised buffer builders for the trace and raster paths.
sorrel-uiegui widgets and views, generic over P: DataProvider.
sorrelBinary. Parses CLI, detects backend, instantiates SorrelApp<P>.
sorrel-pyOptional Python bridge (PyO3 / maturin) — exposes sorrel.open(recording, sorting) for SpikeInterface users.

The split is functional, not layered: each crate owns its concerns end to end, and the binary stitches one fully-monomorphised arm together per backend it supports.

Data Flow

Sorrel’s core path is generic over P: DataProvider. The binary detects a backend, constructs the concrete provider, opens the curation journal, and builds a Session<P>. From there the UI, render buffers, and compute kernels are all statically dispatched.

Open

  1. detect_backend inspects the path (file vs directory, marker files, extension) and picks one of Kilosort, SortingAnalyzer, Nwb, or Ks4Rez. --backend skips the detector.
  2. The chosen provider opens its inputs:
    • Kilosort / phy mmaps spike_times.npy, spike_clusters.npy, and the raw .dat; reads optional artefacts for templates, PC features, amplitudes, similarity, probe geometry, and quality metric sidecars.
    • Other backends do the equivalent for their formats.
  3. Session::new holds the provider and journal. seed_* calls bucket amplitudes, templates, PC features, and template waveforms once so hot-path lookups are O(1) slice borrows.
  4. replay_journal rebuilds the action tree from the journal and applies the path from the sort as loaded to the current edit, so the open state matches the last running state.

Cache

Derived artifacts that have cache support consult <dataset>/.sorrel/cache/ first using the provider identity, current journal head, artifact algorithm version, parameters, and any per-cluster spike fingerprints. Misses fall through to the existing compute path and then write an archive for the next open.

The journal head is the invalidation point. Applying a CurationCommand records the previous head and affected cluster identities in the session’s in-memory invalidation log. Sorrel evicts known pre-edit derived artifacts at save and quit, while CacheStore::open runs bounded GC for orphaned, aged, and over-budget files. See Derived Cache for the full contract.

Edit

CurationCommand is a closed enum: Relabel, Merge, Split, Note, Tag, AddSpikes, Batch, Undo, Redo. Every frontend (GUI, MCP, remote) edits through SessionHost::apply, which tags the edit with its actor and announces it to subscribers. A forward command becomes a new node under the current one; Undo/Redo and History clicks move the current node. The session applies an edit in two strictly-ordered steps:

  1. Append to the journal. A durable (fsynced) journal append is the point-of-no-return.
  2. Mutate in-memory state. The ClusterIndex updates, the selection moves, caches that depend on history are invalidated.

If step 1 fails the in-memory session does not move. If the process is killed between step 1 and step 2, replay reconstructs the missing transition.

Save

Cmd/Ctrl-S writes spike_clusters.npy + cluster_group.tsv into the save directory and journals a seal. Replays still start from the original sort, kept in sorrel_original/ for phy directories.

Render

The trace view assembles a window of the raw trace, optionally runs CMR

  • HP filter (CPU or GPU), then LTTB-downsamples per channel into TraceVertex buffers consumed by the wgpu pipeline. Other views (raster, ISI, CCG, features, drift map…) build their geometry directly in egui from the per-cluster slice borrows the session exposes.

Derived Cache

Sorrel stores rebuildable derived artifacts under:

<dataset>/.sorrel/cache/

The cache is not user data. Deleting this directory must never delete curation work, journal records, provider inputs, or exported phy files. It only removes derived archives that Sorrel can recompute from the dataset and journal.

Contents

The cache stores expensive derived data such as seeded amplitude buckets, per-cluster PC subspaces, isolation metrics, and correlograms. It does not store the curation journal, external JSON sidecars, raw traces, spike arrays, or any file that is required to reopen the dataset.

Each cache entry is an rkyv archive at:

<dataset>/.sorrel/cache/<kind>/<fingerprint>.rkyv

INDEX is an advisory append-only log with one entry per write:

kind|fingerprint|len|mtime

The fingerprint is part of the filename and the index entry. The current file format does not embed an additional header inside the archive.

Cache Keys

Every cache key includes:

  • Provider identity bytes derived from input content, not the dataset path.
  • Journal head, so any replay-visible curation change produces a miss.
  • Artifact algo_version, bumped whenever the archive shape or computation changes.
  • Artifact parameters such as dimensionality, channel index, bin size, window, or k-NN.
  • Per-cluster spike fingerprints where applicable.

Per-cluster PC subspaces and isolation metrics include a fingerprint of the cluster’s current spike membership. Correlograms include spike-time fingerprints for the cluster or ordered cluster pair. Cross-correlogram keys are directional: (a, b) and (b, a) are different entries.

Lifecycle

On read, Sorrel builds the key from the current provider identity, journal head, parameters, and cluster inputs. A matching rkyv archive is memory-mapped and bytechecked before use. Corrupt archives are treated as misses and evicted.

On miss, the caller computes the artifact normally and writes the archive atomically through a temporary file plus rename. The next open can then use the archive without recomputing.

When a CurationCommand is dispatched, the journal append changes the journal head. The running session records a bounded in-memory invalidation log with the previous head and affected cluster identities. Sorrel does not evict on every command; it invalidates opportunistically at save and quit so the current session keeps warm caches while editing. The journal-head component still forces newly requested artifacts to miss after the command.

Garbage Collection

CacheStore::open runs a bounded GC pass over the cache root. GC removes:

  • Orphan .rkyv files that are not referenced by INDEX.
  • Entries older than SORREL_CACHE_MAX_AGE_DAYS, default 30.
  • Least-recently-modified entries when total cache bytes exceed SORREL_CACHE_MAX_BYTES, default 4294967296 bytes.

The open-time sweep scans at most 1000 cache files per call to avoid turning a large cache into a visible startup stall. Larger caches finish over multiple opens.

User Operations

Users can clear the cache without losing data:

sorrel clear-cache <dataset>

This removes <dataset>/.sorrel/cache/ and exits. Manual deletion of the same directory is also safe. The command canonicalizes the target and refuses to remove any path that is not a .sorrel/cache directory.

The cache is local rebuildable state. Sorrel does not guarantee cross-machine cache portability, even if copying a dataset also copies .sorrel/cache.

Boundaries

rkyv is a cache-only codec. It must not leak into:

  • Compute kernels (crates/sorrel-compute/). The kernel crate stays dependency-free of rkyv; its types use plain Rust or serde.
  • JSON ingest (crates/sorrel-io/src/{probeinterface,sorting_analyzer,open_ephys}.rs). External-format deserialisation continues to use serde_json.
  • The curation journal (crates/sorrel-data/src/journal.rs, command.rs). The journal codec stays rmp-serde for schema evolution and forward compatibility.

GPU Compute

sorrel-gpu is a small set of wgpu compute pipelines that share the device and queue with eframe’s renderer. When the app is installed onto an eframe::wgpu render state, install_gpu_compute wires up the GPU preprocessor; otherwise the trace path silently falls back to the CPU kernels in sorrel-compute.

Pipelines

ShaderPipeline
cmr_median.wgslPer-sample channel median for common-median referencing on the trace window.
biquad_hp.wgslCausal biquad high-pass filter applied per-channel after CMR.
mean_snippet.wgslMean-snippet extraction along a window for waveform / template overlays.

Why GPU here

The trace view repaints on every pan and resize. CMR + HP filter on a 1-second × hundreds-of-channels window is fast on the CPU, but pinning it to the same wgpu device the renderer already uses lets the downsampled vertex stream stay on-device and avoids the round-trip through host memory.

Fallback

The CPU implementations live in sorrel-compute::cmr and sorrel-compute::filter and are bit-equivalent up to floating-point ordering. Headless tools (sorrel qc) and any host without a wgpu adapter use them directly.

Code signing policy

Free code signing provided by SignPath.io, certificate by SignPath Foundation. (SignPath.io, SignPath Foundation)

Signing is not active yet. The Windows executables of current releases are unsigned, so Windows SmartScreen may show an “unknown publisher” warning. This page states the policy that applies once signing is enabled.

Verify downloads

Check the download’s SHA-256 hash against the release’s SHA256SUMS.txt, which is signed with minisign (key in keys/minisign.pub). Each asset also has a Sigstore .cosign.bundle and .intoto.bundle. See the verification commands for a Windows example.

What is signed

Only artifacts built by the public GitHub Actions release workflow are signed. These are the Windows executables (sorrel.exe, sorrelw.exe), and the zip and standalone files that hold them. The release workflow builds them from a signed release tag on the trunk branch of caniko/sorrel, from the repository’s source, with Nix and a pinned flake.lock. It then submits the build to SignPath. Nothing built on a developer machine is signed, and neither is any artifact from another repository or fork. Third-party dependencies are compiled from source as part of the build; none of them is signed separately.

The signed files carry the product name “Sorrel” and the release version in their version information.

Team roles

RoleWhoWhat they do
Committers and reviewerscanikoChange the source; review every change from non-committers
ApproverscanikoApprove each signing request, one per release, after the release CI

The project has a single maintainer, who holds all roles. Each release signing request is approved by hand in SignPath before anything is signed. The maintainer uses multi-factor authentication on GitHub and SignPath.

Privacy

This program will not transfer any information to other networked systems unless specifically requested by the user or the person installing or operating it.

Sorrel opens network connections only when you ask it to:

  • sorrel share and sorrel join talk to the peer and relay you name.
  • sorrel auto --llm sends cluster summaries to the agent CLI you are logged in to (claude, codex or opencode), or to the Anthropic API with --llm=api.
  • sorrel auto lets uv download its Python packages on first use.

Those services apply their own privacy policies. Signing transmits no user data: SignPath receives only the build artifacts of a release.

Citing Sorrel

If you use Sorrel in your work, cite the release you used. The canonical metadata is CITATION.cff at the repository root; GitHub’s “Cite this repository” button reads the same file.

BibTeX, as cffconvert -f bibtex emits it from CITATION.cff (rename the key):

@misc{YourReferenceHere,
author = {Tartanoglu, Can H.},
month = {11},
title = {Sorrel},
url = {https://sorrel.beloda.co/},
year = {2026}
}

Regenerate it after editing CITATION.cff:

nix shell nixpkgs#uv -c uvx cffconvert --validate
nix shell nixpkgs#uv -c uvx cffconvert -f bibtex

Authorship and funding

Sorrel is independent work. It was written entirely by Can H. Tartanoglu, without institutional affiliation, and funded entirely by the author, with no external funding.

Acknowledgments

Sorrel was developed and evaluated on tetrode recordings from CINPLA, the Centre for Integrative Neuroplasticity at the University of Oslo, sorted with Kilosort 2 and curated in phy. They were used to verify spike rescue end to end and measure its speed and recall, and to evaluate sorrel auto on tetrode geometry. The double-blind curation bench also scores Sorrel against human-curated sorts that the repository identifies only by opaque session ids.

No recording data is distributed with Sorrel. The phy fixtures in release/fixtures/ are synthetic, generated by crates/sorrel-data/tests/tiny_phy_fixture.rs.

Sorrel Improvement Research Dossier

Evidence gathered 2026-06-10 at commit d15ccf3 (trunk, in sync with origin/trunk). Re-verified and extended later the same day at the same commit; the working tree now carries an uncommitted simit badge block in README.md, this dossier plus its SUMMARY.md entry, and a stray untracked docs/.cargo/config.toml (see Current Reality).

This is a historical snapshot. Sorrel now includes NWB and legacy MATLAB rez.mat readers by default. See Backends & Inputs.

Goal And Trigger

The user asked to “improve the sorrel project” with research-first discipline. This dossier records the evidence-backed current state and the improvement workstreams it supports, so future sessions can act without re-deriving the facts.

Current Reality

  • Workspace health is strong. cargo fmt --check, cargo clippy --workspace --all-targets, and cargo test --workspace all pass in the Nix dev shell (nix develop -c …; bare shell has no cargo). 449 tests pass across 8 crates (164 sorrel-compute, 88+34 sorrel-data, 62+18 sorrel-io, 47 sorrel-ui, 11 sorrel-render, 11 sorrel-gpu, 8 sorrel-cache, 5 sorrel bin) with 2 ignored. Doc-tests are nearly absent: 6 in total (4 sorrel-compute, 1 sorrel-data, 1 sorrel-ui; the other 5 crates have zero).
  • The rkyv derived-cache plan set has fully landed (see Existing Plan Status below) but its planning docs are still published in the mdBook under Planning in docs/src/SUMMARY.md.
  • First publish to crates.io has not happened. The crates.io API returns “crate does not exist” for all 8 workspace crate names (sorrel, -io, -cache, -compute, -gpu, -data, -render, -ui; verified 2026-06-10 — note the API requires a real User-Agent header or it returns a rate-limit error). git tag is empty; CHANGELOG.md already declares 0.1.0 (2026-05-25) and RELEASE.md documents the 8-crate publish order.
  • Generated CI has drifted — all 16 simit-managed workflows. simit init ci --workspace --platform forgejo --check (simit 0.16.1) now reports all 8 ci-sorrel-*.yaml and all 8 publish-crate-*.yaml files under .forgejo/workflows/ as differing, and prints the canonical regeneration command itself: simit init ci --platform forgejo --runner atlas --workspace. (An earlier check the same day reported 12 files; 16 is the current number.) pages.yaml is not simit-managed and is not in the drift set. The simit-generated README badge block (uncommitted) correctly reads CI: drift. There is no simit.toml anywhere in the repo, so generation options are inferred on every check.
  • CI already runs on the self-hosted atlas runner. 16 of 17 workflows declare runs-on: atlas (container rust:bookworm); only pages.yaml still runs on codeberg-small with install-nix-action.
  • CI on trunk head is green after retries. Codeberg API shows many failure runs for d15ccf3 on 2026-05-25 followed by success on 2026-05-27 — consistent with the “Retry CI/runners” commits (92d528e, 5661392) pointing at runner flakiness.
  • Publish workflows are tag-fan-out with no cross-crate ordering. Every publish-crate-*.yaml triggers on the same *.*.* tag push, so one 0.1.0 tag fires all 8 concurrently. Each workflow: verifies the tag is GPG-signed by a key in keys/maintainers.gpg, checks tag == cargo pkgid version, runs tests + clippy (all-features and no-default-features), cargo publish --dry-run, then publishes with the CRATES_IO_API_TOKEN secret. Publishing is idempotent: a pre-publish crates.io check skips crates whose version is already live, so re-running failed downstream workflows in dependency order is safe.
  • Release trust roots are in place locally. keys/maintainers.gpg pins exactly one key (0x4623DEA06FDACFE1, Can H. Tartanoglu), which matches git config user.signingkey, and tag.gpgSign is true — a locally created release tag will pass the workflow’s git verify-tag gate.
  • No license files exist anywhere. All manifests declare license = "MIT OR Apache-2.0" via [workspace.package], but there is no LICENSE*/COPYING* file at the repo root or in any crate directory. No crate has a README.md or readme field either, so published crates.io pages would render with no readme.
  • deny.toml exists but nothing runs cargo-deny. Neither the Forgejo workflows nor the flake checks (nix/checks.nix, nix/pre-commit.nix) reference it.
  • README.md is stale. Its workspace table lists 6 crates, omitting sorrel-cache and sorrel-gpu; its keyboard table still says “Undo (V1: stub)” while crates/sorrel-ui/src/app.rs:293-298 implements full undo/redo with per-command status messages, and the in-app hint also advertises redo and save.
  • A stray docs/.cargo/config.toml appeared (untracked). It is byte-identical to the root .cargo/config.toml (harbor-rs-generated, nightly-only flags like -Zthreads/cranelift) — almost certainly dropped by a tool run from inside docs/. It serves no purpose there and should be deleted, not committed.
  • Two IO backends are deliberate stubs: crates/sorrel-io/src/nwb.rs:27 and crates/sorrel-io/src/ks4_rez.rs:25 only expose open_stub.
  • crates/sorrel-py (PyO3 bindings) is intentionally excluded from the workspace and is the only crate with a description field.

Evidence Inventory

EvidenceCommand / fileWhat it proves
Quality gates passnix develop -c cargo fmt --check / clippy --workspace --all-targets / test --workspace (exit 0, 449 passed)No lint/test debt blocking other work
Doc-test gapnix develop -c cargo test --workspace --doc → 6 doc-tests total, 5 crates with 0rustdoc/examples work needed before docs.rs exposure
All 8 names unreservedcurl -A '<real UA>' https://crates.io/api/v1/crates/<name> → “does not exist” for all 8First publish pending; squatting window open on every name
Publish metadata gapgrep -L "^description" crates/*/Cargo.toml → all 8 workspace crates; [workspace.package] has only version/edition/license/repositorycargo publish will hard-fail on every crate
No license filesls LICENSE* and ls crates/*/LICENSE* → nothingDeclared MIT OR Apache-2.0 has no license texts; legal gap before publish
No crate readmesls crates/sorrel-io/, no readme field in manifestscrates.io pages would be empty
No release tagsgit tag → emptyTag-triggered publish workflows never ran
CI drift (16 files)nix develop -c simit init ci --workspace --platform forgejo --check → all 16 ci-*/publish-crate-* differ; suggests --runner atlas regenRegeneration needed; README badge accurate
simit config gaprg --files -g 'simit.toml' → noneCI options inferred, not pinned
Workflows on atlasgrep runs-on .forgejo/workflows/*.yaml → 16× atlas, 1× codeberg-small (pages.yaml)Only Pages still on shared runners
Publish workflow anatomy.forgejo/workflows/publish-crate-sorrel-io.yaml (143 lines)Signed-tag gate, tag==version check, idempotent skip, CRATES_IO_API_TOKEN required, no cross-crate ordering
Signing key matches trust rootgpg --show-keys keys/maintainers.gpg → 0x4623DEA06FDACFE1 == git config user.signingkey; tag.gpgSign=trueLocally signed tags will pass git verify-tag in CI
cargo-deny unenforceddeny.toml at root; rg deny .forgejo/workflows/ nix/ → only clippy --deny warningsSupply-chain gate exists on disk but never runs
Trunk CI green after retriesCodeberg API actions/tasks: failures 2026-05-25, success 2026-05-27 for d15ccf3Runner flakiness, not code failure
Cache plan landedcrates/sorrel-cache/src/{key,store,gc,tests}.rs, cache hit logs in session.rs:120, quality_ext.rs:67, feature_subspace.rs:83, cache/correlograms.rs:210, bench seed_amplitudes_cache.rs, docs/src/architecture/cache.md in SUMMARY.mdAll four phases shipped (commits 38a8e58, 38832c3, 944b50f, d15ccf3)
rkyv containmentrg -l rkyv crates/sorrel-compute/src crates/sorrel-io/src/{probeinterface,sorting_analyzer,open_ephys}.rs → no matchesWhole-set constraint honoured
Invalidation testedcrates/sorrel-cache/src/tests.rs (add_journal_head), session.rs:194,231 (invalidate_caches)Acceptance criterion met
README stalenessREADME.md:39 “Undo (V1: stub)” vs crates/sorrel-ui/src/app.rs:293-298; workspace table vs Cargo.toml membersDocs drift from implementation
Stray cargo configdiff .cargo/config.toml docs/.cargo/config.toml → identical; untrackedAccidental artifact; delete
Stub backendscrates/sorrel-io/src/nwb.rs:27, ks4_rez.rs:25NWB / legacy MATLAB rez.mat ingest unimplemented at the time

Existing Plan Status

docs/src/planning/rkyv-derived-cache/ (4 phases, phase 03 with 3 sub-layers), audited against the working tree:

PhaseClaimStatusProof
01 Cache infrastructuresorrel-cache crate with key/store/GCdonecrates/sorrel-cache/src/, workspace member in Cargo.toml
02 First consumerseed_amplitudes cached + benchdonesession.rs:120 cache-hit log; benches/seed_amplitudes_cache.rs
03/01 PC subspacescacheddonecache/pc_subspace.rs, feature_subspace.rs:83
03/02 Isolation metricscacheddonecache/isolation.rs, quality_ext.rs:67
03/03 Correlogramscacheddonecache/correlograms.rs:210
04 Invalidation, GC, docsreplay hook, GC, cache.mddonesession.rs:194,231, sorrel-cache/src/gc.rs, architecture/cache.md linked in SUMMARY.md
Whole-settests pass; rkyv stays out of sorrel-compute and JSON ingest; invalidation unit-testeddonetest run + rg evidence above

The plan set is complete and ready for formal plan-and-verify verify mode, which on success migrates durable knowledge into stable docs and retires the planning files.

Work That Should Survive

  • RELEASE.md first-publish order (sorrel-io → sorrel-cache → sorrel-compute → sorrel-gpu → sorrel-data → sorrel-render → sorrel-ui → sorrel) and the name-reservation check (cargo search <crate> --limit 1).
  • The derived-cache architecture doc (docs/src/architecture/cache.md) — already in stable docs; planning prose can retire.
  • Global constraint from the plan set that remains binding for future work: rkyv stays out of sorrel-compute and the JSON ingest / rmp-serde journal codecs.
  • The publish-workflow trust model (signed tag verified against keys/maintainers.gpg, tag==version gate, idempotent re-runs) — any CI regeneration must preserve it; confirm after running simit.

Blockers And Missing Artifacts

  • Crate descriptions (publish blocker). All 8 workspace Cargo.toml files lack description; cargo publish refuses such crates. Producer: this repo. Fix: add description (and ideally keywords, categories) per crate or via [workspace.package] inheritance. Validation: nix develop -c cargo publish --dry-run -p sorrel-io reaches packaging instead of metadata error.
  • License texts (publish-quality blocker). license = "MIT OR Apache-2.0" is declared but no LICENSE-MIT / LICENSE-APACHE files exist anywhere, and no crate ships a readme. Not a hard cargo publish error, but a legal/compliance gap for a public release. Producer: this repo (the rust-crate-legal-readme skill owns this domain). Fix: add dual license texts at the root, point each crate at them (license-file is not needed when texts are included via include/symlink convention), and add per-crate readme. Validation: cargo package -p sorrel-io --list shows the license files in the bundle.
  • CI drift (release-trust blocker). All 16 generated workflows, including every tag-triggered publish-crate-*.yaml, differ from simit 0.16.1 output; publishing through drifted generated workflows invites surprises. Producer: simit 0.16.1. Fix: nix develop -c simit init ci --platform forgejo --runner atlas --workspace (the exact command simit’s check output suggests), review diff, commit — the simit-dependent-fixes skill owns this domain. Validation: the --check form reports no differences and the regenerated badge block stops saying drift.
  • CRATES_IO_API_TOKEN secret unverified. The publish workflows hard-fail without it, and repo secrets cannot be read from this environment. Producer: the user, in Codeberg repo settings (Settings → Actions → Secrets). Validation: a workflow_dispatch run of one publish workflow reaches the dry-run step, or the first real tag publish succeeds for sorrel-io.
  • No other foundational inputs are missing; nothing here blocks the research itself.

Risks And Constraints

  • Publish sequencing vs tag fan-out: one 0.1.0 tag fires all 8 publish workflows concurrently, but downstream crates fail dry-run until upstream crates are live (documented in RELEASE.md). The 8-crate order is a hard constraint that CI does not encode. The idempotent already-published skip makes the safe procedure: let the fan-out run, then re-run failed workflows in dependency order (or pre-publish sorrel-io → … manually before tagging).
  • Signed-tag gate: the release tag must be an exact bare semver (0.1.0, no v prefix), must equal the Cargo version, and must be GPG-signed by the single key pinned in keys/maintainers.gpg. Local git config currently satisfies this; a tag pushed from any other machine/key will fail every publish workflow.
  • Crate-name squatting: all 8 names verified unreserved on 2026-06-10; they stay exposed while publish is delayed. RELEASE.md mandates stopping on a taken name rather than auto-renaming.
  • Runner flakiness now scoped to Pages: 16 of 17 workflows already run on self-hosted atlas; only pages.yaml runs install-nix-action on codeberg-small. Moving it to atlas-nix-trusted is possible but subject to Codeberg ToU constraints (see atlas-runner skill). The May retry storm predates the current runner assignment evidence; treat historical flakiness attribution as uncertain.
  • Generated-file discipline: manual edits to .forgejo/workflows/ will re-introduce drift; there is currently no simit.toml at all, so every check infers options — pinning [ci] options (platform, runner) in simit.toml would make --check deterministic.
  • Supply-chain gate unenforced: deny.toml exists but cargo-deny runs nowhere (not CI, not flake checks, not pre-commit). Advisory drift accumulates silently until wired in.
  • Docs publish planning prose: the mdBook publishes the completed plan set (and now this dossier via the uncommitted SUMMARY.md entry); retiring/curating it is a navigation/content change to the public site, not just a repo cleanup.

Candidate Next Steps

  1. Unblock first publish (metadata + legal) — add description/keywords/categories to all 8 crates, add LICENSE-MIT/LICENSE-APACHE texts and per-crate readme wiring; commit. No dependencies; parallel-safe with (2).
  2. Clear CI drift — regenerate with simit init ci --platform forgejo --runner atlas --workspace, add a simit.toml pinning the [ci] options, re-run the badge update, and commit together with the pending README badge block. Should land before tagging 0.1.0 so publish workflows run from generated state. Verify the signed-tag/idempotency logic survives regeneration. Parallel-safe with (1).
  3. Execute first publish — confirm CRATES_IO_API_TOKEN is set in Codeberg secrets; per RELEASE.md order: name checks, cargo package -p <crate> for each, simit changelog release, create the signed 0.1.0 tag, push it, then re-run failed downstream publish workflows in dependency order (idempotent skip makes this safe). Depends on (1) and (2).
  4. Verify + retire the rkyv-derived-cache plan set — run plan-and-verify verify mode; on success retire docs/src/planning/rkyv-derived-cache/ from SUMMARY.md (retire-docs-planning flow). Independent of (1)–(3).
  5. Refresh README.md — fix the workspace table (add sorrel-cache, sorrel-gpu), correct the undo row, add redo/save keys. Independent; trivial. Also delete the stray untracked docs/.cargo/config.toml.
  6. Wire cargo-deny into CI or flake checks — deny.toml already exists; add a job/check so it actually gates. Small; independent.
  7. Feature work: real NWB and legacy MATLAB rez.mat backends — then stubs; the DataProvider trait boundary is the integration point. Larger design work; would warrant its own plan set.
  8. Optional: move pages.yaml to atlas-nix-trusted; grow rustdoc examples/doc-tests (6 today, 5 crates at zero) before docs.rs exposure.

Open Decisions For The User

  • Publish now or later? Metadata and drift fixes are mechanical, but pushing the 0.1.0 tag publishes 8 crate names to crates.io — an outward-facing, irreversible step that should be an explicit call. The CRATES_IO_API_TOKEN secret must also be provisioned by the user before any tag push.
  • Where should the Pages job run — stay on codeberg-small (flaky but zero-config) or move to atlas-nix-trusted (faster, ToU considerations)? CI proper is already on atlas.
  • NWB / legacy MATLAB rez.mat priority — is backend expansion the next major feature, or does curation UX take precedence? This determines whether step (7) gets a plan set now.

Sorrel Scientific Correctness Research Dossier

Evidence gathered 2026-06-10 at commit d15ccf3 (trunk). Scope: the electrophysiology / spike-sorting compute kernels and quality metrics in sorrel-compute and the sorrel-data metric consumers. Every algorithm below was read in full and checked against its canonical reference; several were brute-forced against oracle implementations.

Update (same day, post-audit): the confirmed bugs, the numerical concerns, and most fidelity items below have been fixed in the working tree — Hill contamination N² (with a golden regression test), the cutoff↔completeness contract, GMM logsumexp, the presence-bin off-by-one, the bimodality-coefficient moment inconsistency, filter.rs/drift.rs scope doc-hardening, the CCG even-bins enforcement (#6), NN-isolation in/out balancing (#7, with a background-stability golden test), and removal of the misleading dead dip_statistic alias (#9). See the per-finding [FIXED] markers.

Update 2 (net-new algorithms now implemented): the stretch metric suite has been added and wired in — the real Hartigan & Hartigan (1985) dip (faithful port of Maechler’s diptest C reference, distribution::hartigan_dip, now feeding the split suggester and its UI column), the Llobet et al. (2022) sliding-refractory minimum contamination (metrics::min_contamination_sliding_refractory), LDA d-prime and simplified silhouette (added to IsolationMetrics, the rkyv cache bumped to ALGO_VERSION = 2, and the QC TSV/JSON export), and template SNR (snippets::template_snr). Each ships with property/golden tests. Workspace green (clippy --deny warnings, 461 tests). The only intentionally-skipped item is renaming sliding_refractory_contamination (the windowed-Hill UI plot), which already documents itself honestly.

Goal And Trigger

The user asked to “improve the scientific aspect of the project” with research-first discipline. Sorrel is a manual-curation GUI for spike-sorted electrophysiology; its scientific value rests on the correctness of its quality metrics (contamination, isolation, presence, amplitude cutoff, drift) and its DSP/statistics kernels (filtering, CMR, LTTB, correlograms, GMM, covariance/Mahalanobis). This dossier records an evidence-backed audit of those kernels so a follow-up session can fix the confirmed defects and close the validation gap without re-deriving the formulas.

Current Reality

The numerical infrastructure is unusually solid — covariance uses a two-pass Bessel-corrected estimator, Mahalanobis distance is correct, LTTB matches Steinarsson 2013 bucket-for-bucket, the median is correct under brute-force testing, snippet templates accumulate in f64, and the χ² survival function is a faithful Numerical-Recipes incomplete-gamma implementation. The defects are concentrated in a few metric formulas and one cross-cutting validation gap:

  • The headline quality metric is wrong. refractory_contamination (crates/sorrel-compute/src/metrics.rs:149-171) implements the Hill et al. (2011) estimator with the denominator n · 2 · t_ref / T — missing a factor of N. Hill’s false-positive fraction is f_p ≈ N_viol · T / (2 · t_ref · N²). The code returns a value ~N× too large (for N in the thousands it routinely exceeds 1.0), and the consumer quality.rs:111 computes contamination_score = (1 - raw_contamination).clamp(0,1), so the contamination dimension saturates to 0 for essentially every real cluster. This is the single most consequential scientific defect.

  • No test pins any metric’s numeric value. There is no golden-value or phy/SpikeInterface-parity test for any metric magnitude. crates/sorrel-data/tests/synthetic_ground_truth.rs checks only the directional behaviour of the merge/split suggesters (merges not empty, dip_z > 2.0, score > 0.5); the in-crate unit tests assert sanity bounds like c > 0.0 (metrics.rs:354-361). Nothing would have caught the Hill scale error, and nothing guards the other metrics against future regressions.

  • A consumer contract is internally inconsistent. quality.rs:119 computes completeness_score = 1 - raw_cutoff*2, assuming amplitude_cutoff maxes at 0.5 — but distribution.rs:204-280 permits its return to climb toward 1.0 (only a saturating clamp, no 0.5 cap like the Allen routine). When cutoff > 0.5, completeness goes negative and clamps to 0.

  • Several functions are named/documented for an algorithm they do not implement. dip_statistic returns the bimodality coefficient, not Hartigan’s dip (distribution.rs:301, self-disclosed); sliding_refractory_contamination is windowed-Hill, not the Llobet et al. (2022) minimum-contamination sliding estimator its name evokes (drift.rs:102); amplitude_cutoff’s doc claims equivalence to “Hill 2011 §3.2” but it is a coarse mirror-tail approximation (distribution.rs:205); the drift.rs metrics are amplitude-QC heuristics, not Kilosort2.5/dredge spatial-motion estimation.

  • No PCA exists in-tree. PC features are precomputed upstream (Kilosort) and only extracted in feature_subspace.rs; there is no eigendecomposition/SVD/whitening anywhere. Any roadmap item assuming sorrel computes its own feature subspace is mistaken.

Evidence Inventory

EvidenceFile:line / commandWhat it proves
Hill contamination missing N²metrics.rs:166 denom = n * 2.0 * rp_s / total_sReturns N_viol·T/(2·t_ref·N), ~N× the Hill fraction N_viol·T/(2·t_ref·N²)
Contamination dimension deadquality.rs:111 (1.0 - raw_contamination).clamp(0,1)Inflated raw value saturates score to 0 for real clusters
Cutoff↔completeness contract mismatchquality.rs:119 1.0 - raw_cutoff*2.0 vs distribution.rs:279 clamp to 1.0completeness_score can be driven negative then clamped to 0
No numeric metric testsrg 'refractory_contamination|isolation_distance|l_ratio|amplitude_cutoff' crates/**/tests → none assert valuesNo golden/parity coverage; scale bugs invisible
Suggester tests are directional onlysynthetic_ground_truth.rs:177-252 (!merges.is_empty(), dip_z > 2.0)Validates pipeline direction, not metric magnitude
Unit tests assert sanity onlymetrics.rs:354-361 (assert!(c > 0.0))Would not catch an N× scale error
presence last-bin off-by-onemetrics.rs:188-191 (idx < n_bins drops idx==n_bins); same drift.rs:81-85Boundary spike at t==total silently dropped; biases ratio low
GMM E-step no logsumexpgmm.rs:96-104 linear-domain pa+pb; resp=0.5 on total==0.0Far-outlier underflow fabricates a 0.5 posterior, biasing M-step
BC mixes corrected/uncorrected momentsdistribution.rs:116-130 corrected 3(n-1)²/((n-2)(n-3)) with uncorrected g1,g2 (lines 65,73)Sarle BC internally inconsistent for small n
CCG even-bin assumptionccg_analysis.rs:54 half = bins/2 vs correlograms.rs:277 ceil(2*window/bin)Bin count even only if 2*window % bin == 0; else zero-lag center off by half a bin
CCG right-edge asymmetrymetrics.rs:46-49 dt==+max_lag → idx=bins clamped to bins-1Extreme positive lag folded into last bin; one-bin asymmetry vs -max_lag
dip_statistic ≠ Hartigan dipdistribution.rs:301-310 returns bimodality_coefficientName/scale mismatch (Hartigan dip ∈ ~[0,0.25]; BC ∈ [0,1])
sliding_refractory ≠ Llobetdrift.rs:102-143 re-applies (buggy) Hill per windowNot the Llobet 2022 min-contamination estimator
NN isolation unbalancedmetrics_iso.rs:194-258 strides only in-cluster queries, never subsamples backgroundDeviates from balanced Chung 2017 / SpikeInterface nn_hit_rate
Causal display filterfilter.rs:79-99 single forward-pass DF2T biquad; only caller sorrel-render/src/buffers.rs:209-226Group delay OK for display; must never feed spike-time measurement
No PCA in-treerg 'eigen|jacobi|svd|whiten|principal_component' crates/ → none; feature_subspace.rs:153,175 extracts precomputed feats[pc*n_chans+ch]PCs come from upstream sorter
Covariance correctlinalg.rs:65-91 1/(n-1), two-pass, symmetrizedConfirmed-correct sample covariance
Mahalanobis correctlinalg.rs:170-186 (x-μ)ᵀΣ⁻¹(x-μ), .max(0.0) guardConfirmed correct
LTTB correctlttb.rs:39-70 brute-forced vs Steinarsson 2013 oracle, all (n,threshold)<2000Bucket boundaries + triangle area exact; no underflow/div-by-zero
Median correctcmr.rs:38-53 brute-forced 200k random arrays vs sort oracleselect_nth_unstable tie-handling exact for even n
L-ratio correctmetrics_iso.rs:179-181 Σ χ²-sf(D²,df=d) / N_inMatches Schmitzer-Torbert 2005 (initially suspected, confirmed correct)
Isolation distance correctmetrics_iso.rs:173-178 N-th nearest non-cluster Mahalanobis², guarded n_out≥n_inMatches Schmitzer-Torbert 2005

Findings By Severity

Confirmed bugs

  1. [FIXED] Hill contamination missing N² (metrics.rs). Now f_p = viol * total_s / (2.0 * rp_s * n * n) accumulated in f64, clamped to [0, 1] (the f_p > 0.5 “no real root” case saturates to 1.0). Doc rewritten to state the estimator and the N² rationale. Guarded by the new golden test refractory_contamination_recovers_known_fraction, which injects a known violation count and asserts the recovered fraction matches the analytic Hill value — it fails under the old ÷N formula. Was highest priority — the only finding that corrupted a shipped composite dimension.
  2. [FIXED] completeness_score contract. amplitude_cutoff now clamps to [0, 0.5] (Allen convention: a hard low-amplitude cutoff masks at most half the distribution), so the consumer’s 1 - cutoff*2 rescale in quality.rs is valid and bounded. Both docs note the shared 0.5 ceiling.

Numerical concerns

  1. [FIXED] GMM E-step lacks logsumexp (gmm.rs). E-step and final log-likelihood now run in the log domain via log_normal: responsibility is 1/(1+exp(lb−la)) and the per-point LL is the logsumexp of the two log-weighted densities — no more fabricated resp=0.5 on underflow.
  2. [FIXED] Presence-bin off-by-one (metrics.rs). presence_ratio now clamps the bin index to n_bins-1 so a spike at the recording end is counted, not dropped. (drift.rs::presence_cv uses the same pattern but its idx < n_bins guard is harmless for a CV of counts; left as-is.)
  3. [FIXED] Bimodality coefficient mixes corrected/uncorrected moments (distribution.rs). Now converts the uncorrected g1/g2 to the bias-corrected G1/G2 that the SAS small-sample correction term assumes, so the conventions are consistent for small clusters.
  4. [FIXED] CCG even-bins convention. The one path feeding analyse_refractory_dip (suggest.rs) now rounds ccg_bins up to even via (n + 1) & !1, so zero lag always lands on the half-1/half boundary and the refractory window [half-r, half+r) stays symmetric; analyse_refractory_dip gained a debug_assert on even bins to catch any future caller. (The extreme-lag right-edge clamp in cross_correlogram affects only pairs at exactly ±max_lag samples — far from the central dip — and was left as-is to avoid churning a well-tested path for a negligible-impact edge case.)

Fidelity / documentation mismatches

  1. [FIXED] NN isolation unbalanced (metrics_iso.rs). Now builds a balanced neighbour pool — every in-cluster spike plus a deterministically strided background subsample sized to ~n_in — before counting k-NN hits, matching SpikeInterface’s balanced nn_hit_rate. Guarded by nn_isolation_is_stable_under_background_growth, which asserts the score barely moves when the background grows 10×.
  2. [ADDRESSED] Llobet sliding-refractory minimum now implemented. The genuine Llobet et al. (2022) minimum-contamination-over-t_ref estimator is added as metrics::min_contamination_sliding_refractory (sweeps candidate refractory periods, returns the smallest Hill fraction). The original sliding_refractory_contamination (a time-window sweep for the UI plot) is retained and unchanged — it honestly documents itself as windowed-Hill; only a possible rename remains a user decision.
  3. [ADDRESSED] Real Hartigan dip now implemented. The misleading dead dip_statistic alias was removed, and a faithful port of Hartigan & Hartigan (1985) — Maechler’s diptest C reference — was added as distribution::hartigan_dip ([0, 0.25], 0 for unimodal). It now corroborates the bimodality coefficient in the split suggester (amp_dip field, blended via max) and shows in the UI split table.
  4. amplitude_cutoff doc overclaims Hill-2011 equivalence (distribution.rs:205). Soften the doc and/or implement the Allen/Hill reflected-Gaussian-tail estimator with the 0.5 cap.
  5. [FIXED] filter.rs causal display filter — doc hardening. Module doc now states the single-pass biquad has frequency-dependent group delay and must never feed a spike-time/latency/alignment path (those need zero-phase filtfilt).
  6. [FIXED] drift.rs scope. Module doc now states these are per-cluster amplitude-QC indicators, not a Kilosort/dredge spatial motion estimate.

Confirmed correct (do not “fix”)

Covariance (N−1, two-pass, symmetrized), Mahalanobis, χ² survival via incomplete gamma, LTTB, median tie-handling, snippet f64 template accumulation, ACG zero-lag self-exclusion, L-ratio normalization (÷N_in, df=d), and isolation-distance N-th-neighbor selection were all verified against their canonical definitions (several by brute force). The prior dossier’s claim that PCA/eigensolvers exist is wrong — none do.

Work That Should Survive

  • The Hill-contamination correction and its f64 N² requirement — this is the load-bearing fix.
  • The binding constraint that filter.rs is display-only: any future spike-time/latency feature must add a separate zero-phase filtfilt path.
  • The fact that PC features are upstream-provided, not computed here — governs any feature-space metric work.
  • The metric→score consumer contracts in quality.rs (each *_score is a (1 - raw).clamp(0,1)-style transform of a raw metric); these must stay in agreement with each raw metric’s documented range.

Blockers And Missing Artifacts

  • No reference oracle for metric values (validation blocker). To prove a metric is correct (not just self-consistent), a golden dataset with known contamination/isolation is needed. Producer: this repo — extend synthetic_ground_truth.rs with clusters of known injected contamination fraction and assert the recovered f_p matches within tolerance; and/or port a handful of SpikeInterface/phy metric outputs on a small fixture as parity golden values (mirroring how phy_parity.rs already pins curation semantics). Validation: those tests fail on the current Hill formula and pass after the N² fix.
  • No other foundational inputs are missing; all source is present and builds/tests green in the Nix dev shell.

Risks And Constraints

  • Fixing the Hill formula changes user-visible scores. Clusters that currently show contamination_score = 0 will move to meaningful values; any saved thresholds, screenshots, or user expectations calibrated against the broken metric will shift. This is a behaviour-changing correctness fix, not a silent refactor — note it in CHANGELOG.md and ideally bump a metrics version if one is exposed.
  • Metric changes ripple into the merge/split suggesters. The CCG binning and contamination fixes feed analyse_refractory_dip and the suggesters; re-run synthetic_ground_truth.rs and confirm the directional assertions still hold after each change.
  • f32 vs f64 discipline. The N² term and any long count accumulations must be f64; several metrics currently take len() as f32 early (metrics.rs:158).
  • Ordering: land the validation harness (or at least the known-contamination golden test) alongside or before the Hill fix so the fix is proven, not just plausible.
  • Pre-publish timing. These are scientific-correctness fixes; landing them before the first crates.io publish (see the companion sorrel-improvement-research.md dossier) avoids shipping a 0.1.0 with a known-wrong contamination metric.

Candidate Next Steps

  1. [DONE] Fix Hill contamination + add a known-contamination golden test — fixed in metrics.rs with the golden test refractory_contamination_recovers_known_fraction (placed in the crate unit tests rather than synthetic_ground_truth.rs, so it runs without a Session fixture).
  2. [DONE] Reconcile the cutoff↔completeness contract — amplitude_cutoff capped at 0.5 in distribution.rs.
  3. [DONE] Add logsumexp to the GMM E-step — gmm.rs.
  4. [DONE] Fix presence-bin off-by-one and the BC moment inconsistency — metrics.rs presence clamp, distribution.rs bias-corrected G1/G2.
  5. [DONE] Settle the CCG binning convention — suggest.rs rounds ccg_bins up to even; analyse_refractory_dip asserts even bins. Suggester tests re-run green.
  6. [DONE] Remove the misleading dip_statistic alias (dead code). The amplitude_cutoff doc was also corrected (0.5 cap) under step 2. sliding_refractory_contamination left as-is (honest Hill doc).
  7. [DONE] Balance NN isolation sampling (metrics_iso.rs) — in/out balanced pool, with the nn_isolation_is_stable_under_background_growth golden test.
  8. [DONE] Harden filter.rs / drift.rs rustdoc to scope them (display-only; QC-only).
  9. [DONE] Fill the missing standard metrics — the real Hartigan dip (hartigan_dip), Llobet sliding-refractory minimum (min_contamination_sliding_refractory), LDA d-prime and simplified silhouette (on IsolationMetrics, cache ALGO_VERSION = 2, QC export), and template SNR (template_snr). The dip feeds the split suggester and its UI column. All ship with tests.

Open Decisions For The User

  • Rename sliding_refractory_contamination? It is the windowed-Hill UI plot (honestly documented), distinct from the new min_contamination_sliding_refractory (Llobet). The name is still slightly suggestive of Llobet; rename for clarity, or leave it since the UI relies on it and the doc is honest?
  • Wire d-prime / silhouette into the composite quality score and UI? They are computed, cached, and exported, and already contribute to IsolationMetrics::score(). A dedicated UI display (beyond the QC export) is optional polish.
  • How far to chase phy/SpikeInterface numeric parity? The metrics are algorithmically faithful and property-tested; pinning exact values against SpikeInterface fixtures is a larger, optional effort. Where is the line for 0.1.0?

phy parity

Sorrel aims to do everything phy’s TemplateGUI does. The target is cortex-lab/phy master (v2.1, 2026). This page lists every phy view, action and shortcut against its Sorrel equivalent. Each row has one of these statuses:

  • done — available now. The test column names the check that covers it.
  • planned — not built yet.
  • excluded — deliberately left out; the row says why.

Views

phy viewSorrelStatusTest
FeatureViewFeatures: phy’s 4×4 grid (best channels 0/1 × PC A/B, time on the diagonal), 2500 grey background spikes, 2500 shown per clusterdonefeature_view::tests, ui_states::features_grid_lasso_split
FeatureView without pc_features.npyphy hides the view. Sorrel fits two temporal PCs on raw peak-channel snippets and projects the shown spikes, then every lassoed spike before a splitdoneui_states::features_computed_pcs, linalg::tests::top_eigenvectors_recover_known_basis
TemplateFeatureViewTmpl features: with two clusters selected, each spike projected on both clusters’ templates (template_features.npy / template_feature_ind.npy), grey background, Ctrl+click lasso and kdoneui_states::template_features_two_clusters
WaveformViewWaveformsplanned
AmplitudeViewAmplitudes: template, feature (the FeatureView’s Alt+clicked dimension) and raw types (a / Shift+a), grey background spikes on the peak channel, a per-cluster histogram, the polygon lasso, the v2.1 Alt+right-drag threshold split (orange preview), Alt+click to seek. The template-feature type comes with TemplateFeatureView.doneamplitude_view::tests, ui_states::amplitudes_threshold_split
CorrelogramViewCCGplanned
ISIViewISIplanned
FiringRateViewRate: phy’s bin count (default 200, :frn, header field) and the v2.1 time unit (s, min, h)done
TraceViewTrace; shortcuts in the trace table belowdoneapp::tests::alt_pgdn_centres_the_trace_on_the_selections_next_spike
TraceImageViewTrace image (tab beside Trace): the trace window as a channels × pixels image of the signed voltage, following the Trace window, HP/CMR and origindonetrace_image::tests, ui_states::spike_data_and_trace_image
ProbeViewProbedone
RasterViewRaster: click seeks the trace, Ctrl+click selects the row’s cluster, Shift+click adds or removes itdone
TemplateViewTemplates: every cluster’s template on its peak channel in table order, selection outlined; click selects, Ctrl/Shift+click addsdone
ClusterScatterViewScatter: one point per cluster; x / y / size from amp, depth, fr, n_spikes, ch (defaults amp × depth, size log fr) with log toggles; click selects, Shift+click adds, Ctrl+click lasso selects every cluster inside; :csx / :csy / :css. Shift+wheel cycles the colour scheme. Drag pans, the wheel zooms, double-click resets.doneui_states::cluster_scatter_dense, cluster_scatter::tests
Spike*ViewSpike data: every spike_<name>.npy (phylib spike attributes), 1-D against time or 2-D as x vs y, grey background, Ctrl+click lasso and kdonephy_parity::phy_spike_attributes_and_reorder, ui_states::spike_data_and_trace_image
ClusterViewCluster tableplanned
SimilarityViewSimilar; cluster similarity is phy’s max over both clusters’ templatesplannedphy_parity::phy_cluster_similarity_is_max_over_templates
HistogramViewPlugin base class; the built-in histograms are ISI and Rateexcluded: plugin API
IPythonViewScripting goes through sorrel-py and the sorrel mcp JSON-RPC API instead of an in-window consoleexcluded

FeatureView behaviour

phySorrelStatusTest
Features read by real channel through pc_feature_ind[spike_template]Session::pc_featuredonephy_parity::phy_feature_view_channels_and_lookup
A selected spike whose template lacks the channel is drawn at 0samedone
Channels: first cluster’s best, those shared by every selected cluster firstSession::best_channelsdonephy_parity::phy_feature_view_channels_and_lookup
c toggles automatic channel selectionc, or the fixed checkbox in the headerdone
Ctrl+click (left/right) on a Waveforms channel sets channel 0/1FeatureViewState::edit_channels(SetA/SetB), called from the Ctrl+click on a Waveforms channeldone
ISI violators brush, split what-if and merge ghosts (Sorrel extra): clicking the ISI refractory band brushes both spikes of every pair under 1 ms; a lasso / k-means brush on one selected cluster previews its split (preview_split: ISI dashed inside / dotted outside, Quality “if split” delta rows, Waveforms dashed / dotted means); a hovered merge candidate adds a grey dashed mean in Waveforms and a ghost row and column in CCG—doneisi_view::tests::violators_include_both_members_once, isi_view::tests::split_target_needs_a_part_brush_and_a_remainder, preview::tests::preview_split_matches_an_applied_split, ui_states::xtalk_isi_whatif, ui_states::xtalk_isi_tooltip
Polygon lasso: Ctrl+click adds points, Ctrl+right-click clears, k splitssame; Esc also clears. Sorrel extras: Ctrl+drag draws a freehand lasso (Ramer-Douglas-Peucker, at most 64 nodes), and on a closed lasso a node drags, a double-click on an edge inserts a node, a right-click on a node deletes it (min 3); hovering shows the node or a ghost “+”donelasso::tests, ui_states::features_lasso_freehand_and_edit
k-means auto-lasso (Sorrel extra): the k-means button (or :km [k|auto]) clusters the first selected cluster in its 4 PC columns (rayon, off the UI thread; k: auto picks 2–5 by silhouette), wraps the lasso around the smallest part in the cell that separates it best, highlights the exact members, and shows a chip per part; auto-run refits whenever the features change unless you drew your own lasso. A live “N spikes · M nodes · K splits” badge sits under every closed lasso.—donefeature_view::tests::kmeans_auto_lasso_wraps_the_small_blob, ui_states::features_lasso_drawing_and_kmeans, kmeans::tests::parallel_runs_are_identical_on_large_inputs
k-means collision evidence (Sorrel extra): every projection counts the other parts’ and selected clusters’ spikes inside the previewed part’s hull (green 0, amber ≤ 15%, red above); the part’s hull is dashed in the other projections. Evidence is shown on the real plots, not a replacement projection navigator.—donefeature_view::tests::cell_hits_count_other_parts_and_clusters_inside_each_hull, feature_view::tests::collision_colours_follow_the_15_percent_rule, ui_states::features_kmeans_collision
Full Phy-style Features matrix: all 16 projections for A/B in a fixed 4×4 arrangement, fitted to the available width and height at narrow, default, wide and maximized sizes. No navigator or single-cell layout. 3D remains an explicit inspection mode.—doneui_states::tetrode_feature_grid_is_complete_at_narrow_default_wide_and_maximized_sizes, ui_states::features_compact, ui_states::pane_maximized, ui_states::pane_popout
Channel set (Sorrel extra): Features works on a set of up to 8 channels (default the selection’s best four; feature_view::MAX_SET), edited by Shift+click in Waveforms or the toolbar chips; A/B are the set’s first two and follow the best-separating channel pair unless fixed with cFeatureViewState::edit_channelsdonefeature_view::tests::edit_channels_keeps_two_to_max_and_swaps_like_phy, feature_view::tests::separation_ranks_the_separating_pair_first
Probe channel picker (Sorrel extra): set rings, A/B badges and highlight rings on the probe; Shift+click toggles a site in the Features set, Ctrl+click / Ctrl+right-click set A / B—doneviews::probe_tests, ui_states::xtalk_probe_set
Merge / history ghosts (Sorrel extra): hovering a Similar or Suggest merge row writes a merge ghost and shows the preview_merge delta; hovering a History row writes a history ghost—donesimilarity_view::tests, ui_states::xtalk_features_ghost, ui_states::xtalk_history_ghost
Alternatives strip (Sorrel extra): the six best-separating pairs over the set’s dims as mini scatters; a click promotes one to A/B and focuses its grid cell, armed first when a lasso would be droppedfeature_view::alternativesdonefeature_view::tests::promotion_maps_every_pair_to_a_grid_cell, ui_states::features_alternatives
Features 3D (Sorrel extra): the 3D toggle shows the points in any three dimensions of the channel set (time and PC1/PC2 per channel) behind an orbit camera, every triple ranked by silhouette (clusters, else k-means parts, else variance; top 20 and “show all”), the focused 2D plot’s pair pinned by default (chip, third-axis list), the chosen triple’s channels highlighted in Waveforms; convex hulls per cluster (filled for Auto, wireframe for Sorrel-made), a dashed parent hull for split children, the lasso extruded as a prism and the k-means part’s hull. Inspection only.—donefeature_view3d::tests::every_triple_of_the_set_is_scored_best_first, feature_view3d::tests::pinning_keeps_the_triples_holding_the_pair_and_ranks_the_third_axis, feature_view3d::tests::the_chosen_triple_survives_a_rerank_and_falls_back_when_its_dims_vanish, feature_view3d::tests::triple_channels_dedupe_and_leave_out_time, feature_view3d::tests::prism_needs_both_lasso_dims_in_the_triple, convex_hull_3d tests, ui_states::features_3d, ui_states::features_3d_kmeans_prism, ui_states::features_3d_pinned, ui_states::features_3d_maximized, wgpu_scene3d GPU tests
Features 2D cross-talk (Sorrel extra): a closed lasso or previewed k-means part writes the spike brush (only when it changes; clearing the lasso clears the brush only if Features wrote it); brushed spikes drawn in ink in every cell and mini; the 6 px hover pick writes the shared hover and every cell rings the hovered spike; Alt+click on a spike seeks the Trace (Alt+click elsewhere still picks the amplitude feature); spikes in the Trace window ringed (≤ 200 per cluster); Shift+drag a time cell sets the time brush (band on the axis, outside spikes fade to 0.2 alpha); ⚙ “colour by cluster / time / depth” with a ramp legend; Similar merge ghost as grey points “cN (ghost)”—donefeature_view::tests::brush_is_written_only_when_its_key_changes, feature_view::tests::nearest_spike_picks_the_closest_within_reach, feature_view::tests::time_brush_fades_or_hides_spikes_outside, feature_view::tests::colour_ramp_runs_viridis_end_to_end, feature_view::tests::trace_window_is_a_range_of_local_indices, ui_states::xtalk_features_brush, ui_states::xtalk_hover_spike, ui_states::xtalk_amplitudes_ink
Features 3D cross-talk (Sorrel extra): brushed spikes in ink, the time brush fading or hiding spikes, hover ring and pointer pick (6 px), Similar ghost hull, History “before #n” hulls (Session::pre_edit_spikes), point colour by time or depth, and a depth space axis ranked with the PCs.—donefeature_view3d::tests::space_dims_join_the_triples_and_rank_by_separation, feature_view3d::tests::brushes_ink_fade_and_hide_spikes_in_the_scene, feature_view3d::tests::a_new_brush_or_time_range_changes_the_scene_key, feature_view3d::tests::the_nearest_candidate_within_reach_is_picked, session::tests::pre_edit_spikes_match_the_memberships_before_each_edit, ui_states::xtalk_3d_space, ui_states::xtalk_history_ghost
Time-axis cross-talk (Sorrel extra): the Amplitudes lasso or threshold, the Spike data lasso and the Tmpl features lasso are the app-wide spike brush (ink points in Amplitudes, Spike data, Tmpl features, Drift, ink ticks in Raster and Trace); hovering a spike in Amplitudes or Spike data rings it and draws its time as an accent line in Raster, Rate, Drift, Amplitudes and Trace; a plain click on a Trace tick picks that spike (sticky hover for Features); Shift+drag along Amplitudes, Rate, Drift or Raster sets the time range (band, outside points fade)—donewidgets::brush_tests, ui_states::xtalk_time_brush
Split loads every spike of the lassoed clusterssame, for computed PCs toodoneui_states::features_computed_pcs
Feature scaling (Ctrl+wheel), marker size (Alt+wheel), pan/zoom, resetsame; double-click resetsdone
Alt+click a subplot sets the AmplitudeView feature dimension (left = x, right = y)samedone
Custom grids (set_grid_dim)—excluded: plugin API

Every view

phySorrelStatusTest
toggle_auto_update (freeze a view)tab right-click → Freeze on this selection (🔒 in the title)done
screenshottab right-click → Save screenshot, a PNG in <dataset>/.sorrel/screenshots/ (phy: ~/.phy/screenshots)done
pan / zoom / resetdrag, wheel, double-click on Features, Amplitudes, Scatter, Tmpl features and Spike datadonepanzoom::tests
pan / zoom on Raster, Rate, TemplatesRaster: drag, wheel, double-click (time and rows). Rate: the same in time, re-binned over the visible span. Templates: the wheel scrolls, Ctrl+wheel or pinch zooms the boxes, double-click resetsdoneui_states::raster_and_rate_zoomed

Supervisor actions

phy actionKey (phy and Sorrel)StatusTest
mergegdoneintent::tests::phy_supervisor_keys
splitkdoneui_states::features_grid_lasso_split
label (custom label column, saved as cluster_<name>.tsv)l, :l name valuedonesave::tests::custom_labels_write_phy_tsvs_and_undo
move best / similar / all to good, mua, noise, unsortedAlt / Ctrl / Ctrl+Alt + g m n udoneintent::tests::phy_supervisor_keys
advance after a move (_after_move)—done
next / previous similarSpace / Shift+Spacedoneselection::tests::similar_part_steps_and_resets_like_phy_wizard
skip noise and MUA while stepping (v2.1, default on)always ondone
next / previous best, first / last↓ / ↑, Home / Enddone
select first similarCtrl+Space (first 15)done
unselect similarBackspacedone
reset wizardCtrl+Alt+Spacedone
undo / redo (sorrel keeps undone edits as branches; see the History pane)Ctrl+Z / Ctrl+Shift+Z, Ctrl+Ydonesession::tests::edit_after_undo_branches_and_checkout_crosses_branches
save (also writes cluster_info.tsv)Ctrl+Sdonesave::tests::custom_labels_write_phy_tsvs_and_undo
split_init (split by original template)Shift+Ctrl+Kdonephy_parity::phy_split_init_restores_one_cluster_per_template
toggle_spike_reorder (spike_reorder.npy on the Feature, Amplitude and Spike-data time axes)Ctrl+Rdonephy_parity::phy_spike_attributes_and_reorder
colour fields (none, cluster, group, depth, fr) for unselected clusters in Raster, Scatter and Templates:cf name, Shift+wheeldonetheme::tests::colour_schemes_match_phy_fields
colormaps:cmexcluded: one sequential map (viridis); diverging and rainbow on request
merge mode (v2.1): stage the selection, add similar candidates, G merges, V cancels and restores; labels blocked while active. Dragging rows between views and undo restoring the workspace are not built.vdoneapp::tests::merge_mode_stages_candidates_and_cancel_restores
merge propositions (v2.1, curation.json merges)the Proposals pane (Enter accepts, Delete rejects)in progress (sorrel-f6 lane)
cluster table filter / sort:f expr, :s coldone
help, quith (also ?, F1), Ctrl+Qdone

Snippets

phy snippetStatusTest
:g, :k, :c 1 2 3 (ranges 3-7)donesnippets::tests::parses_phy_snippets
:l name value (group moves the selection)donesnippets::tests::parses_phy_snippets
:tg time, :ts windowdonesnippets::tests::parses_phy_snippets
:csx, :csy, :css (ClusterScatter axes)donesnippets::tests::parses_phy_snippets
:f expr, :s coldone
:frn n, :cf fielddonesnippets::tests::parses_phy_snippets
:wn, :cb, :cw, :cr, :isi…Waveforms / CCG / ISI lane (sorrel-f6)
:frb seconds (bin size)donesnippets::tests::parses_phy_snippets
:frmin, :frmax (x range, seconds; no value resets)donesnippets::tests::parses_phy_snippets, prefs::tests::rate_x_range_clamps_and_falls_back_to_the_recording

Trace shortcuts

phySorrelStatus
Alt+← / Alt+→ previous / next windowsamedone
Alt+Home / Alt+Endsamedone
Alt++ / Alt+- narrow / widensamedone
Alt+PgDn / Alt+PgUp next / previous spike of the selection, Alt+T go tosame (Alt+T opens :tg)done
Alt+O origin, Alt+S every cluster’s spikes, Alt+L labels, Ctrl+Alt+↑/↓ gainsamedone
Ctrl+click a spike selects its clusternearest spike within 1 ms (phy also weighs the clicked channel)done

Command line

phySorrelStatus
phy template-gui params.pysorrel open <DATA_DIR> (Phy, SortingAnalyzer, NWB, MATLAB rez.mat)done
phy template-describe params.pysorrel describe <DATA_DIR>done
--clear-cachesorrel clear-cachedone
kwik-gui, trace-gui, alf-convert—excluded: not template-gui

Differences that stay

  • SortingAnalyzer PCs. SpikeInterface’s principal_components extension only holds the random_spikes subset (at most 500 spikes per unit; on one real 0.105 analyzer, 32 425 of 210 884 spikes). A lasso split on it would leave every other spike behind. Sorrel therefore computes its own PCs for SortingAnalyzer folders, which covers every spike.
  • Missing PCs. phy shows no FeatureView without pc_features.npy; Sorrel computes PCs instead.
  • Custom labels in curation.json. These are written as name=value tags, not as SpikeInterface label keys.
  • Plugins and the IPython console. Both are excluded. Scripting goes through sorrel-py and sorrel mcp.

Clustering brainstorm: speed and hard-to-find waveforms

Session 2026-10-28. The ideas, scores and verdicts below are the brainstorm’s proposals, not findings; scores are decision aids. What was built afterwards, and how it measured, is in the decision log.

Focal question. Which new Sorrel features would make re-clustering much faster and recover units or spikes that Kilosort 4 leaves behind? The target cases are low-amplitude units, units buried in MUA or noise, overlapping spikes, units split by drift, bursting units and sparse units.

Participants (all AI).

IDRoleModelStage
P01Statistics / ML algorithmsOpusindependent
P02GPU / systemsOpusindependent
P03Curator workflowHaikuindependent
P04Cross-field transferHaikuindependent
R1Adversarial review and raterOpusreview
R2Blind raterHaikureview
L1Prior-art check (web search)Haikuevidence
P05Post-evidence ideationHaikupost-check

Round 1 produced 44 ideas, grouped into 11 clusters by mechanism. No human participant generated or rated ideas. That is the main missing perspective.

Main result

Most recall ideas share one unmet prerequisite, so they should be ordered by dependency, not by score.

  1. Sorrel cannot yet do residual work correctly. It never loads whitening_mat*.npy, spike_positions.npy or the KS4 drift shifts. The templates live in whitened, drift-corrected space, but the trace mmap is raw. Every subtraction or matched-filter idea (C1, C2, C3, C7) is therefore wrong until those files are loaded. (Located evidence: grep of crates/, verified by the facilitator.)
  2. Kilosort 4 already runs template pursuit and resolves most collisions. A native Sorrel detector only adds value below KS4’s threshold, and false positives concentrate there. So every detector must beat a simple baseline first: rerunning KS4 on a channel and time window with a lower threshold.
  3. Recall cannot be measured without hybrid injection (C8). Injection comes first, because it is how the gate below gets checked.
  4. Sorrel’s unique advantage as a curator is the human in the loop, the journal of decisions, interactive views and the ability to compare sorters. The strongest new ideas from the post-evidence round (P05) use these, not raw signal processing.

Gate (applies outside the scores). A recall feature may only emit journaled proposals the curator reviews, each with a null or false-positive estimate. Nothing applies automatically. This rules out “batch-accept p > 0.95” and “auto-accept the tail” (C9) as originally proposed.

Proposed sequence (facilitator proposal, not a decision)

StepWhatWhy firstSmallest check
0Instrumentation: per-operation timestamps and view dwell time in the journal (R1-new-5)Speed claims must be measured, not assertedReplay a journal and report the median time per decision
1Mergeable statistics and per-cluster cache keys (P02-02)Exact, low-risk speed win. Today every cache key includes journal_head, so any edit invalidates everythingFixture assert that CCG(A∪B) = ACG(A) + ACG(B) + CCG(A,B) + CCG(B,A); measure latency after a merge
2Load whitening, spike positions and drift shifts (R1-new-1)Prerequisite for C1, C2, C3 and C7Whitened mean snippet matches templates.npy for a unit
3Virtual hybrid injection (C8) through a DataProvider wrapper; never write to the .datMeasures recall; calibrates C1/C2 thresholds3 templates at 3 amplitudes are recovered by the mean-snippet shader
4Cheap recall and precision proposals: drift-aware amplitude_cutoff per time bin (R1-new-4); ambiguous-assignment proposals from template_features.npy (R1-new-3); burst-aware split test (P01-04) with connection tagging (P05-02)Reuse existing code; show where spikes are lost before building detectorsCount GMM split suggestions that disappear after regressing amplitude on ISI
5Drift-fragment merge score (P01-03)Highest-scoring recall cluster; pairwise and reversibleCurator blind-rates the top 20 pairs against 20 random pairs
6Detectors on the residual (C1, then C2), compared against a KS4 window rerun (R1-new-2), after the template-error vs unexplained triage (P05-01)Only worthwhile if they beat the baseline under injectionAt 0.5–1× threshold, the injected-spike recall of the Sorrel peel exceeds the KS4 rerun

Cluster scores

Two raters (R1, R2) scored each cluster independently from 1 to 5, using criteria and weights fixed before scoring:

CriterionWeight
recall0.25
speed0.20
verifiable0.15
feasibility0.15
safety0.15
novelty0.10

Each cell is the mean of the two raters. The interval spans the widest low and high either rater gave. The ranking was computed by the skill’s evaluate_matrix.py with ±20% one-at-a-time weight sensitivity.

ClusterBest memberScore [interval]Rank rangeR1 verdictPrior art (L1)
C11 Interactive speedP02-02 mergeable statistics51 [33–66]1–2advance P02-02 onlymixed
C4 Drift-fragment stitchingP01-03 shifted template × complementary presence51 [25–75]1–2advance P01-03 onlymixed (DARTsort, SpikeSift)
C10 Cross-session priorsimport UnitMatch output46 [24–71]3–4revise: import, don’t rebuildsupport (UnitMatch)
C9 Learning from the curatorP01-06 in-session active learning45 [23–68]3–4revise: drop auto-acceptmixed (UnitRefine)
C8 Hybrid injectionvirtual DataProvider overlay42 [30–58]5–7advance first (enabler)support (SI hybrid)
C5 Burst-aware split/mergeP01-04 amplitude~ISI regression41 [18–61]5–7advance (cheap)mixed (SLAy)
C1 Residual matched filterP01-01 + second-best-template margin40 [21–68]5–7revisemixed (KS4)
C2 New units from residualP03-02 lasso-scoped re-threshold38 [13–69]8–9revise; split off P03-02challenge (none located)
C3 Collision recoveryP02-10 refit only at CCG dips37 [15–66]8–9parksupport (KS4, binary pursuit)
C6 MUA density re-clusteringP01-08 recursive dip on computed PCs34 [10–68]10advance P01-08; park P01-11mixed (ISO-SPLIT)
C7 Sparse unitsP03-07 with held-out templates31 [3–58]11revise; park P04-04search incomplete

How to read this. The ranking is fragile. Every interval overlaps the others, and 9 of 11 clusters change rank under weight perturbation. The formula is compensatory, so recall clusters score low because of false-discovery risk, even though recall is half of the question. Use the verdicts and the dependency order, not the numbers.

Where the raters disagree (gap of one point or more):

ClusterCriteriaR1 vs R2
C6speed, verifiable, feasibility, safetyR1 higher on each: computed PCs make it testable
C3recall, noveltyR1 lower
C4safetyR1 higher
C10feasibilityR1 lower
C7verifiableR1 lower: double-dipping
C8safetyR1 higher

Adversarial findings (R1)

  • C1, C2: recovered spikes may belong to a neighbouring unit, and residual hotspots near large units are probably template error. Mitigations: require a margin over the second-best template; reject candidates with a zero-lag CCG peak against the parent unit; run P05-01’s refit test before hunting.

  • C4: KS4 templates are already drift-corrected, so shifting by Δz corrects twice. Fragments only appear where nonrigid drift is left over.

  • C5: an asymmetric 3–15 ms CCG is also the signature of a monosynaptic connection. Merging such a pair is a silent error (P05-02 addresses this).

  • C7: building a template from fewer than 100 spikes and scoring those same spikes is circular. Build on half A, score half B.

  • C9: speed gains may just mean the curator stopped looking (automation bias). Learning within a session and learning across sessions rest on different assumptions.

  • C11: a 1% reservoir (P02-11) cuts coincident pair counts by about 10⁴, which makes ACG and refractory-violation views meaningless. Refractory metrics must stay exact.

  • Attractive mainly because of the technology:

    IdeaMethod
    P01-11contrastive embedding
    P04-07LSH (a 1000² similarity matrix is trivial)
    P04-08SPRT (Sorrel does not assign spikes)
    P04-05kernel differencing
    P04-10sticky HMM

    Several P04 items rename existing methods: successive interference cancellation is matching pursuit, CFAR is a MAD threshold, and network coincidence is a multichannel template.

Ideas added after the evidence check

IDIdeaTarget
R1-new-1Load whitening, spike_positions.npy and KS4 drift shiftsprerequisite
R1-new-2KS4 rerun on a channel/time window at lower threshold, through the sorrel auto sidecar, as the baselinerecall (baseline)
R1-new-3Reassignment proposals for spikes whose best and second-best templates are closeprecision
R1-new-4amplitude_cutoff per time bin: which units lose spikes, and whenrecall (diagnosis)
R1-new-5Decision-time telemetry in the journalmeasuring speed
P05-01Triage residual hotspots into template error (refit with gain/shift) vs unexplainedprecision
P05-02Tag stable-latency, spatially disjoint asymmetric-CCG pairs as putative connections; block mergesprecision
P05-03Second sorter through the sidecar; queue only units the sorters disagree onrecall
P05-04Calibrate merge thresholds on the journal’s merge/reject history (selection-biased sample)precision, speed
P05-05“Stop here” line in the queue from journaled yield per minute; rare-unit flags bypass itspeed

Parked

IdeaReason
C3 collision refitMeasure the zero-lag CCG deficit on 3 KS4 sorts first; close it if under 5%
P01-11 contrastive embeddingNeeds a training stack and its own validation
P04-04 track-before-detectNo supporting evidence located
P04-05, P04-06, P04-10Heavy models for a problem a pairwise score covers
P02-11 approximate viewsBreaks exact refractory metrics
P04-07, P04-08No problem to solve at Sorrel’s scale
P02-12 compute on the remote hostRevisit once a remote GPU workload exists

Citations

L1 checked these with web search only and opened no pages. These corrections apply before anything is cited:

  • Pillow et al. 2013, PLoS One 8:e62123: authors are Pillow, Shlens, Chichilnisky and Simoncelli.
  • Chung et al. 2017, Neuron 95:1381: the title is “A Fully Automated Approach to Spike Sorting”. ISO-SPLIT is a separate Magland & Barnett paper.
  • Boussard et al. 2021, NeurIPS: “Three-dimensional spike localization and improved motion correction for Neuropixels recordings”.
  • Rossant et al. 2016, Nat. Neurosci.: hybrid ground truth was not confirmed in this paper. It is attributed to Pachitariu et al. 2016 (KiloSort, NeurIPS).
  • YASS: Lee et al. 2017, NeurIPS / bioRxiv 151928. The 2020 version is an extension.
  • DREDge: Windolf et al., Nat. Methods 2025. The DOI comes from a search summary only.

Verified as cited:

WorkVenue
Kilosort4Nat. Methods 2024
UnitMatchNat. Methods 2024
CEEDNeurIPS 2023
SpikeForesteLife 2020
Shelly 2007Nature
Yoon 2015Sci. Adv.
Alard & Lupton 1998ApJ
Adams & MacKay 2007arXiv
VBxCSL 2022
Fee 1996J. Neurosci. Methods
Hellerstein 1997SIGMOD
Bansal 2004Mach. Learn.

Not finding prior art in a bounded search does not show that an idea is novel.

Decision log

  • 2026-10-28: the user chose in-place spike addition. Implemented W1–W5 from the plan; KS4 whitening I/O, collision refit, active learning, UnitMatch import and the other pruned items were dropped as low value. New units from the residual are deferred.
  • Results:
    • incremental suggestions 5.7× faster;
    • rescue verified end to end on a CINPLA KS2 copy: 661 spikes added, phylib loads the result, arrays aligned;
    • hybrid recall varies by unit (see usage/rescue.md).
  • Open:
    • choice of null (channel shift vs sign flip);
    • low feature-calibration R²;
    • a labelled Neuropixels KS4 sort for real recall.