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

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.